Search in sources :

Example 6 with URLSpanNoUnderline

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

the class ChatMessageCell method onLongPress.

@Override
protected boolean onLongPress() {
    if (isRoundVideo && isPlayingRound && MediaController.getInstance().isPlayingMessage(currentMessageObject)) {
        float touchRadius = (lastTouchX - photoImage.getCenterX()) * (lastTouchX - photoImage.getCenterX()) + (lastTouchY - photoImage.getCenterY()) * (lastTouchY - photoImage.getCenterY());
        float r1 = (photoImage.getImageWidth() / 2f) * (photoImage.getImageWidth() / 2f);
        if (touchRadius < r1 && (lastTouchX > photoImage.getCenterX() + photoImage.getImageWidth() / 4f || lastTouchX < photoImage.getCenterX() - photoImage.getImageWidth() / 4f)) {
            boolean forward = lastTouchX > photoImage.getCenterX();
            if (videoPlayerRewinder == null) {
                videoForwardDrawable = new VideoForwardDrawable(true);
                videoPlayerRewinder = new VideoPlayerRewinder() {

                    @Override
                    protected void onRewindCanceled() {
                        onTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0, 0, 0));
                        videoForwardDrawable.setShowing(false);
                    }

                    @Override
                    protected void updateRewindProgressUi(long timeDiff, float progress, boolean rewindByBackSeek) {
                        videoForwardDrawable.setTime(Math.abs(timeDiff));
                        if (rewindByBackSeek) {
                            currentMessageObject.audioProgress = progress;
                            updatePlayingMessageProgress();
                        }
                    }

                    @Override
                    protected void onRewindStart(boolean rewindForward) {
                        videoForwardDrawable.setDelegate(new VideoForwardDrawable.VideoForwardDrawableDelegate() {

                            @Override
                            public void onAnimationEnd() {
                            }

                            @Override
                            public void invalidate() {
                                ChatMessageCell.this.invalidate();
                            }
                        });
                        videoForwardDrawable.setOneShootAnimation(false);
                        videoForwardDrawable.setLeftSide(!rewindForward);
                        videoForwardDrawable.setShowing(true);
                        invalidate();
                    }
                };
                getParent().requestDisallowInterceptTouchEvent(true);
            }
            videoPlayerRewinder.startRewind(MediaController.getInstance().getVideoPlayer(), forward, MediaController.getInstance().getPlaybackSpeed(false));
            return false;
        }
    }
    if (pressedLink instanceof URLSpanMono) {
        delegate.didPressUrl(this, pressedLink, true);
        return true;
    } else if (pressedLink instanceof URLSpanNoUnderline) {
        URLSpanNoUnderline url = (URLSpanNoUnderline) pressedLink;
        if (ChatActivity.isClickableLink(url.getURL()) || url.getURL().startsWith("/")) {
            delegate.didPressUrl(this, pressedLink, true);
            return true;
        }
    } else if (pressedLink instanceof URLSpan) {
        delegate.didPressUrl(this, pressedLink, true);
        return true;
    }
    resetPressedLink(-1);
    if (buttonPressed != 0 || miniButtonPressed != 0 || videoButtonPressed != 0 || pressedBotButton != -1) {
        buttonPressed = 0;
        miniButtonPressed = 0;
        videoButtonPressed = 0;
        pressedBotButton = -1;
        invalidate();
    }
    linkPreviewPressed = false;
    sideButtonPressed = false;
    imagePressed = false;
    timePressed = false;
    gamePreviewPressed = false;
    if (pressedVoteButton != -1 || pollHintPressed || psaHintPressed || instantPressed || otherPressed || commentButtonPressed) {
        instantPressed = instantButtonPressed = commentButtonPressed = false;
        pressedVoteButton = -1;
        pollHintPressed = false;
        psaHintPressed = false;
        otherPressed = false;
        if (Build.VERSION.SDK_INT >= 21) {
            for (int a = 0; a < selectorDrawable.length; a++) {
                if (selectorDrawable[a] != null) {
                    selectorDrawable[a].setState(StateSet.NOTHING);
                }
            }
        }
        invalidate();
    }
    if (delegate != null) {
        boolean handled = false;
        if (avatarPressed) {
            if (currentUser != null) {
                if (currentUser.id != 0) {
                    handled = delegate.didLongPressUserAvatar(this, currentUser, lastTouchX, lastTouchY);
                }
            } else if (currentChat != null) {
                final int id;
                if (currentMessageObject.messageOwner.fwd_from != null) {
                    if ((currentMessageObject.messageOwner.fwd_from.flags & 16) != 0) {
                        id = currentMessageObject.messageOwner.fwd_from.saved_from_msg_id;
                    } else {
                        id = currentMessageObject.messageOwner.fwd_from.channel_post;
                    }
                } else {
                    id = 0;
                }
                handled = delegate.didLongPressChannelAvatar(this, currentChat, id, lastTouchX, lastTouchY);
            }
        }
        if (!handled) {
            delegate.didLongPress(this, lastTouchX, lastTouchY);
        }
    }
    return true;
}
Also used : URLSpanMono(org.telegram.ui.Components.URLSpanMono) VideoPlayerRewinder(org.telegram.messenger.video.VideoPlayerRewinder) VideoForwardDrawable(org.telegram.ui.Components.VideoForwardDrawable) URLSpan(android.text.style.URLSpan) URLSpanNoUnderline(org.telegram.ui.Components.URLSpanNoUnderline) TextPaint(android.text.TextPaint) Paint(android.graphics.Paint) SuppressLint(android.annotation.SuppressLint) Point(org.telegram.ui.Components.Point)

Example 7 with URLSpanNoUnderline

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

the class ChatActionCell method onTouchEvent.

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (currentMessageObject == null) {
        return super.onTouchEvent(event);
    }
    float x = lastTouchX = event.getX();
    float y = lastTouchY = event.getY();
    boolean result = false;
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        if (delegate != null) {
            if (currentMessageObject.type == 11 && imageReceiver.isInsideImage(x, y)) {
                imagePressed = true;
                result = true;
            }
            if (result) {
                startCheckLongPress();
            }
        }
    } else {
        if (event.getAction() != MotionEvent.ACTION_MOVE) {
            cancelCheckLongPress();
        }
        if (imagePressed) {
            if (event.getAction() == MotionEvent.ACTION_UP) {
                imagePressed = false;
                if (delegate != null) {
                    delegate.didClickImage(this);
                    playSoundEffect(SoundEffectConstants.CLICK);
                }
            } else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
                imagePressed = false;
            } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                if (!imageReceiver.isInsideImage(x, y)) {
                    imagePressed = false;
                }
            }
        }
    }
    if (!result) {
        if (event.getAction() == MotionEvent.ACTION_DOWN || pressedLink != null && event.getAction() == MotionEvent.ACTION_UP) {
            if (x >= textX && y >= textY && x <= textX + textWidth && y <= textY + textHeight) {
                y -= textY;
                x -= textXLeft;
                final int line = textLayout.getLineForVertical((int) y);
                final int off = textLayout.getOffsetForHorizontal(line, x);
                final float left = textLayout.getLineLeft(line);
                if (left <= x && left + textLayout.getLineWidth(line) >= x && currentMessageObject.messageText instanceof Spannable) {
                    Spannable buffer = (Spannable) currentMessageObject.messageText;
                    URLSpan[] link = buffer.getSpans(off, off, URLSpan.class);
                    if (link.length != 0) {
                        if (event.getAction() == MotionEvent.ACTION_DOWN) {
                            pressedLink = link[0];
                            result = true;
                        } else {
                            if (link[0] == pressedLink) {
                                if (delegate != null) {
                                    String url = link[0].getURL();
                                    if (url.startsWith("invite") && pressedLink instanceof URLSpanNoUnderline) {
                                        URLSpanNoUnderline spanNoUnderline = (URLSpanNoUnderline) pressedLink;
                                        TLObject object = spanNoUnderline.getObject();
                                        if (object instanceof TLRPC.TL_chatInviteExported) {
                                            TLRPC.TL_chatInviteExported invite = (TLRPC.TL_chatInviteExported) object;
                                            delegate.needOpenInviteLink(invite);
                                        }
                                    } else if (url.startsWith("game")) {
                                        delegate.didPressReplyMessage(this, currentMessageObject.getReplyMsgId());
                                    /*TLRPC.KeyboardButton gameButton = null;
                                            MessageObject messageObject = currentMessageObject.replyMessageObject;
                                            if (messageObject != null && messageObject.messageOwner.reply_markup != null) {
                                                for (int a = 0; a < messageObject.messageOwner.reply_markup.rows.size(); a++) {
                                                    TLRPC.TL_keyboardButtonRow row = messageObject.messageOwner.reply_markup.rows.get(a);
                                                    for (int b = 0; b < row.buttons.size(); b++) {
                                                        TLRPC.KeyboardButton button = row.buttons.get(b);
                                                        if (button instanceof TLRPC.TL_keyboardButtonGame && button.game_id == currentMessageObject.messageOwner.action.game_id) {
                                                            gameButton = button;
                                                            break;
                                                        }
                                                    }
                                                    if (gameButton != null) {
                                                        break;
                                                    }
                                                }
                                            }
                                            if (gameButton != null) {
                                                delegate.didPressBotButton(messageObject, gameButton);
                                            }*/
                                    } else if (url.startsWith("http")) {
                                        Browser.openUrl(getContext(), url);
                                    } else {
                                        delegate.needOpenUserProfile(Long.parseLong(url));
                                    }
                                }
                                result = true;
                            }
                        }
                    } else {
                        pressedLink = null;
                    }
                } else {
                    pressedLink = null;
                }
            } else {
                pressedLink = null;
            }
        }
    }
    if (!result) {
        result = super.onTouchEvent(event);
    }
    return result;
}
Also used : TLObject(org.telegram.tgnet.TLObject) URLSpan(android.text.style.URLSpan) URLSpanNoUnderline(org.telegram.ui.Components.URLSpanNoUnderline) TextPaint(android.text.TextPaint) Paint(android.graphics.Paint) Spannable(android.text.Spannable) TLRPC(org.telegram.tgnet.TLRPC)

Example 8 with URLSpanNoUnderline

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

the class PassportActivity method createView.

@Override
public View createView(Context context) {
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(true);
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {

        private boolean onIdentityDone(Runnable finishRunnable, ErrorRunnable errorRunnable) {
            if (!uploadingDocuments.isEmpty() || checkFieldsForError()) {
                return false;
            }
            if (allowNonLatinName) {
                allowNonLatinName = false;
                boolean error = false;
                for (int a = 0; a < nonLatinNames.length; a++) {
                    if (nonLatinNames[a]) {
                        inputFields[a].setErrorText(LocaleController.getString("PassportUseLatinOnly", R.string.PassportUseLatinOnly));
                        if (!error) {
                            error = true;
                            String firstName = nonLatinNames[0] ? getTranslitString(inputExtraFields[FIELD_NATIVE_NAME].getText().toString()) : inputFields[FIELD_NAME].getText().toString();
                            String middleName = nonLatinNames[1] ? getTranslitString(inputExtraFields[FIELD_NATIVE_MIDNAME].getText().toString()) : inputFields[FIELD_MIDNAME].getText().toString();
                            String lastName = nonLatinNames[2] ? getTranslitString(inputExtraFields[FIELD_NATIVE_SURNAME].getText().toString()) : inputFields[FIELD_SURNAME].getText().toString();
                            if (!TextUtils.isEmpty(firstName) && !TextUtils.isEmpty(middleName) && !TextUtils.isEmpty(lastName)) {
                                int num = a;
                                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                                builder.setMessage(LocaleController.formatString("PassportNameCheckAlert", R.string.PassportNameCheckAlert, firstName, middleName, lastName));
                                builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                                builder.setPositiveButton(LocaleController.getString("Done", R.string.Done), (dialogInterface, i) -> {
                                    inputFields[FIELD_NAME].setText(firstName);
                                    inputFields[FIELD_MIDNAME].setText(middleName);
                                    inputFields[FIELD_SURNAME].setText(lastName);
                                    showEditDoneProgress(true, true);
                                    onIdentityDone(finishRunnable, errorRunnable);
                                });
                                builder.setNegativeButton(LocaleController.getString("Edit", R.string.Edit), (dialogInterface, i) -> onFieldError(inputFields[num]));
                                showDialog(builder.create());
                            } else {
                                onFieldError(inputFields[a]);
                            }
                        }
                    }
                }
                if (error) {
                    return false;
                }
            }
            if (isHasNotAnyChanges()) {
                finishFragment();
                return false;
            }
            JSONObject json = null;
            JSONObject documentsJson = null;
            try {
                if (!documentOnly) {
                    HashMap<String, String> valuesToSave = new HashMap<>(currentValues);
                    if (currentType.native_names) {
                        if (nativeInfoCell.getVisibility() == View.VISIBLE) {
                            valuesToSave.put("first_name_native", inputExtraFields[FIELD_NATIVE_NAME].getText().toString());
                            valuesToSave.put("middle_name_native", inputExtraFields[FIELD_NATIVE_MIDNAME].getText().toString());
                            valuesToSave.put("last_name_native", inputExtraFields[FIELD_NATIVE_SURNAME].getText().toString());
                        } else {
                            valuesToSave.put("first_name_native", inputFields[FIELD_NATIVE_NAME].getText().toString());
                            valuesToSave.put("middle_name_native", inputFields[FIELD_NATIVE_MIDNAME].getText().toString());
                            valuesToSave.put("last_name_native", inputFields[FIELD_NATIVE_SURNAME].getText().toString());
                        }
                    }
                    valuesToSave.put("first_name", inputFields[FIELD_NAME].getText().toString());
                    valuesToSave.put("middle_name", inputFields[FIELD_MIDNAME].getText().toString());
                    valuesToSave.put("last_name", inputFields[FIELD_SURNAME].getText().toString());
                    valuesToSave.put("birth_date", inputFields[FIELD_BIRTHDAY].getText().toString());
                    valuesToSave.put("gender", currentGender);
                    valuesToSave.put("country_code", currentCitizeship);
                    valuesToSave.put("residence_country_code", currentResidence);
                    json = new JSONObject();
                    ArrayList<String> keys = new ArrayList<>(valuesToSave.keySet());
                    Collections.sort(keys, (key1, key2) -> {
                        int val1 = getFieldCost(key1);
                        int val2 = getFieldCost(key2);
                        if (val1 < val2) {
                            return -1;
                        } else if (val1 > val2) {
                            return 1;
                        }
                        return 0;
                    });
                    for (int a = 0, size = keys.size(); a < size; a++) {
                        String key = keys.get(a);
                        json.put(key, valuesToSave.get(key));
                    }
                }
                if (currentDocumentsType != null) {
                    HashMap<String, String> valuesToSave = new HashMap<>(currentDocumentValues);
                    valuesToSave.put("document_no", inputFields[FIELD_CARDNUMBER].getText().toString());
                    if (currentExpireDate[0] != 0) {
                        valuesToSave.put("expiry_date", String.format(Locale.US, "%02d.%02d.%d", currentExpireDate[2], currentExpireDate[1], currentExpireDate[0]));
                    } else {
                        valuesToSave.put("expiry_date", "");
                    }
                    documentsJson = new JSONObject();
                    ArrayList<String> keys = new ArrayList<>(valuesToSave.keySet());
                    Collections.sort(keys, (key1, key2) -> {
                        int val1 = getFieldCost(key1);
                        int val2 = getFieldCost(key2);
                        if (val1 < val2) {
                            return -1;
                        } else if (val1 > val2) {
                            return 1;
                        }
                        return 0;
                    });
                    for (int a = 0, size = keys.size(); a < size; a++) {
                        String key = keys.get(a);
                        documentsJson.put(key, valuesToSave.get(key));
                    }
                }
            } catch (Exception ignore) {
            }
            if (fieldsErrors != null) {
                fieldsErrors.clear();
            }
            if (documentsErrors != null) {
                documentsErrors.clear();
            }
            delegate.saveValue(currentType, null, json != null ? json.toString() : null, currentDocumentsType, documentsJson != null ? documentsJson.toString() : null, null, selfieDocument, translationDocuments, frontDocument, reverseLayout != null && reverseLayout.getVisibility() == View.VISIBLE ? reverseDocument : null, finishRunnable, errorRunnable);
            return true;
        }

        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                if (checkDiscard()) {
                    return;
                }
                if (currentActivityType == TYPE_REQUEST || currentActivityType == TYPE_PASSWORD) {
                    callCallback(false);
                }
                finishFragment();
            } else if (id == info_item) {
                if (getParentActivity() == null) {
                    return;
                }
                final TextView message = new TextView(getParentActivity());
                String str2 = LocaleController.getString("PassportInfo2", R.string.PassportInfo2);
                SpannableStringBuilder spanned = new SpannableStringBuilder(str2);
                int index1 = str2.indexOf('*');
                int index2 = str2.lastIndexOf('*');
                if (index1 != -1 && index2 != -1) {
                    spanned.replace(index2, index2 + 1, "");
                    spanned.replace(index1, index1 + 1, "");
                    spanned.setSpan(new URLSpanNoUnderline(LocaleController.getString("PassportInfoUrl", R.string.PassportInfoUrl)) {

                        @Override
                        public void onClick(View widget) {
                            dismissCurrentDialog();
                            super.onClick(widget);
                        }
                    }, index1, index2 - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
                message.setText(spanned);
                message.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
                message.setLinkTextColor(Theme.getColor(Theme.key_dialogTextLink));
                message.setHighlightColor(Theme.getColor(Theme.key_dialogLinkSelection));
                message.setPadding(AndroidUtilities.dp(23), 0, AndroidUtilities.dp(23), 0);
                message.setMovementMethod(new AndroidUtilities.LinkMovementMethodMy());
                message.setTextColor(Theme.getColor(Theme.key_dialogTextBlack));
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setView(message);
                builder.setTitle(LocaleController.getString("PassportInfoTitle", R.string.PassportInfoTitle));
                builder.setNegativeButton(LocaleController.getString("Close", R.string.Close), null);
                showDialog(builder.create());
            } else if (id == done_button) {
                if (currentActivityType == TYPE_PASSWORD) {
                    onPasswordDone(false);
                    return;
                }
                if (currentActivityType == TYPE_PHONE_VERIFICATION) {
                    views[currentViewNum].onNextPressed(null);
                } else {
                    final Runnable finishRunnable = () -> finishFragment();
                    final ErrorRunnable errorRunnable = new ErrorRunnable() {

                        @Override
                        public void onError(String error, String text) {
                            if ("PHONE_VERIFICATION_NEEDED".equals(error)) {
                                startPhoneVerification(true, text, finishRunnable, this, delegate);
                            } else {
                                showEditDoneProgress(true, false);
                            }
                        }
                    };
                    if (currentActivityType == TYPE_EMAIL) {
                        String value;
                        if (useCurrentValue) {
                            value = currentEmail;
                        } else {
                            if (checkFieldsForError()) {
                                return;
                            }
                            value = inputFields[FIELD_EMAIL].getText().toString();
                        }
                        delegate.saveValue(currentType, value, null, null, null, null, null, null, null, null, finishRunnable, errorRunnable);
                    } else if (currentActivityType == TYPE_PHONE) {
                        String value;
                        if (useCurrentValue) {
                            value = UserConfig.getInstance(currentAccount).getCurrentUser().phone;
                        } else {
                            if (checkFieldsForError()) {
                                return;
                            }
                            value = inputFields[FIELD_PHONECODE].getText().toString() + inputFields[FIELD_PHONE].getText().toString();
                        }
                        delegate.saveValue(currentType, value, null, null, null, null, null, null, null, null, finishRunnable, errorRunnable);
                    } else if (currentActivityType == TYPE_ADDRESS) {
                        if (!uploadingDocuments.isEmpty() || checkFieldsForError()) {
                            return;
                        }
                        if (isHasNotAnyChanges()) {
                            finishFragment();
                            return;
                        }
                        JSONObject json = null;
                        try {
                            if (!documentOnly) {
                                json = new JSONObject();
                                json.put("street_line1", inputFields[FIELD_STREET1].getText().toString());
                                json.put("street_line2", inputFields[FIELD_STREET2].getText().toString());
                                json.put("post_code", inputFields[FIELD_POSTCODE].getText().toString());
                                json.put("city", inputFields[FIELD_CITY].getText().toString());
                                json.put("state", inputFields[FIELD_STATE].getText().toString());
                                json.put("country_code", currentCitizeship);
                            }
                        } catch (Exception ignore) {
                        }
                        if (fieldsErrors != null) {
                            fieldsErrors.clear();
                        }
                        if (documentsErrors != null) {
                            documentsErrors.clear();
                        }
                        delegate.saveValue(currentType, null, json != null ? json.toString() : null, currentDocumentsType, null, documents, selfieDocument, translationDocuments, null, null, finishRunnable, errorRunnable);
                    } else if (currentActivityType == TYPE_IDENTITY) {
                        if (!onIdentityDone(finishRunnable, errorRunnable)) {
                            return;
                        }
                    } else if (currentActivityType == TYPE_EMAIL_VERIFICATION) {
                        final TLRPC.TL_account_verifyEmail req = new TLRPC.TL_account_verifyEmail();
                        req.email = currentValues.get("email");
                        req.code = inputFields[FIELD_EMAIL].getText().toString();
                        int reqId = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
                            if (error == null) {
                                delegate.saveValue(currentType, currentValues.get("email"), null, null, null, null, null, null, null, null, finishRunnable, errorRunnable);
                            } else {
                                AlertsCreator.processError(currentAccount, error, PassportActivity.this, req);
                                errorRunnable.onError(null, null);
                            }
                        }));
                        ConnectionsManager.getInstance(currentAccount).bindRequestToGuid(reqId, classGuid);
                    }
                    showEditDoneProgress(true, true);
                }
            }
        }
    });
    if (currentActivityType == TYPE_PHONE_VERIFICATION) {
        fragmentView = scrollView = new ScrollView(context) {

            @Override
            protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
                return false;
            }

            @Override
            public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
                if (currentViewNum == 1 || currentViewNum == 2 || currentViewNum == 4) {
                    rectangle.bottom += AndroidUtilities.dp(40);
                }
                return super.requestChildRectangleOnScreen(child, rectangle, immediate);
            }

            @Override
            protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
                scrollHeight = MeasureSpec.getSize(heightMeasureSpec) - AndroidUtilities.dp(30);
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            }
        };
        scrollView.setFillViewport(true);
        AndroidUtilities.setScrollViewEdgeEffectColor(scrollView, Theme.getColor(Theme.key_actionBarDefault));
    } else {
        fragmentView = new FrameLayout(context);
        FrameLayout frameLayout = (FrameLayout) fragmentView;
        fragmentView.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundGray));
        scrollView = new ScrollView(context) {

            @Override
            protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
                return false;
            }

            @Override
            public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
                rectangle.offset(child.getLeft() - child.getScrollX(), child.getTop() - child.getScrollY());
                rectangle.top += AndroidUtilities.dp(20);
                rectangle.bottom += AndroidUtilities.dp(50);
                return super.requestChildRectangleOnScreen(child, rectangle, immediate);
            }
        };
        scrollView.setFillViewport(true);
        AndroidUtilities.setScrollViewEdgeEffectColor(scrollView, Theme.getColor(Theme.key_actionBarDefault));
        frameLayout.addView(scrollView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 0, 0, 0, currentActivityType == TYPE_REQUEST ? 48 : 0));
        linearLayout2 = new LinearLayout(context);
        linearLayout2.setOrientation(LinearLayout.VERTICAL);
        scrollView.addView(linearLayout2, new ScrollView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    }
    if (currentActivityType != TYPE_REQUEST && currentActivityType != TYPE_MANAGE) {
        ActionBarMenu menu = actionBar.createMenu();
        doneItem = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56), LocaleController.getString("Done", R.string.Done));
        progressView = new ContextProgressView(context, 1);
        progressView.setAlpha(0.0f);
        progressView.setScaleX(0.1f);
        progressView.setScaleY(0.1f);
        progressView.setVisibility(View.INVISIBLE);
        doneItem.addView(progressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
        if (currentActivityType == TYPE_IDENTITY || currentActivityType == TYPE_ADDRESS) {
            if (chatAttachAlert != null) {
                try {
                    if (chatAttachAlert.isShowing()) {
                        chatAttachAlert.dismiss();
                    }
                } catch (Exception ignore) {
                }
                chatAttachAlert.onDestroy();
                chatAttachAlert = null;
            }
        }
    }
    if (currentActivityType == TYPE_PASSWORD) {
        createPasswordInterface(context);
    } else if (currentActivityType == TYPE_REQUEST) {
        createRequestInterface(context);
    } else if (currentActivityType == TYPE_IDENTITY) {
        createIdentityInterface(context);
        fillInitialValues();
    } else if (currentActivityType == TYPE_ADDRESS) {
        createAddressInterface(context);
        fillInitialValues();
    } else if (currentActivityType == TYPE_PHONE) {
        createPhoneInterface(context);
    } else if (currentActivityType == TYPE_EMAIL) {
        createEmailInterface(context);
    } else if (currentActivityType == TYPE_EMAIL_VERIFICATION) {
        createEmailVerificationInterface(context);
    } else if (currentActivityType == TYPE_PHONE_VERIFICATION) {
        createPhoneVerificationInterface(context);
    } else if (currentActivityType == TYPE_MANAGE) {
        createManageInterface(context);
    }
    return fragmentView;
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) RandomAccessFile(java.io.RandomAccessFile) Arrays(java.util.Arrays) Bundle(android.os.Bundle) Uri(android.net.Uri) FrameLayout(android.widget.FrameLayout) ImageView(android.widget.ImageView) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) Drawable(android.graphics.drawable.Drawable) AvatarDrawable(org.telegram.ui.Components.AvatarDrawable) Manifest(android.Manifest) RSAPublicKey(java.security.interfaces.RSAPublicKey) MediaStore(android.provider.MediaStore) Canvas(android.graphics.Canvas) TimerTask(java.util.TimerTask) ForegroundColorSpan(android.text.style.ForegroundColorSpan) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) NotificationCenter(org.telegram.messenger.NotificationCenter) TextPaint(android.text.TextPaint) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) Paint(android.graphics.Paint) InputFilter(android.text.InputFilter) RadialProgress(org.telegram.ui.Components.RadialProgress) TextWatcher(android.text.TextWatcher) FileLoader(org.telegram.messenger.FileLoader) SlideView(org.telegram.ui.Components.SlideView) RequestDelegate(org.telegram.tgnet.RequestDelegate) Dialog(android.app.Dialog) URLSpanNoUnderline(org.telegram.ui.Components.URLSpanNoUnderline) AlertsCreator(org.telegram.ui.Components.AlertsCreator) Editable(android.text.Editable) TextInfoPrivacyCell(org.telegram.ui.Cells.TextInfoPrivacyCell) ArrayList(java.util.ArrayList) SpannableStringBuilder(android.text.SpannableStringBuilder) Calendar(java.util.Calendar) TextDetailSettingsCell(org.telegram.ui.Cells.TextDetailSettingsCell) TLRPC(org.telegram.tgnet.TLRPC) Toast(android.widget.Toast) PhoneFormat(org.telegram.PhoneFormat.PhoneFormat) Menu(android.view.Menu) BuildConfig(org.telegram.messenger.BuildConfig) TextSettingsCell(org.telegram.ui.Cells.TextSettingsCell) HintEditText(org.telegram.ui.Components.HintEditText) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) R(org.telegram.messenger.R) TextUtils(android.text.TextUtils) InputStreamReader(java.io.InputStreamReader) File(java.io.File) Gravity(android.view.Gravity) UserObject(org.telegram.messenger.UserObject) SharedPreferences(android.content.SharedPreferences) TypedValue(android.util.TypedValue) ScrollView(android.widget.ScrollView) BufferedReader(java.io.BufferedReader) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) ThemeDescription(org.telegram.ui.ActionBar.ThemeDescription) Rect(android.graphics.Rect) ActionMode(android.view.ActionMode) LinearLayout(android.widget.LinearLayout) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) PackageManager(android.content.pm.PackageManager) Spannable(android.text.Spannable) AndroidUtilities(org.telegram.messenger.AndroidUtilities) ClickableSpan(android.text.style.ClickableSpan) Timer(java.util.Timer) Animator(android.animation.Animator) AccelerateDecelerateInterpolator(android.view.animation.AccelerateDecelerateInterpolator) CheckBoxCell(org.telegram.ui.Cells.CheckBoxCell) MrzRecognizer(org.telegram.messenger.MrzRecognizer) ShadowSectionCell(org.telegram.ui.Cells.ShadowSectionCell) JSONObject(org.json.JSONObject) ApplicationLoader(org.telegram.messenger.ApplicationLoader) Locale(java.util.Locale) MediaController(org.telegram.messenger.MediaController) View(android.view.View) ImageLoader(org.telegram.messenger.ImageLoader) ContextProgressView(org.telegram.ui.Components.ContextProgressView) Utilities(org.telegram.messenger.Utilities) EmptyTextProgressView(org.telegram.ui.Components.EmptyTextProgressView) ObjectAnimator(android.animation.ObjectAnimator) InputType(android.text.InputType) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) PorterDuff(android.graphics.PorterDuff) SendMessagesHelper(org.telegram.messenger.SendMessagesHelper) ConnectionsManager(org.telegram.tgnet.ConnectionsManager) ViewGroup(android.view.ViewGroup) KeyFactory(java.security.KeyFactory) UserConfig(org.telegram.messenger.UserConfig) TextView(android.widget.TextView) FileProvider(androidx.core.content.FileProvider) EditorInfo(android.view.inputmethod.EditorInfo) Typeface(android.graphics.Typeface) Context(android.content.Context) StaticLayout(android.text.StaticLayout) Spanned(android.text.Spanned) KeyEvent(android.view.KeyEvent) Theme(org.telegram.ui.ActionBar.Theme) Intent(android.content.Intent) LocaleController(org.telegram.messenger.LocaleController) HashMap(java.util.HashMap) HeaderCell(org.telegram.ui.Cells.HeaderCell) PackageInfo(android.content.pm.PackageInfo) Cipher(javax.crypto.Cipher) MenuItem(android.view.MenuItem) SuppressLint(android.annotation.SuppressLint) PhoneNumberUtils(android.telephony.PhoneNumberUtils) MotionEvent(android.view.MotionEvent) SRPHelper(org.telegram.messenger.SRPHelper) SecureDocument(org.telegram.messenger.SecureDocument) TelephonyManager(android.telephony.TelephonyManager) ActionBar(org.telegram.ui.ActionBar.ActionBar) TLObject(org.telegram.tgnet.TLObject) AnimatorSet(android.animation.AnimatorSet) MessageObject(org.telegram.messenger.MessageObject) SharedConfig(org.telegram.messenger.SharedConfig) PasswordTransformationMethod(android.text.method.PasswordTransformationMethod) BuildVars(org.telegram.messenger.BuildVars) Build(android.os.Build) DownloadController(org.telegram.messenger.DownloadController) DialogInterface(android.content.DialogInterface) Browser(org.telegram.messenger.browser.Browser) Iterator(java.util.Iterator) BackupImageView(org.telegram.ui.Components.BackupImageView) LayoutHelper(org.telegram.ui.Components.LayoutHelper) FileLog(org.telegram.messenger.FileLog) SecureDocumentKey(org.telegram.messenger.SecureDocumentKey) ChatAttachAlert(org.telegram.ui.Components.ChatAttachAlert) Bitmap(android.graphics.Bitmap) Base64(android.util.Base64) Vibrator(android.os.Vibrator) Comparator(java.util.Comparator) Activity(android.app.Activity) Collections(java.util.Collections) JSONArray(org.json.JSONArray) HashMap(java.util.HashMap) SpannableStringBuilder(android.text.SpannableStringBuilder) ContextProgressView(org.telegram.ui.Components.ContextProgressView) ArrayList(java.util.ArrayList) TLRPC(org.telegram.tgnet.TLRPC) TextView(android.widget.TextView) URLSpanNoUnderline(org.telegram.ui.Components.URLSpanNoUnderline) ActionBar(org.telegram.ui.ActionBar.ActionBar) Rect(android.graphics.Rect) ImageView(android.widget.ImageView) SlideView(org.telegram.ui.Components.SlideView) ScrollView(android.widget.ScrollView) View(android.view.View) ContextProgressView(org.telegram.ui.Components.ContextProgressView) EmptyTextProgressView(org.telegram.ui.Components.EmptyTextProgressView) TextView(android.widget.TextView) BackupImageView(org.telegram.ui.Components.BackupImageView) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) TextPaint(android.text.TextPaint) Paint(android.graphics.Paint) SuppressLint(android.annotation.SuppressLint) AndroidUtilities(org.telegram.messenger.AndroidUtilities) JSONObject(org.json.JSONObject) ScrollView(android.widget.ScrollView) FrameLayout(android.widget.FrameLayout) SpannableStringBuilder(android.text.SpannableStringBuilder) LinearLayout(android.widget.LinearLayout)

Example 9 with URLSpanNoUnderline

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

the class MessageObject method addUrlsByPattern.

public static void addUrlsByPattern(boolean isOut, CharSequence charSequence, boolean botCommands, int patternType, int duration, boolean check) {
    try {
        Matcher matcher;
        if (patternType == 3 || patternType == 4) {
            if (videoTimeUrlPattern == null) {
                videoTimeUrlPattern = Pattern.compile("\\b(?:(\\d{1,2}):)?(\\d{1,3}):([0-5][0-9])\\b");
            }
            matcher = videoTimeUrlPattern.matcher(charSequence);
        } else if (patternType == 1) {
            if (instagramUrlPattern == null) {
                instagramUrlPattern = Pattern.compile("(^|\\s|\\()@[a-zA-Z\\d_.]{1,32}|(^|\\s|\\()#[\\w.]+");
            }
            matcher = instagramUrlPattern.matcher(charSequence);
        } else {
            if (urlPattern == null) {
                urlPattern = Pattern.compile("(^|\\s)/[a-zA-Z@\\d_]{1,255}|(^|\\s|\\()@[a-zA-Z\\d_]{1,32}|(^|\\s|\\()#[^0-9][\\w.]+|(^|\\s)\\$[A-Z]{3,8}([ ,.]|$)");
            }
            matcher = urlPattern.matcher(charSequence);
        }
        Spannable spannable = (Spannable) charSequence;
        while (matcher.find()) {
            int start = matcher.start();
            int end = matcher.end();
            URLSpanNoUnderline url = null;
            if (patternType == 3 || patternType == 4) {
                URLSpan[] spans = spannable.getSpans(start, end, URLSpan.class);
                if (spans != null && spans.length > 0) {
                    continue;
                }
                int count = matcher.groupCount();
                int s1 = matcher.start(1);
                int e1 = matcher.end(1);
                int s2 = matcher.start(2);
                int e2 = matcher.end(2);
                int s3 = matcher.start(3);
                int e3 = matcher.end(3);
                int minutes = Utilities.parseInt(charSequence.subSequence(s2, e2));
                int seconds = Utilities.parseInt(charSequence.subSequence(s3, e3));
                int hours = s1 >= 0 && e1 >= 0 ? Utilities.parseInt(charSequence.subSequence(s1, e1)) : -1;
                seconds += minutes * 60;
                if (hours > 0) {
                    seconds += hours * 60 * 60;
                }
                if (seconds > duration) {
                    continue;
                }
                if (patternType == 3) {
                    url = new URLSpanNoUnderline("video?" + seconds);
                } else {
                    url = new URLSpanNoUnderline("audio?" + seconds);
                }
            } else {
                char ch = charSequence.charAt(start);
                if (patternType != 0) {
                    if (ch != '@' && ch != '#') {
                        start++;
                    }
                    ch = charSequence.charAt(start);
                    if (ch != '@' && ch != '#') {
                        continue;
                    }
                } else {
                    if (ch != '@' && ch != '#' && ch != '/' && ch != '$') {
                        start++;
                    }
                }
                if (patternType == 1) {
                    if (ch == '@') {
                        url = new URLSpanNoUnderline("https://instagram.com/" + charSequence.subSequence(start + 1, end).toString());
                    } else {
                        url = new URLSpanNoUnderline("https://www.instagram.com/explore/tags/" + charSequence.subSequence(start + 1, end).toString());
                    }
                } else if (patternType == 2) {
                    if (ch == '@') {
                        url = new URLSpanNoUnderline("https://twitter.com/" + charSequence.subSequence(start + 1, end).toString());
                    } else {
                        url = new URLSpanNoUnderline("https://twitter.com/hashtag/" + charSequence.subSequence(start + 1, end).toString());
                    }
                } else {
                    if (charSequence.charAt(start) == '/') {
                        if (botCommands) {
                            url = new URLSpanBotCommand(charSequence.subSequence(start, end).toString(), isOut ? 1 : 0);
                        }
                    } else {
                        url = new URLSpanNoUnderline(charSequence.subSequence(start, end).toString());
                    }
                }
            }
            if (url != null) {
                if (check) {
                    ClickableSpan[] spans = spannable.getSpans(start, end, ClickableSpan.class);
                    if (spans != null && spans.length > 0) {
                        spannable.removeSpan(spans[0]);
                    }
                }
                spannable.setSpan(url, start, end, 0);
            }
        }
    } catch (Exception e) {
        FileLog.e(e);
    }
}
Also used : Matcher(java.util.regex.Matcher) URLSpanBotCommand(org.telegram.ui.Components.URLSpanBotCommand) URLSpan(android.text.style.URLSpan) URLSpanNoUnderline(org.telegram.ui.Components.URLSpanNoUnderline) ClickableSpan(android.text.style.ClickableSpan) Spannable(android.text.Spannable) TextPaint(android.text.TextPaint)

Example 10 with URLSpanNoUnderline

use of org.telegram.ui.Components.URLSpanNoUnderline 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)

Aggregations

URLSpanNoUnderline (org.telegram.ui.Components.URLSpanNoUnderline)11 Spannable (android.text.Spannable)6 SpannableStringBuilder (android.text.SpannableStringBuilder)6 TextPaint (android.text.TextPaint)6 URLSpan (android.text.style.URLSpan)6 TLRPC (org.telegram.tgnet.TLRPC)6 Paint (android.graphics.Paint)5 Intent (android.content.Intent)4 Canvas (android.graphics.Canvas)4 Spanned (android.text.Spanned)4 View (android.view.View)4 ViewGroup (android.view.ViewGroup)4 ImageView (android.widget.ImageView)4 TextView (android.widget.TextView)4 ArrayList (java.util.ArrayList)4 AndroidUtilities (org.telegram.messenger.AndroidUtilities)4 ActionBar (org.telegram.ui.ActionBar.ActionBar)4 Manifest (android.Manifest)3 Animator (android.animation.Animator)3 AnimatorListenerAdapter (android.animation.AnimatorListenerAdapter)3