Search in sources :

Example 81 with AlertDialog

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

the class ThemeActivity method didReceivedNotification.

@Override
public void didReceivedNotification(int id, int account, Object... args) {
    if (id == NotificationCenter.locationPermissionGranted) {
        updateSunTime(null, true);
    } else if (id == NotificationCenter.didSetNewWallpapper || id == NotificationCenter.emojiLoaded) {
        if (listView != null) {
            listView.invalidateViews();
        }
        updateMenuItem();
    } else if (id == NotificationCenter.themeAccentListUpdated) {
        if (listAdapter != null && themeAccentListRow != -1) {
            listAdapter.notifyItemChanged(themeAccentListRow, new Object());
        }
    } else if (id == NotificationCenter.themeListUpdated) {
        updateRows(true);
    } else if (id == NotificationCenter.themeUploadedToServer) {
        Theme.ThemeInfo themeInfo = (Theme.ThemeInfo) args[0];
        Theme.ThemeAccent accent = (Theme.ThemeAccent) args[1];
        if (themeInfo == sharingTheme && accent == sharingAccent) {
            String link = "https://" + getMessagesController().linkPrefix + "/addtheme/" + (accent != null ? accent.info.slug : themeInfo.info.slug);
            showDialog(new ShareAlert(getParentActivity(), null, link, false, link, false));
            if (sharingProgressDialog != null) {
                sharingProgressDialog.dismiss();
            }
        }
    } else if (id == NotificationCenter.themeUploadError) {
        Theme.ThemeInfo themeInfo = (Theme.ThemeInfo) args[0];
        Theme.ThemeAccent accent = (Theme.ThemeAccent) args[1];
        if (themeInfo == sharingTheme && accent == sharingAccent && sharingProgressDialog == null) {
            sharingProgressDialog.dismiss();
        }
    } else if (id == NotificationCenter.needShareTheme) {
        if (getParentActivity() == null || isPaused) {
            return;
        }
        sharingTheme = (Theme.ThemeInfo) args[0];
        sharingAccent = (Theme.ThemeAccent) args[1];
        sharingProgressDialog = new AlertDialog(getParentActivity(), 3);
        sharingProgressDialog.setCanCacnel(true);
        showDialog(sharingProgressDialog, dialog -> {
            sharingProgressDialog = null;
            sharingTheme = null;
            sharingAccent = null;
        });
    } else if (id == NotificationCenter.needSetDayNightTheme) {
        updateMenuItem();
        checkCurrentDayNight();
    } else if (id == NotificationCenter.emojiPreviewThemesChanged) {
        if (themeListRow2 >= 0) {
            listAdapter.notifyItemChanged(themeListRow2);
        }
    }
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) ShareAlert(org.telegram.ui.Components.ShareAlert) Theme(org.telegram.ui.ActionBar.Theme) DocumentObject(org.telegram.messenger.DocumentObject)

Example 82 with AlertDialog

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

the class MediaController method saveFile.

public static void saveFile(String fullPath, Context context, final int type, final String name, final String mime, final Runnable onSaved) {
    if (fullPath == null || context == null) {
        return;
    }
    File file = null;
    if (!TextUtils.isEmpty(fullPath)) {
        file = new File(fullPath);
        if (!file.exists() || AndroidUtilities.isInternalUri(Uri.fromFile(file))) {
            file = null;
        }
    }
    if (file == null) {
        return;
    }
    final File sourceFile = file;
    final boolean[] cancelled = new boolean[] { false };
    if (sourceFile.exists()) {
        AlertDialog progressDialog = null;
        final boolean[] finished = new boolean[1];
        if (context != null && type != 0) {
            try {
                final AlertDialog dialog = new AlertDialog(context, 2);
                dialog.setMessage(LocaleController.getString("Loading", R.string.Loading));
                dialog.setCanceledOnTouchOutside(false);
                dialog.setCancelable(true);
                dialog.setOnCancelListener(d -> cancelled[0] = true);
                AndroidUtilities.runOnUIThread(() -> {
                    if (!finished[0]) {
                        dialog.show();
                    }
                }, 250);
                progressDialog = dialog;
            } catch (Exception e) {
                FileLog.e(e);
            }
        }
        final AlertDialog finalProgress = progressDialog;
        new Thread(() -> {
            try {
                boolean result = true;
                if (Build.VERSION.SDK_INT >= 29) {
                    result = saveFileInternal(type, sourceFile, null);
                } else {
                    File destFile;
                    if (type == 0) {
                        destFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Telegram");
                        destFile.mkdirs();
                        destFile = new File(destFile, AndroidUtilities.generateFileName(0, FileLoader.getFileExtension(sourceFile)));
                    } else if (type == 1) {
                        destFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES), "Telegram");
                        destFile.mkdirs();
                        destFile = new File(destFile, AndroidUtilities.generateFileName(1, FileLoader.getFileExtension(sourceFile)));
                    } else {
                        File dir;
                        if (type == 2) {
                            dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                        } else {
                            dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
                        }
                        dir = new File(dir, "Telegram");
                        dir.mkdirs();
                        destFile = new File(dir, name);
                        if (destFile.exists()) {
                            int idx = name.lastIndexOf('.');
                            for (int a = 0; a < 10; a++) {
                                String newName;
                                if (idx != -1) {
                                    newName = name.substring(0, idx) + "(" + (a + 1) + ")" + name.substring(idx);
                                } else {
                                    newName = name + "(" + (a + 1) + ")";
                                }
                                destFile = new File(dir, newName);
                                if (!destFile.exists()) {
                                    break;
                                }
                            }
                        }
                    }
                    if (!destFile.exists()) {
                        destFile.createNewFile();
                    }
                    long lastProgress = System.currentTimeMillis() - 500;
                    try (FileInputStream inputStream = new FileInputStream(sourceFile);
                        FileChannel source = inputStream.getChannel();
                        FileChannel destination = new FileOutputStream(destFile).getChannel()) {
                        long size = source.size();
                        try {
                            @SuppressLint("DiscouragedPrivateApi") Method getInt = FileDescriptor.class.getDeclaredMethod("getInt$");
                            int fdint = (Integer) getInt.invoke(inputStream.getFD());
                            if (AndroidUtilities.isInternalUri(fdint)) {
                                if (finalProgress != null) {
                                    AndroidUtilities.runOnUIThread(() -> {
                                        try {
                                            finalProgress.dismiss();
                                        } catch (Exception e) {
                                            FileLog.e(e);
                                        }
                                    });
                                }
                                return;
                            }
                        } catch (Throwable e) {
                            FileLog.e(e);
                        }
                        for (long a = 0; a < size; a += 4096) {
                            if (cancelled[0]) {
                                break;
                            }
                            destination.transferFrom(source, a, Math.min(4096, size - a));
                            if (finalProgress != null) {
                                if (lastProgress <= System.currentTimeMillis() - 500) {
                                    lastProgress = System.currentTimeMillis();
                                    final int progress = (int) ((float) a / (float) size * 100);
                                    AndroidUtilities.runOnUIThread(() -> {
                                        try {
                                            finalProgress.setProgress(progress);
                                        } catch (Exception e) {
                                            FileLog.e(e);
                                        }
                                    });
                                }
                            }
                        }
                    } catch (Exception e) {
                        FileLog.e(e);
                        result = false;
                    }
                    if (cancelled[0]) {
                        destFile.delete();
                        result = false;
                    }
                    if (result) {
                        if (type == 2) {
                            DownloadManager downloadManager = (DownloadManager) ApplicationLoader.applicationContext.getSystemService(Context.DOWNLOAD_SERVICE);
                            downloadManager.addCompletedDownload(destFile.getName(), destFile.getName(), false, mime, destFile.getAbsolutePath(), destFile.length(), true);
                        } else {
                            AndroidUtilities.addMediaToGallery(destFile.getAbsoluteFile());
                        }
                    }
                }
                if (result && onSaved != null) {
                    AndroidUtilities.runOnUIThread(onSaved);
                }
            } catch (Exception e) {
                FileLog.e(e);
            }
            if (finalProgress != null) {
                AndroidUtilities.runOnUIThread(() -> {
                    try {
                        if (finalProgress.isShowing()) {
                            finalProgress.dismiss();
                        } else {
                            finished[0] = true;
                        }
                    } catch (Exception e) {
                        FileLog.e(e);
                    }
                });
            }
        }).start();
    }
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) FileChannel(java.nio.channels.FileChannel) Method(java.lang.reflect.Method) DownloadManager(android.app.DownloadManager) FileNotFoundException(java.io.FileNotFoundException) SuppressLint(android.annotation.SuppressLint) Point(android.graphics.Point) FileInputStream(java.io.FileInputStream) FileDescriptor(java.io.FileDescriptor) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 83 with AlertDialog

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

the class StickersAlert method showNameEnterAlert.

private void showNameEnterAlert() {
    Context context = getContext();
    int[] state = new int[] { 0 };
    FrameLayout fieldLayout = new FrameLayout(context);
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle(LocaleController.getString("ImportStickersEnterName", R.string.ImportStickersEnterName));
    builder.setPositiveButton(LocaleController.getString("Next", R.string.Next), (dialog, which) -> {
    });
    LinearLayout linearLayout = new LinearLayout(context);
    linearLayout.setOrientation(LinearLayout.VERTICAL);
    builder.setView(linearLayout);
    linearLayout.addView(fieldLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 36, Gravity.TOP | Gravity.LEFT, 24, 6, 24, 0));
    TextView message = new TextView(context);
    TextView textView = new TextView(context);
    textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
    textView.setTextColor(getThemedColor(Theme.key_dialogTextHint));
    textView.setMaxLines(1);
    textView.setLines(1);
    textView.setText("t.me/addstickers/");
    textView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
    textView.setGravity(Gravity.LEFT | Gravity.TOP);
    textView.setSingleLine(true);
    textView.setVisibility(View.INVISIBLE);
    textView.setImeOptions(EditorInfo.IME_ACTION_DONE);
    textView.setPadding(0, AndroidUtilities.dp(4), 0, 0);
    fieldLayout.addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 36, Gravity.TOP | Gravity.LEFT));
    EditTextBoldCursor editText = new EditTextBoldCursor(context);
    editText.setBackgroundDrawable(Theme.createEditTextDrawable(context, true));
    editText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
    editText.setTextColor(getThemedColor(Theme.key_dialogTextBlack));
    editText.setMaxLines(1);
    editText.setLines(1);
    editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
    editText.setGravity(Gravity.LEFT | Gravity.TOP);
    editText.setSingleLine(true);
    editText.setImeOptions(EditorInfo.IME_ACTION_NEXT);
    editText.setCursorColor(getThemedColor(Theme.key_windowBackgroundWhiteBlackText));
    editText.setCursorSize(AndroidUtilities.dp(20));
    editText.setCursorWidth(1.5f);
    editText.setPadding(0, AndroidUtilities.dp(4), 0, 0);
    editText.addTextChangedListener(new TextWatcher() {

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

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (state[0] != 2) {
                return;
            }
            checkUrlAvailable(message, editText.getText().toString(), false);
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });
    fieldLayout.addView(editText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 36, Gravity.TOP | Gravity.LEFT));
    editText.setOnEditorActionListener((view, i, keyEvent) -> {
        if (i == EditorInfo.IME_ACTION_NEXT) {
            builder.create().getButton(AlertDialog.BUTTON_POSITIVE).callOnClick();
            return true;
        }
        return false;
    });
    editText.setSelection(editText.length());
    builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), (dialog, which) -> AndroidUtilities.hideKeyboard(editText));
    message.setText(AndroidUtilities.replaceTags(LocaleController.getString("ImportStickersEnterNameInfo", R.string.ImportStickersEnterNameInfo)));
    message.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    message.setPadding(AndroidUtilities.dp(23), AndroidUtilities.dp(12), AndroidUtilities.dp(23), AndroidUtilities.dp(6));
    message.setTextColor(getThemedColor(Theme.key_dialogTextGray2));
    linearLayout.addView(message, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    final AlertDialog alertDialog = builder.create();
    alertDialog.setOnShowListener(dialog -> AndroidUtilities.runOnUIThread(() -> {
        editText.requestFocus();
        AndroidUtilities.showKeyboard(editText);
    }));
    alertDialog.show();
    editText.requestFocus();
    alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(v -> {
        if (state[0] == 1) {
            return;
        }
        if (state[0] == 0) {
            state[0] = 1;
            TLRPC.TL_stickers_suggestShortName req = new TLRPC.TL_stickers_suggestShortName();
            req.title = setTitle = editText.getText().toString();
            ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
                boolean set = false;
                if (response instanceof TLRPC.TL_stickers_suggestedShortName) {
                    TLRPC.TL_stickers_suggestedShortName res = (TLRPC.TL_stickers_suggestedShortName) response;
                    if (res.short_name != null) {
                        editText.setText(res.short_name);
                        editText.setSelection(0, editText.length());
                        checkUrlAvailable(message, editText.getText().toString(), true);
                        set = true;
                    }
                }
                textView.setVisibility(View.VISIBLE);
                editText.setPadding(textView.getMeasuredWidth(), AndroidUtilities.dp(4), 0, 0);
                if (!set) {
                    editText.setText("");
                }
                state[0] = 2;
            }));
        } else if (state[0] == 2) {
            state[0] = 3;
            if (!lastNameAvailable) {
                AndroidUtilities.shakeView(editText, 2, 0);
                editText.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
            }
            AndroidUtilities.hideKeyboard(editText);
            SendMessagesHelper.getInstance(currentAccount).prepareImportStickers(setTitle, lastCheckName, importingSoftware, importingStickersPaths, (param) -> {
                ImportingAlert importingAlert = new ImportingAlert(getContext(), lastCheckName, null, resourcesProvider);
                importingAlert.show();
            });
            builder.getDismissRunnable().run();
            dismiss();
        }
    });
}
Also used : Context(android.content.Context) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) ThemeDescription(org.telegram.ui.ActionBar.ThemeDescription) Rect(android.graphics.Rect) LinearLayout(android.widget.LinearLayout) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) Spannable(android.text.Spannable) Uri(android.net.Uri) FrameLayout(android.widget.FrameLayout) AndroidUtilities(org.telegram.messenger.AndroidUtilities) Animator(android.animation.Animator) LinkMovementMethod(android.text.method.LinkMovementMethod) TransitionManager(android.transition.TransitionManager) Drawable(android.graphics.drawable.Drawable) Selection(android.text.Selection) Matcher(java.util.regex.Matcher) MediaController(org.telegram.messenger.MediaController) View(android.view.View) Transition(android.transition.Transition) Emoji(org.telegram.messenger.Emoji) FileRefController(org.telegram.messenger.FileRefController) RecyclerView(androidx.recyclerview.widget.RecyclerView) Utilities(org.telegram.messenger.Utilities) ObjectAnimator(android.animation.ObjectAnimator) ImageLocation(org.telegram.messenger.ImageLocation) InputType(android.text.InputType) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) SendMessagesHelper(org.telegram.messenger.SendMessagesHelper) ConnectionsManager(org.telegram.tgnet.ConnectionsManager) ViewGroup(android.view.ViewGroup) NotificationCenter(org.telegram.messenger.NotificationCenter) SparseArray(android.util.SparseArray) HapticFeedbackConstants(android.view.HapticFeedbackConstants) List(java.util.List) TextView(android.widget.TextView) Pattern(java.util.regex.Pattern) EditorInfo(android.view.inputmethod.EditorInfo) EmptyCell(org.telegram.ui.Cells.EmptyCell) TextWatcher(android.text.TextWatcher) FileLoader(org.telegram.messenger.FileLoader) ChatActivity(org.telegram.ui.ChatActivity) Context(android.content.Context) GridLayoutManager(androidx.recyclerview.widget.GridLayoutManager) FeaturedStickerSetInfoCell(org.telegram.ui.Cells.FeaturedStickerSetInfoCell) Theme(org.telegram.ui.ActionBar.Theme) RequestDelegate(org.telegram.tgnet.RequestDelegate) LocaleController(org.telegram.messenger.LocaleController) HashMap(java.util.HashMap) Editable(android.text.Editable) ArrayList(java.util.ArrayList) SuppressLint(android.annotation.SuppressLint) SpannableStringBuilder(android.text.SpannableStringBuilder) MotionEvent(android.view.MotionEvent) TLRPC(org.telegram.tgnet.TLRPC) TransitionValues(android.transition.TransitionValues) Toast(android.widget.Toast) TLObject(org.telegram.tgnet.TLObject) AnimatorSet(android.animation.AnimatorSet) MessageObject(org.telegram.messenger.MessageObject) MediaDataController(org.telegram.messenger.MediaDataController) Build(android.os.Build) StickerEmojiCell(org.telegram.ui.Cells.StickerEmojiCell) Parcelable(android.os.Parcelable) R(org.telegram.messenger.R) BottomSheet(org.telegram.ui.ActionBar.BottomSheet) ContentPreviewViewer(org.telegram.ui.ContentPreviewViewer) TextUtils(android.text.TextUtils) FileLog(org.telegram.messenger.FileLog) File(java.io.File) MessagesController(org.telegram.messenger.MessagesController) Gravity(android.view.Gravity) android.graphics(android.graphics) TypedValue(android.util.TypedValue) Activity(android.app.Activity) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) ValueAnimator(android.animation.ValueAnimator) SpannableStringBuilder(android.text.SpannableStringBuilder) SuppressLint(android.annotation.SuppressLint) TLRPC(org.telegram.tgnet.TLRPC) FrameLayout(android.widget.FrameLayout) TextWatcher(android.text.TextWatcher) Editable(android.text.Editable) TextView(android.widget.TextView) LinearLayout(android.widget.LinearLayout)

Example 84 with AlertDialog

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

the class ChatActivity method didPressMessageUrl.

private void didPressMessageUrl(CharacterStyle url, boolean longPress, MessageObject messageObject, ChatMessageCell cell) {
    if (url == null || getParentActivity() == null) {
        return;
    }
    boolean noforwards = getMessagesController().isChatNoForwards(currentChat) || (messageObject != null && messageObject.messageOwner != null && messageObject.messageOwner.noforwards);
    if (url instanceof URLSpanMono) {
        if (!noforwards) {
            ((URLSpanMono) url).copyToClipboard();
            getUndoView().showWithAction(0, UndoView.ACTION_TEXT_COPIED, null);
        }
    } else if (url instanceof URLSpanUserMention) {
        TLRPC.User user = getMessagesController().getUser(Utilities.parseLong(((URLSpanUserMention) url).getURL()));
        if (user != null) {
            MessagesController.openChatOrProfileWith(user, null, ChatActivity.this, 0, false);
        }
    } else if (url instanceof URLSpanNoUnderline) {
        String str = ((URLSpanNoUnderline) url).getURL();
        if (messageObject != null && str.startsWith("/")) {
            if (URLSpanBotCommand.enabled) {
                chatActivityEnterView.setCommand(messageObject, str, longPress, currentChat != null && currentChat.megagroup);
                if (!longPress && chatActivityEnterView.getFieldText() == null) {
                    hideFieldPanel(false);
                }
            }
        } else if (messageObject != null && str.startsWith("video") && !longPress) {
            int seekTime = Utilities.parseInt(str);
            TLRPC.WebPage webPage;
            if (messageObject.isYouTubeVideo()) {
                webPage = messageObject.messageOwner.media.webpage;
            } else if (messageObject.replyMessageObject != null && messageObject.replyMessageObject.isYouTubeVideo()) {
                webPage = messageObject.replyMessageObject.messageOwner.media.webpage;
                messageObject = messageObject.replyMessageObject;
            } else {
                webPage = null;
            }
            if (webPage != null) {
                EmbedBottomSheet.show(getParentActivity(), messageObject, photoViewerProvider, webPage.site_name, webPage.title, webPage.url, webPage.embed_url, webPage.embed_width, webPage.embed_height, seekTime, isKeyboardVisible());
            } else {
                if (!messageObject.isVideo() && messageObject.replyMessageObject != null) {
                    MessageObject obj = messagesDict[messageObject.replyMessageObject.getDialogId() == dialog_id ? 0 : 1].get(messageObject.replyMessageObject.getId());
                    cell = null;
                    if (obj == null) {
                        messageObject = messageObject.replyMessageObject;
                    } else {
                        messageObject = obj;
                    }
                }
                messageObject.forceSeekTo = seekTime / (float) messageObject.getDuration();
                openPhotoViewerForMessage(cell, messageObject);
            }
        } else if (messageObject != null && str.startsWith("audio")) {
            int seekTime = Utilities.parseInt(str);
            if (!messageObject.isMusic() && messageObject.replyMessageObject != null) {
                messageObject = messagesDict[messageObject.replyMessageObject.getDialogId() == dialog_id ? 0 : 1].get(messageObject.replyMessageObject.getId());
            }
            float progress = seekTime / (float) messageObject.getDuration();
            MediaController mediaController = getMediaController();
            if (mediaController.isPlayingMessage(messageObject)) {
                messageObject.audioProgress = progress;
                mediaController.seekToProgress(messageObject, progress);
                if (mediaController.isMessagePaused()) {
                    mediaController.playMessage(messageObject);
                }
            } else {
                messageObject.forceSeekTo = seekTime / (float) messageObject.getDuration();
                mediaController.playMessage(messageObject);
            }
        } else if (str.startsWith("card:")) {
            String number = str.substring(5);
            final AlertDialog[] progressDialog = new AlertDialog[] { new AlertDialog(getParentActivity(), 3, themeDelegate) };
            TLRPC.TL_payments_getBankCardData req = new TLRPC.TL_payments_getBankCardData();
            req.number = number;
            int requestId = getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
                try {
                    progressDialog[0].dismiss();
                } catch (Throwable ignore) {
                }
                progressDialog[0] = null;
                if (response instanceof TLRPC.TL_payments_bankCardData) {
                    if (getParentActivity() == null) {
                        return;
                    }
                    TLRPC.TL_payments_bankCardData data = (TLRPC.TL_payments_bankCardData) response;
                    BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity(), false, themeDelegate);
                    ArrayList<CharSequence> arrayList = new ArrayList<>();
                    for (int a = 0, N = data.open_urls.size(); a < N; a++) {
                        arrayList.add(data.open_urls.get(a).name);
                    }
                    arrayList.add(LocaleController.getString("CopyCardNumber", R.string.CopyCardNumber));
                    builder.setTitle(data.title);
                    builder.setItems(arrayList.toArray(new CharSequence[0]), (dialog, which) -> {
                        if (which < data.open_urls.size()) {
                            Browser.openUrl(getParentActivity(), data.open_urls.get(which).url, inlineReturn == 0, false);
                        } else {
                            AndroidUtilities.addToClipboard(number);
                            Toast.makeText(ApplicationLoader.applicationContext, LocaleController.getString("CardNumberCopied", R.string.CardNumberCopied), Toast.LENGTH_SHORT).show();
                        }
                    });
                    showDialog(builder.create());
                }
            }), null, null, 0, getMessagesController().webFileDatacenterId, ConnectionsManager.ConnectionTypeGeneric, true);
            AndroidUtilities.runOnUIThread(() -> {
                if (progressDialog[0] == null) {
                    return;
                }
                progressDialog[0].setOnCancelListener(dialog -> getConnectionsManager().cancelRequest(requestId, true));
                showDialog(progressDialog[0]);
            }, 500);
        } else {
            if (longPress) {
                BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity(), false, themeDelegate);
                int timestamp = -1;
                if (str.startsWith("video?")) {
                    timestamp = Utilities.parseInt(str);
                }
                if (timestamp >= 0) {
                    builder.setTitle(AndroidUtilities.formatDuration(timestamp, false));
                } else {
                    builder.setTitle(str);
                }
                final int finalTimestamp = timestamp;
                ChatMessageCell finalCell = cell;
                MessageObject finalMessageObject = messageObject;
                builder.setItems(noforwards ? new CharSequence[] { LocaleController.getString("Open", R.string.Open) } : new CharSequence[] { LocaleController.getString("Open", R.string.Open), LocaleController.getString("Copy", R.string.Copy) }, (dialog, which) -> {
                    if (which == 0) {
                        if (str.startsWith("video?")) {
                            didPressMessageUrl(url, false, finalMessageObject, finalCell);
                        } else {
                            openClickableLink(str);
                        }
                    } else if (which == 1) {
                        if (str.startsWith("video?") && finalMessageObject != null && !finalMessageObject.scheduled) {
                            MessageObject messageObject1 = finalMessageObject;
                            boolean isMedia = finalMessageObject.isVideo() || finalMessageObject.isRoundVideo() || finalMessageObject.isVoice() || finalMessageObject.isMusic();
                            if (!isMedia && finalMessageObject.replyMessageObject != null) {
                                messageObject1 = finalMessageObject.replyMessageObject;
                            }
                            long dialogId = messageObject1.getDialogId();
                            int messageId = messageObject1.getId();
                            String link = null;
                            if (messageObject1.messageOwner.fwd_from != null) {
                                if (messageObject1.messageOwner.fwd_from.saved_from_peer != null) {
                                    dialogId = MessageObject.getPeerId(messageObject1.messageOwner.fwd_from.saved_from_peer);
                                    messageId = messageObject1.messageOwner.fwd_from.saved_from_msg_id;
                                } else if (messageObject1.messageOwner.fwd_from.from_id != null) {
                                    dialogId = MessageObject.getPeerId(messageObject1.messageOwner.fwd_from.from_id);
                                    messageId = messageObject1.messageOwner.fwd_from.channel_post;
                                }
                            }
                            if (DialogObject.isChatDialog(dialogId)) {
                                TLRPC.Chat currentChat = MessagesController.getInstance(currentAccount).getChat(-dialogId);
                                if (currentChat != null && currentChat.username != null) {
                                    link = "https://t.me/" + currentChat.username + "/" + messageId + "?t=" + finalTimestamp;
                                }
                            } else {
                                TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(dialogId);
                                if (user != null && user.username != null) {
                                    link = "https://t.me/" + user.username + "/" + messageId + "?t=" + finalTimestamp;
                                }
                            }
                            if (link == null) {
                                return;
                            }
                            AndroidUtilities.addToClipboard(link);
                        } else {
                            AndroidUtilities.addToClipboard(str);
                        }
                        if (str.startsWith("@")) {
                            undoView.showWithAction(0, UndoView.ACTION_USERNAME_COPIED, null);
                        } else if (str.startsWith("#") || str.startsWith("$")) {
                            undoView.showWithAction(0, UndoView.ACTION_HASHTAG_COPIED, null);
                        } else {
                            undoView.showWithAction(0, UndoView.ACTION_LINK_COPIED, null);
                        }
                    }
                });
                showDialog(builder.create());
            } else {
                openClickableLink(str);
            }
        }
    } else {
        final String urlFinal = ((URLSpan) url).getURL();
        if (longPress) {
            BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity(), false, themeDelegate);
            builder.setTitle(urlFinal);
            builder.setItems(noforwards ? new CharSequence[] { LocaleController.getString("Open", R.string.Open) } : new CharSequence[] { LocaleController.getString("Open", R.string.Open), LocaleController.getString("Copy", R.string.Copy) }, (dialog, which) -> {
                if (which == 0) {
                    processExternalUrl(1, urlFinal, false);
                } else if (which == 1) {
                    String url1 = urlFinal;
                    boolean tel = false;
                    boolean mail = false;
                    if (url1.startsWith("mailto:")) {
                        url1 = url1.substring(7);
                        mail = true;
                    } else if (url1.startsWith("tel:")) {
                        url1 = url1.substring(4);
                        tel = true;
                    }
                    AndroidUtilities.addToClipboard(url1);
                    if (mail) {
                        undoView.showWithAction(0, UndoView.ACTION_EMAIL_COPIED, null);
                    } else if (tel) {
                        undoView.showWithAction(0, UndoView.ACTION_PHONE_COPIED, null);
                    } else {
                        undoView.showWithAction(0, UndoView.ACTION_LINK_COPIED, null);
                    }
                }
            });
            showDialog(builder.create());
        } else {
            boolean forceAlert = url instanceof URLSpanReplacement;
            if (url instanceof URLSpanReplacement && (urlFinal == null || !urlFinal.startsWith("mailto:")) || AndroidUtilities.shouldShowUrlInAlert(urlFinal)) {
                if (openLinkInternally(urlFinal, messageObject != null ? messageObject.getId() : 0)) {
                    return;
                }
                forceAlert = true;
            } else {
                if (messageObject != null && messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage && messageObject.messageOwner.media.webpage != null && messageObject.messageOwner.media.webpage.cached_page != null) {
                    String lowerUrl = urlFinal.toLowerCase();
                    String lowerUrl2 = messageObject.messageOwner.media.webpage.url.toLowerCase();
                    if ((lowerUrl.contains("telegram.org/blog") || Browser.isTelegraphUrl(lowerUrl, false) || lowerUrl.contains("t.me/iv")) && (lowerUrl.contains(lowerUrl2) || lowerUrl2.contains(lowerUrl))) {
                        ArticleViewer.getInstance().setParentActivity(getParentActivity(), ChatActivity.this);
                        ArticleViewer.getInstance().open(messageObject);
                        return;
                    }
                }
                if (openLinkInternally(urlFinal, messageObject != null ? messageObject.getId() : 0)) {
                    return;
                }
            }
            if (Browser.urlMustNotHaveConfirmation(urlFinal)) {
                forceAlert = false;
            }
            processExternalUrl(2, urlFinal, forceAlert);
        }
    }
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) ViewHelper(org.telegram.ui.Components.ViewHelper) Bundle(android.os.Bundle) BotHelpCell(org.telegram.ui.Cells.BotHelpCell) AdjustPanLayoutHelper(org.telegram.ui.ActionBar.AdjustPanLayoutHelper) StickersAlert(org.telegram.ui.Components.StickersAlert) RecyclerAnimationScrollHelper(org.telegram.ui.Components.RecyclerAnimationScrollHelper) URLSpanUserMention(org.telegram.ui.Components.URLSpanUserMention) Property(android.util.Property) HorizontalScrollView(android.widget.HorizontalScrollView) ChatThemeController(org.telegram.messenger.ChatThemeController) MediaStore(android.provider.MediaStore) Map(java.util.Map) Shader(android.graphics.Shader) ContextCompat(androidx.core.content.ContextCompat) NotificationCenter(org.telegram.messenger.NotificationCenter) PinnedLineView(org.telegram.ui.Components.PinnedLineView) CountDownLatch(java.util.concurrent.CountDownLatch) Layout(android.text.Layout) EmojiData(org.telegram.messenger.EmojiData) ForwardingMessagesParams(org.telegram.messenger.ForwardingMessagesParams) BotCommandsMenuView(org.telegram.ui.Components.BotCommandsMenuView) Paint(android.graphics.Paint) Path(android.graphics.Path) ReactedHeaderView(org.telegram.ui.Components.ReactedHeaderView) PipRoundVideoView(org.telegram.ui.Components.PipRoundVideoView) SystemClock(android.os.SystemClock) ChatBlurredFrameLayout(org.telegram.ui.Components.ChatBlurredFrameLayout) SpannableStringBuilder(android.text.SpannableStringBuilder) Calendar(java.util.Calendar) Toast(android.widget.Toast) PhoneFormat(org.telegram.PhoneFormat.PhoneFormat) Menu(android.view.Menu) SizeNotifierFrameLayout(org.telegram.ui.Components.SizeNotifierFrameLayout) JoinGroupAlert(org.telegram.ui.Components.JoinGroupAlert) AspectRatioFrameLayout(com.google.android.exoplayer2.ui.AspectRatioFrameLayout) LongSparseIntArray(org.telegram.messenger.support.LongSparseIntArray) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) URLSpan(android.text.style.URLSpan) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) R(org.telegram.messenger.R) BottomSheet(org.telegram.ui.ActionBar.BottomSheet) ChatActivityMemberRequestsDelegate(org.telegram.ui.Delegates.ChatActivityMemberRequestsDelegate) UserObject(org.telegram.messenger.UserObject) SharedPreferences(android.content.SharedPreferences) ContactsController(org.telegram.messenger.ContactsController) MessagesStorage(org.telegram.messenger.MessagesStorage) EditText(android.widget.EditText) Rect(android.graphics.Rect) LinearLayout(android.widget.LinearLayout) URLDecoder(java.net.URLDecoder) PackageManager(android.content.pm.PackageManager) WindowManager(android.view.WindowManager) Animator(android.animation.Animator) TypefaceSpan(org.telegram.ui.Components.TypefaceSpan) ChatAttachAlertDocumentLayout(org.telegram.ui.Components.ChatAttachAlertDocumentLayout) DatePickerDialog(android.app.DatePickerDialog) ChatMessageCell(org.telegram.ui.Cells.ChatMessageCell) RecyclerView(androidx.recyclerview.widget.RecyclerView) StickersAdapter(org.telegram.ui.Adapters.StickersAdapter) RectF(android.graphics.RectF) ReportAlert(org.telegram.ui.Components.ReportAlert) TextSelectionHint(org.telegram.ui.Components.TextSelectionHint) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) ChatActionCell(org.telegram.ui.Cells.ChatActionCell) ChatThemeBottomSheet(org.telegram.ui.Components.ChatThemeBottomSheet) PorterDuff(android.graphics.PorterDuff) SendMessagesHelper(org.telegram.messenger.SendMessagesHelper) BackDrawable(org.telegram.ui.ActionBar.BackDrawable) ShareAlert(org.telegram.ui.Components.ShareAlert) BluredView(org.telegram.ui.Components.BluredView) UserConfig(org.telegram.messenger.UserConfig) TextStyleSpan(org.telegram.ui.Components.TextStyleSpan) EmojiThemes(org.telegram.ui.ActionBar.EmojiThemes) InstantCameraView(org.telegram.ui.Components.InstantCameraView) PhonebookShareAlert(org.telegram.ui.Components.PhonebookShareAlert) ChatActivityEnterView(org.telegram.ui.Components.ChatActivityEnterView) ImportingAlert(org.telegram.ui.Components.ImportingAlert) Spanned(android.text.Spanned) GridLayoutManager(androidx.recyclerview.widget.GridLayoutManager) SparseIntArray(android.util.SparseIntArray) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) LocaleController(org.telegram.messenger.LocaleController) ChatActivityEnterTopView(org.telegram.ui.Components.ChatActivityEnterTopView) ExtendedGridLayoutManager(org.telegram.ui.Components.ExtendedGridLayoutManager) ChatBigEmptyView(org.telegram.ui.Components.ChatBigEmptyView) ActionBar(org.telegram.ui.ActionBar.ActionBar) LinearSmoothScrollerCustom(androidx.recyclerview.widget.LinearSmoothScrollerCustom) TLObject(org.telegram.tgnet.TLObject) Size(org.telegram.ui.Components.Size) MessageObject(org.telegram.messenger.MessageObject) SharedConfig(org.telegram.messenger.SharedConfig) BuildVars(org.telegram.messenger.BuildVars) Build(android.os.Build) ChatAvatarContainer(org.telegram.ui.Components.ChatAvatarContainer) PollVotesAlert(org.telegram.ui.Components.PollVotesAlert) EmbedBottomSheet(org.telegram.ui.Components.EmbedBottomSheet) DialogObject(org.telegram.messenger.DialogObject) BackupImageView(org.telegram.ui.Components.BackupImageView) LayoutHelper(org.telegram.ui.Components.LayoutHelper) TextureView(android.view.TextureView) Color(android.graphics.Color) Bitmap(android.graphics.Bitmap) CharacterStyle(android.text.style.CharacterStyle) ViewTreeObserver(android.view.ViewTreeObserver) Vibrator(android.os.Vibrator) Comparator(java.util.Comparator) Activity(android.app.Activity) ImageReceiver(org.telegram.messenger.ImageReceiver) RecyclerListView(org.telegram.ui.Components.RecyclerListView) Arrays(java.util.Arrays) Uri(android.net.Uri) FrameLayout(android.widget.FrameLayout) ImageView(android.widget.ImageView) AnimatedFileDrawable(org.telegram.ui.Components.AnimatedFileDrawable) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) Drawable(android.graphics.drawable.Drawable) Bulletin(org.telegram.ui.Components.Bulletin) RadialProgressView(org.telegram.ui.Components.RadialProgressView) Manifest(android.Manifest) ActionBarMenuSubItem(org.telegram.ui.ActionBar.ActionBarMenuSubItem) Matcher(java.util.regex.Matcher) ChatGreetingsView(org.telegram.ui.Components.ChatGreetingsView) Canvas(android.graphics.Canvas) AccessibilityEvent(android.view.accessibility.AccessibilityEvent) Emoji(org.telegram.messenger.Emoji) MessagesSearchAdapter(org.telegram.ui.Adapters.MessagesSearchAdapter) ColorMatrix(android.graphics.ColorMatrix) ForegroundColorSpan(android.text.style.ForegroundColorSpan) TargetApi(android.annotation.TargetApi) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) BackButtonMenu(org.telegram.ui.Components.BackButtonMenu) ChatListItemAnimator(androidx.recyclerview.widget.ChatListItemAnimator) MentionsAdapter(org.telegram.ui.Adapters.MentionsAdapter) UndoView(org.telegram.ui.Components.UndoView) AnimationProperties(org.telegram.ui.Components.AnimationProperties) ColorMatrixColorFilter(android.graphics.ColorMatrixColorFilter) CounterView(org.telegram.ui.Components.CounterView) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) TrendingStickersAlert(org.telegram.ui.Components.TrendingStickersAlert) Outline(android.graphics.Outline) HapticFeedbackConstants(android.view.HapticFeedbackConstants) TextPaint(android.text.TextPaint) BotSwitchCell(org.telegram.ui.Cells.BotSwitchCell) HintView(org.telegram.ui.Components.HintView) MessageBackgroundDrawable(org.telegram.ui.Components.MessageBackgroundDrawable) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) URLSpanBotCommand(org.telegram.ui.Components.URLSpanBotCommand) ReactionsLayoutInBubble(org.telegram.ui.Components.Reactions.ReactionsLayoutInBubble) ExifInterface(androidx.exifinterface.media.ExifInterface) FileLoader(org.telegram.messenger.FileLoader) ContextLinkCell(org.telegram.ui.Cells.ContextLinkCell) ClearHistoryAlert(org.telegram.ui.Components.ClearHistoryAlert) Space(android.widget.Space) ViewPager(androidx.viewpager.widget.ViewPager) Dialog(android.app.Dialog) BitmapFactory(android.graphics.BitmapFactory) GigagroupConvertAlert(org.telegram.ui.Components.GigagroupConvertAlert) URLSpanMono(org.telegram.ui.Components.URLSpanMono) URLSpanNoUnderline(org.telegram.ui.Components.URLSpanNoUnderline) AlertsCreator(org.telegram.ui.Components.AlertsCreator) BlurBehindDrawable(org.telegram.ui.Components.BlurBehindDrawable) ArrayList(java.util.ArrayList) SharedMediaLayout(org.telegram.ui.Components.SharedMediaLayout) FragmentContextView(org.telegram.ui.Components.FragmentContextView) TLRPC(org.telegram.tgnet.TLRPC) EditTextCaption(org.telegram.ui.Components.EditTextCaption) BuildConfig(org.telegram.messenger.BuildConfig) DialogCell(org.telegram.ui.Cells.DialogCell) SpannableString(android.text.SpannableString) BufferedWriter(java.io.BufferedWriter) FileOutputStream(java.io.FileOutputStream) TextUtils(android.text.TextUtils) ChatUnreadCell(org.telegram.ui.Cells.ChatUnreadCell) ChatLoadingCell(org.telegram.ui.Cells.ChatLoadingCell) ClippingImageView(org.telegram.ui.Components.ClippingImageView) File(java.io.File) ReactionsEffectOverlay(org.telegram.ui.Components.Reactions.ReactionsEffectOverlay) Gravity(android.view.Gravity) PorterDuffXfermode(android.graphics.PorterDuffXfermode) TypedValue(android.util.TypedValue) Configuration(android.content.res.Configuration) StickerCell(org.telegram.ui.Cells.StickerCell) ReactionsContainerLayout(org.telegram.ui.Components.ReactionsContainerLayout) ColorUtils(androidx.core.graphics.ColorUtils) ChatObject(org.telegram.messenger.ChatObject) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) VoIPHelper(org.telegram.ui.Components.voip.VoIPHelper) EmojiView(org.telegram.ui.Components.EmojiView) ValueAnimator(android.animation.ValueAnimator) ThemeDescription(org.telegram.ui.ActionBar.ThemeDescription) ChatScrimPopupContainerLayout(org.telegram.ui.Components.ChatScrimPopupContainerLayout) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) Spannable(android.text.Spannable) AccountInstance(org.telegram.messenger.AccountInstance) AndroidUtilities(org.telegram.messenger.AndroidUtilities) CubicBezierInterpolator(org.telegram.ui.Components.CubicBezierInterpolator) CheckBoxCell(org.telegram.ui.Cells.CheckBoxCell) ApplicationLoader(org.telegram.messenger.ApplicationLoader) ChecksHintView(org.telegram.ui.Components.ChecksHintView) MediaController(org.telegram.messenger.MediaController) ThemeEditorView(org.telegram.ui.Components.ThemeEditorView) View(android.view.View) Matrix(android.graphics.Matrix) SearchCounterView(org.telegram.ui.Components.SearchCounterView) ForwardingPreviewView(org.telegram.ui.Components.ForwardingPreviewView) BitmapShader(android.graphics.BitmapShader) Utilities(org.telegram.messenger.Utilities) HideViewAfterAnimation(org.telegram.ui.Components.HideViewAfterAnimation) ObjectAnimator(android.animation.ObjectAnimator) GridLayoutManagerFixed(androidx.recyclerview.widget.GridLayoutManagerFixed) ImageLocation(org.telegram.messenger.ImageLocation) MentionCell(org.telegram.ui.Cells.MentionCell) ReactionTabHolderView(org.telegram.ui.Components.ReactionTabHolderView) ConnectionsManager(org.telegram.tgnet.ConnectionsManager) ViewGroup(android.view.ViewGroup) SparseArray(android.util.SparseArray) List(java.util.List) TextView(android.widget.TextView) MotionBackgroundDrawable(org.telegram.ui.Components.MotionBackgroundDrawable) SecretChatHelper(org.telegram.messenger.SecretChatHelper) FileProvider(androidx.core.content.FileProvider) Pattern(java.util.regex.Pattern) DecelerateInterpolator(android.view.animation.DecelerateInterpolator) ActionBarPopupWindow(org.telegram.ui.ActionBar.ActionBarPopupWindow) Typeface(android.graphics.Typeface) Context(android.content.Context) StaticLayout(android.text.StaticLayout) AccessibilityNodeInfo(android.view.accessibility.AccessibilityNodeInfo) TextSelectionHelper(org.telegram.ui.Cells.TextSelectionHelper) ReactedUsersListView(org.telegram.ui.Components.ReactedUsersListView) KeyEvent(android.view.KeyEvent) VoIPService(org.telegram.messenger.voip.VoIPService) Theme(org.telegram.ui.ActionBar.Theme) PagerAdapter(androidx.viewpager.widget.PagerAdapter) ViewOutlineProvider(android.view.ViewOutlineProvider) BulletinFactory(org.telegram.ui.Components.BulletinFactory) Intent(android.content.Intent) HashMap(java.util.HashMap) ActionBarLayout(org.telegram.ui.ActionBar.ActionBarLayout) TranslateAlert(org.telegram.ui.Components.TranslateAlert) AtomicReference(java.util.concurrent.atomic.AtomicReference) ClipData(android.content.ClipData) SuppressLint(android.annotation.SuppressLint) VideoEditedInfo(org.telegram.messenger.VideoEditedInfo) MotionEvent(android.view.MotionEvent) AnimatorSet(android.animation.AnimatorSet) MediaDataController(org.telegram.messenger.MediaDataController) DialogInterface(android.content.DialogInterface) Browser(org.telegram.messenger.browser.Browser) FireworksOverlay(org.telegram.ui.Components.FireworksOverlay) LongSparseArray(androidx.collection.LongSparseArray) FileWriter(java.io.FileWriter) FileLog(org.telegram.messenger.FileLog) URLSpanReplacement(org.telegram.ui.Components.URLSpanReplacement) MessagesController(org.telegram.messenger.MessagesController) NumberTextView(org.telegram.ui.Components.NumberTextView) ChatAttachAlert(org.telegram.ui.Components.ChatAttachAlert) InviteMembersBottomSheet(org.telegram.ui.Components.InviteMembersBottomSheet) Collections(java.util.Collections) RLottieDrawable(org.telegram.ui.Components.RLottieDrawable) InputStream(java.io.InputStream) MediaController(org.telegram.messenger.MediaController) URLSpanMono(org.telegram.ui.Components.URLSpanMono) SpannableStringBuilder(android.text.SpannableStringBuilder) ArrayList(java.util.ArrayList) SpannableString(android.text.SpannableString) URLSpan(android.text.style.URLSpan) TLRPC(org.telegram.tgnet.TLRPC) URLSpanNoUnderline(org.telegram.ui.Components.URLSpanNoUnderline) Paint(android.graphics.Paint) TextSelectionHint(org.telegram.ui.Components.TextSelectionHint) TextPaint(android.text.TextPaint) SuppressLint(android.annotation.SuppressLint) ChatMessageCell(org.telegram.ui.Cells.ChatMessageCell) URLSpanUserMention(org.telegram.ui.Components.URLSpanUserMention) BottomSheet(org.telegram.ui.ActionBar.BottomSheet) ChatThemeBottomSheet(org.telegram.ui.Components.ChatThemeBottomSheet) EmbedBottomSheet(org.telegram.ui.Components.EmbedBottomSheet) InviteMembersBottomSheet(org.telegram.ui.Components.InviteMembersBottomSheet) MessageObject(org.telegram.messenger.MessageObject) URLSpanReplacement(org.telegram.ui.Components.URLSpanReplacement)

Example 85 with AlertDialog

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

the class ChatActivity method scrollToMessageId.

public void scrollToMessageId(int id, int fromMessageId, boolean select, int loadIndex, boolean forceScroll, int forcePinnedMessageId) {
    if (id == 0 || NotificationCenter.getInstance(currentAccount).isAnimationInProgress() || getParentActivity() == null) {
        if (NotificationCenter.getInstance(currentAccount).isAnimationInProgress()) {
            nextScrollToMessageId = id;
            nextScrollFromMessageId = fromMessageId;
            nextScrollSelect = select;
            nextScrollLoadIndex = loadIndex;
            nextScrollForce = forceScroll;
            nextScrollForcePinnedMessageId = forcePinnedMessageId;
            NotificationCenter.getInstance(currentAccount).doOnIdle(() -> {
                if (nextScrollToMessageId != 0) {
                    scrollToMessageId(nextScrollToMessageId, nextScrollFromMessageId, nextScrollSelect, nextScrollLoadIndex, nextScrollForce, nextScrollForcePinnedMessageId);
                    nextScrollToMessageId = 0;
                }
            });
        }
        return;
    }
    forceNextPinnedMessageId = Math.abs(forcePinnedMessageId);
    forceScrollToFirst = forcePinnedMessageId > 0;
    wasManualScroll = true;
    MessageObject object = messagesDict[loadIndex].get(id);
    boolean query = false;
    int scrollDirection = RecyclerAnimationScrollHelper.SCROLL_DIRECTION_UNSET;
    int scrollFromIndex = 0;
    if (fromMessageId != 0) {
        boolean scrollDown = fromMessageId < id;
        if (isSecretChat()) {
            scrollDown = !scrollDown;
        }
        scrollDirection = scrollDown ? RecyclerAnimationScrollHelper.SCROLL_DIRECTION_DOWN : RecyclerAnimationScrollHelper.SCROLL_DIRECTION_UP;
    } else if (messages.size() > 0) {
        if (isThreadChat() && id == threadMessageId) {
            scrollDirection = RecyclerAnimationScrollHelper.SCROLL_DIRECTION_UP;
        } else {
            int end = chatLayoutManager.findLastVisibleItemPosition();
            for (int i = chatLayoutManager.findFirstVisibleItemPosition(); i <= end; i++) {
                if (i >= chatAdapter.messagesStartRow && i <= chatAdapter.messagesEndRow) {
                    MessageObject messageObject = messages.get(i - chatAdapter.messagesStartRow);
                    if (messageObject.getId() == 0) {
                        continue;
                    }
                    scrollFromIndex = i - chatAdapter.messagesStartRow;
                    boolean scrollDown = messageObject.getId() < id;
                    if (isSecretChat()) {
                        scrollDown = !scrollDown;
                    }
                    scrollDirection = scrollDown ? RecyclerAnimationScrollHelper.SCROLL_DIRECTION_DOWN : RecyclerAnimationScrollHelper.SCROLL_DIRECTION_UP;
                    break;
                }
            }
        }
    }
    chatScrollHelper.setScrollDirection(scrollDirection);
    if (object != null) {
        MessageObject.GroupedMessages groupedMessages = groupedMessagesMap.get(object.getGroupId());
        if (object.getGroupId() != 0 && groupedMessages != null) {
            MessageObject primary = groupedMessages.findPrimaryMessageObject();
            if (primary != null) {
                object = primary;
            }
        }
        int index = messages.indexOf(object);
        if (index != -1) {
            if (scrollFromIndex > 0) {
                scrollDirection = scrollFromIndex > index ? RecyclerAnimationScrollHelper.SCROLL_DIRECTION_DOWN : RecyclerAnimationScrollHelper.SCROLL_DIRECTION_UP;
                chatScrollHelper.setScrollDirection(scrollDirection);
            }
            removeSelectedMessageHighlight();
            if (select) {
                highlightMessageId = id;
            }
            chatAdapter.updateRowsSafe();
            int position = chatAdapter.messagesStartRow + messages.indexOf(object);
            updateVisibleRows();
            boolean found = false;
            int count = chatListView.getChildCount();
            for (int a = 0; a < count; a++) {
                View view = chatListView.getChildAt(a);
                if (view instanceof ChatMessageCell) {
                    ChatMessageCell cell = (ChatMessageCell) view;
                    MessageObject messageObject = cell.getMessageObject();
                    if (messageObject != null && messageObject.getId() == object.getId()) {
                        found = true;
                        view.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
                    }
                } else if (view instanceof ChatActionCell) {
                    ChatActionCell cell = (ChatActionCell) view;
                    MessageObject messageObject = cell.getMessageObject();
                    if (messageObject != null && messageObject.getId() == object.getId()) {
                        found = true;
                        view.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
                    }
                }
                if (found) {
                    int yOffset = getScrollOffsetForMessage(object);
                    int scrollY = (int) (view.getTop() - chatListViewPaddingTop - yOffset);
                    int maxScrollOffset = chatListView.computeVerticalScrollRange() - chatListView.computeVerticalScrollOffset() - chatListView.computeVerticalScrollExtent();
                    if (maxScrollOffset < 0)
                        maxScrollOffset = 0;
                    if (scrollY > maxScrollOffset) {
                        scrollY = maxScrollOffset;
                    }
                    if (scrollY != 0) {
                        scrollByTouch = false;
                        chatListView.smoothScrollBy(0, scrollY);
                        chatListView.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER);
                    }
                    break;
                }
            }
            if (!found) {
                int yOffset = getScrollOffsetForMessage(object);
                chatScrollHelperCallback.scrollTo = object;
                chatScrollHelperCallback.lastBottom = false;
                chatScrollHelperCallback.lastItemOffset = yOffset;
                chatScrollHelperCallback.lastPadding = (int) chatListViewPaddingTop;
                chatScrollHelper.setScrollDirection(scrollDirection);
                chatScrollHelper.scrollToPosition(position, yOffset, false, true);
                canShowPagedownButton = true;
                updatePagedownButtonVisibility(true);
            }
        } else {
            query = true;
        }
    } else {
        query = true;
    }
    if (query) {
        if (isThreadChat() && id == threadMessageId) {
            scrollToThreadMessage = true;
            id = 1;
        }
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        showPinnedProgress(forceNextPinnedMessageId != 0);
        progressDialog = new AlertDialog(getParentActivity(), 3, themeDelegate);
        progressDialog.setOnShowListener(dialogInterface -> showPinnedProgress(false));
        progressDialog.setOnCancelListener(postponedScrollCancelListener);
        progressDialog.showDelayed(400);
        waitingForLoad.clear();
        removeSelectedMessageHighlight();
        scrollToMessagePosition = -10000;
        startLoadFromMessageId = id;
        showScrollToMessageError = !forceScroll;
        if (id == createUnreadMessageAfterId) {
            createUnreadMessageAfterIdLoading = true;
        }
        postponedScrollIsCanceled = false;
        waitingForLoad.add(lastLoadIndex);
        postponedScrollToLastMessageQueryIndex = lastLoadIndex;
        postponedScrollMinMessageId = minMessageId[0];
        postponedScrollMessageId = id;
        getMessagesController().loadMessages(loadIndex == 0 ? dialog_id : mergeDialogId, 0, false, isThreadChat() || AndroidUtilities.isTablet() ? 30 : 20, startLoadFromMessageId, 0, true, 0, classGuid, 3, 0, chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++);
    } else {
        View child = chatListView.getChildAt(0);
        if (child != null && child.getTop() <= 0) {
            showFloatingDateView(false);
        }
    }
    returnToMessageId = fromMessageId;
    returnToLoadIndex = loadIndex;
    needSelectFromMessageId = select;
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) ChatActionCell(org.telegram.ui.Cells.ChatActionCell) ChatMessageCell(org.telegram.ui.Cells.ChatMessageCell) MessageObject(org.telegram.messenger.MessageObject) HorizontalScrollView(android.widget.HorizontalScrollView) PinnedLineView(org.telegram.ui.Components.PinnedLineView) BotCommandsMenuView(org.telegram.ui.Components.BotCommandsMenuView) ReactedHeaderView(org.telegram.ui.Components.ReactedHeaderView) PipRoundVideoView(org.telegram.ui.Components.PipRoundVideoView) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) RecyclerView(androidx.recyclerview.widget.RecyclerView) BluredView(org.telegram.ui.Components.BluredView) InstantCameraView(org.telegram.ui.Components.InstantCameraView) ChatActivityEnterView(org.telegram.ui.Components.ChatActivityEnterView) ChatActivityEnterTopView(org.telegram.ui.Components.ChatActivityEnterTopView) ChatBigEmptyView(org.telegram.ui.Components.ChatBigEmptyView) BackupImageView(org.telegram.ui.Components.BackupImageView) TextureView(android.view.TextureView) RecyclerListView(org.telegram.ui.Components.RecyclerListView) ImageView(android.widget.ImageView) RadialProgressView(org.telegram.ui.Components.RadialProgressView) ChatGreetingsView(org.telegram.ui.Components.ChatGreetingsView) UndoView(org.telegram.ui.Components.UndoView) CounterView(org.telegram.ui.Components.CounterView) HintView(org.telegram.ui.Components.HintView) FragmentContextView(org.telegram.ui.Components.FragmentContextView) ClippingImageView(org.telegram.ui.Components.ClippingImageView) EmojiView(org.telegram.ui.Components.EmojiView) ChecksHintView(org.telegram.ui.Components.ChecksHintView) ThemeEditorView(org.telegram.ui.Components.ThemeEditorView) View(android.view.View) SearchCounterView(org.telegram.ui.Components.SearchCounterView) ForwardingPreviewView(org.telegram.ui.Components.ForwardingPreviewView) ReactionTabHolderView(org.telegram.ui.Components.ReactionTabHolderView) TextView(android.widget.TextView) ReactedUsersListView(org.telegram.ui.Components.ReactedUsersListView) NumberTextView(org.telegram.ui.Components.NumberTextView) Paint(android.graphics.Paint) TextSelectionHint(org.telegram.ui.Components.TextSelectionHint) TextPaint(android.text.TextPaint) SuppressLint(android.annotation.SuppressLint)

Aggregations

AlertDialog (org.telegram.ui.ActionBar.AlertDialog)101 TLRPC (org.telegram.tgnet.TLRPC)71 TextView (android.widget.TextView)63 FrameLayout (android.widget.FrameLayout)47 ArrayList (java.util.ArrayList)47 Context (android.content.Context)45 View (android.view.View)44 AndroidUtilities (org.telegram.messenger.AndroidUtilities)41 LocaleController (org.telegram.messenger.LocaleController)41 Theme (org.telegram.ui.ActionBar.Theme)41 R (org.telegram.messenger.R)40 BaseFragment (org.telegram.ui.ActionBar.BaseFragment)40 LinearLayout (android.widget.LinearLayout)38 Paint (android.graphics.Paint)37 MessagesController (org.telegram.messenger.MessagesController)37 SuppressLint (android.annotation.SuppressLint)36 TextUtils (android.text.TextUtils)36 FileLog (org.telegram.messenger.FileLog)36 Build (android.os.Build)34 Gravity (android.view.Gravity)34