Search in sources :

Example 66 with AlertDialog

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

the class FilterCreateActivity method saveFilterToServer.

public static void saveFilterToServer(MessagesController.DialogFilter filter, int newFilterFlags, String newFilterName, ArrayList<Long> newAlwaysShow, ArrayList<Long> newNeverShow, LongSparseIntArray newPinned, boolean creatingNew, boolean atBegin, boolean hasUserChanged, boolean resetUnreadCounter, boolean progress, BaseFragment fragment, Runnable onFinish) {
    if (fragment == null || fragment.getParentActivity() == null) {
        return;
    }
    AlertDialog progressDialog;
    if (progress) {
        progressDialog = new AlertDialog(fragment.getParentActivity(), 3);
        progressDialog.setCanCacnel(false);
        progressDialog.show();
    } else {
        progressDialog = null;
    }
    TLRPC.TL_messages_updateDialogFilter req = new TLRPC.TL_messages_updateDialogFilter();
    req.id = filter.id;
    req.flags |= 1;
    req.filter = new TLRPC.TL_dialogFilter();
    req.filter.contacts = (newFilterFlags & MessagesController.DIALOG_FILTER_FLAG_CONTACTS) != 0;
    req.filter.non_contacts = (newFilterFlags & MessagesController.DIALOG_FILTER_FLAG_NON_CONTACTS) != 0;
    req.filter.groups = (newFilterFlags & MessagesController.DIALOG_FILTER_FLAG_GROUPS) != 0;
    req.filter.broadcasts = (newFilterFlags & MessagesController.DIALOG_FILTER_FLAG_CHANNELS) != 0;
    req.filter.bots = (newFilterFlags & MessagesController.DIALOG_FILTER_FLAG_BOTS) != 0;
    req.filter.exclude_muted = (newFilterFlags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) != 0;
    req.filter.exclude_read = (newFilterFlags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_READ) != 0;
    req.filter.exclude_archived = (newFilterFlags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED) != 0;
    req.filter.id = filter.id;
    req.filter.title = newFilterName;
    MessagesController messagesController = fragment.getMessagesController();
    ArrayList<Long> pinArray = new ArrayList<>();
    if (newPinned.size() != 0) {
        for (int a = 0, N = newPinned.size(); a < N; a++) {
            long key = newPinned.keyAt(a);
            if (DialogObject.isEncryptedDialog(key)) {
                continue;
            }
            pinArray.add(key);
        }
        Collections.sort(pinArray, (o1, o2) -> {
            int idx1 = newPinned.get(o1);
            int idx2 = newPinned.get(o2);
            if (idx1 > idx2) {
                return 1;
            } else if (idx1 < idx2) {
                return -1;
            }
            return 0;
        });
    }
    for (int b = 0; b < 3; b++) {
        ArrayList<Long> fromArray;
        ArrayList<TLRPC.InputPeer> toArray;
        if (b == 0) {
            fromArray = newAlwaysShow;
            toArray = req.filter.include_peers;
        } else if (b == 1) {
            fromArray = newNeverShow;
            toArray = req.filter.exclude_peers;
        } else {
            fromArray = pinArray;
            toArray = req.filter.pinned_peers;
        }
        for (int a = 0, N = fromArray.size(); a < N; a++) {
            long did = fromArray.get(a);
            if (b == 0 && newPinned.indexOfKey(did) >= 0) {
                continue;
            }
            if (!DialogObject.isEncryptedDialog(did)) {
                if (did > 0) {
                    TLRPC.User user = messagesController.getUser(did);
                    if (user != null) {
                        TLRPC.InputPeer inputPeer = new TLRPC.TL_inputPeerUser();
                        inputPeer.user_id = did;
                        inputPeer.access_hash = user.access_hash;
                        toArray.add(inputPeer);
                    }
                } else {
                    TLRPC.Chat chat = messagesController.getChat(-did);
                    if (chat != null) {
                        if (ChatObject.isChannel(chat)) {
                            TLRPC.InputPeer inputPeer = new TLRPC.TL_inputPeerChannel();
                            inputPeer.channel_id = -did;
                            inputPeer.access_hash = chat.access_hash;
                            toArray.add(inputPeer);
                        } else {
                            TLRPC.InputPeer inputPeer = new TLRPC.TL_inputPeerChat();
                            inputPeer.chat_id = -did;
                            toArray.add(inputPeer);
                        }
                    }
                }
            }
        }
    }
    fragment.getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
        if (progress) {
            try {
                if (progressDialog != null) {
                    progressDialog.dismiss();
                }
            } catch (Exception e) {
                FileLog.e(e);
            }
            processAddFilter(filter, newFilterFlags, newFilterName, newAlwaysShow, newNeverShow, creatingNew, atBegin, hasUserChanged, resetUnreadCounter, fragment, onFinish);
        }
    }));
    if (!progress) {
        processAddFilter(filter, newFilterFlags, newFilterName, newAlwaysShow, newNeverShow, creatingNew, atBegin, hasUserChanged, resetUnreadCounter, fragment, onFinish);
    }
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) MessagesController(org.telegram.messenger.MessagesController) ArrayList(java.util.ArrayList) TLRPC(org.telegram.tgnet.TLRPC) TextPaint(android.text.TextPaint) Paint(android.graphics.Paint)

Example 67 with AlertDialog

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

the class FilterCreateActivity method showRemoveAlert.

private void showRemoveAlert(int position, CharSequence name, Object object, boolean include) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
    if (include) {
        builder.setTitle(LocaleController.getString("FilterRemoveInclusionTitle", R.string.FilterRemoveInclusionTitle));
        if (object instanceof String) {
            builder.setMessage(LocaleController.formatString("FilterRemoveInclusionText", R.string.FilterRemoveInclusionText, name));
        } else if (object instanceof TLRPC.User) {
            builder.setMessage(LocaleController.formatString("FilterRemoveInclusionUserText", R.string.FilterRemoveInclusionUserText, name));
        } else {
            builder.setMessage(LocaleController.formatString("FilterRemoveInclusionChatText", R.string.FilterRemoveInclusionChatText, name));
        }
    } else {
        builder.setTitle(LocaleController.getString("FilterRemoveExclusionTitle", R.string.FilterRemoveExclusionTitle));
        if (object instanceof String) {
            builder.setMessage(LocaleController.formatString("FilterRemoveExclusionText", R.string.FilterRemoveExclusionText, name));
        } else if (object instanceof TLRPC.User) {
            builder.setMessage(LocaleController.formatString("FilterRemoveExclusionUserText", R.string.FilterRemoveExclusionUserText, name));
        } else {
            builder.setMessage(LocaleController.formatString("FilterRemoveExclusionChatText", R.string.FilterRemoveExclusionChatText, name));
        }
    }
    builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
    builder.setPositiveButton(LocaleController.getString("StickersRemove", R.string.StickersRemove), (dialogInterface, i) -> {
        if (position == includeContactsRow) {
            newFilterFlags &= ~MessagesController.DIALOG_FILTER_FLAG_CONTACTS;
        } else if (position == includeNonContactsRow) {
            newFilterFlags &= ~MessagesController.DIALOG_FILTER_FLAG_NON_CONTACTS;
        } else if (position == includeGroupsRow) {
            newFilterFlags &= ~MessagesController.DIALOG_FILTER_FLAG_GROUPS;
        } else if (position == includeChannelsRow) {
            newFilterFlags &= ~MessagesController.DIALOG_FILTER_FLAG_CHANNELS;
        } else if (position == includeBotsRow) {
            newFilterFlags &= ~MessagesController.DIALOG_FILTER_FLAG_BOTS;
        } else if (position == excludeArchivedRow) {
            newFilterFlags &= ~MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED;
        } else if (position == excludeMutedRow) {
            newFilterFlags &= ~MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED;
        } else if (position == excludeReadRow) {
            newFilterFlags &= ~MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_READ;
        } else {
            if (include) {
                newAlwaysShow.remove(position - includeStartRow);
            } else {
                newNeverShow.remove(position - excludeStartRow);
            }
        }
        fillFilterName();
        updateRows();
        checkDoneButton(true);
    });
    AlertDialog alertDialog = builder.create();
    showDialog(alertDialog);
    TextView button = (TextView) alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
    if (button != null) {
        button.setTextColor(Theme.getColor(Theme.key_dialogTextRed2));
    }
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) TextView(android.widget.TextView) TLRPC(org.telegram.tgnet.TLRPC)

Example 68 with AlertDialog

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

the class LaunchActivity method runImportRequest.

private void runImportRequest(final Uri importUri, ArrayList<Uri> documents) {
    final int intentAccount = UserConfig.selectedAccount;
    final AlertDialog progressDialog = new AlertDialog(this, 3);
    final int[] requestId = new int[] { 0 };
    Runnable cancelRunnable = null;
    String content;
    InputStream inputStream = null;
    try {
        int linesCount = 0;
        inputStream = getContentResolver().openInputStream(importUri);
        BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder total = new StringBuilder();
        for (String line; (line = r.readLine()) != null && linesCount < 100; ) {
            total.append(line).append('\n');
            linesCount++;
        }
        content = total.toString();
    } catch (Exception e) {
        FileLog.e(e);
        return;
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (Exception e2) {
            FileLog.e(e2);
        }
    }
    final TLRPC.TL_messages_checkHistoryImport req = new TLRPC.TL_messages_checkHistoryImport();
    req.import_head = content;
    requestId[0] = ConnectionsManager.getInstance(intentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
        if (!LaunchActivity.this.isFinishing()) {
            if (response != null && actionBarLayout != null) {
                final TLRPC.TL_messages_historyImportParsed res = (TLRPC.TL_messages_historyImportParsed) response;
                Bundle args = new Bundle();
                args.putBoolean("onlySelect", true);
                args.putString("importTitle", res.title);
                args.putBoolean("allowSwitchAccount", true);
                if (res.pm) {
                    args.putInt("dialogsType", 12);
                } else if (res.group) {
                    args.putInt("dialogsType", 11);
                } else {
                    String uri = importUri.toString();
                    Set<String> uris = MessagesController.getInstance(intentAccount).exportPrivateUri;
                    boolean ok = false;
                    for (String u : uris) {
                        if (uri.contains(u)) {
                            args.putInt("dialogsType", 12);
                            ok = true;
                            break;
                        }
                    }
                    if (!ok) {
                        uris = MessagesController.getInstance(intentAccount).exportGroupUri;
                        for (String u : uris) {
                            if (uri.contains(u)) {
                                args.putInt("dialogsType", 11);
                                ok = true;
                                break;
                            }
                        }
                        if (!ok) {
                            args.putInt("dialogsType", 13);
                        }
                    }
                }
                if (SecretMediaViewer.hasInstance() && SecretMediaViewer.getInstance().isVisible()) {
                    SecretMediaViewer.getInstance().closePhoto(false, false);
                } else if (PhotoViewer.hasInstance() && PhotoViewer.getInstance().isVisible()) {
                    PhotoViewer.getInstance().closePhoto(false, true);
                } else if (ArticleViewer.hasInstance() && ArticleViewer.getInstance().isVisible()) {
                    ArticleViewer.getInstance().close(false, true);
                }
                if (GroupCallActivity.groupCallInstance != null) {
                    GroupCallActivity.groupCallInstance.dismiss();
                }
                drawerLayoutContainer.setAllowOpenDrawer(false, false);
                if (AndroidUtilities.isTablet()) {
                    actionBarLayout.showLastFragment();
                    rightActionBarLayout.showLastFragment();
                } else {
                    drawerLayoutContainer.setAllowOpenDrawer(true, false);
                }
                DialogsActivity fragment = new DialogsActivity(args);
                fragment.setDelegate(this);
                boolean removeLast;
                if (AndroidUtilities.isTablet()) {
                    removeLast = layersActionBarLayout.fragmentsStack.size() > 0 && layersActionBarLayout.fragmentsStack.get(layersActionBarLayout.fragmentsStack.size() - 1) instanceof DialogsActivity;
                } else {
                    removeLast = actionBarLayout.fragmentsStack.size() > 1 && actionBarLayout.fragmentsStack.get(actionBarLayout.fragmentsStack.size() - 1) instanceof DialogsActivity;
                }
                actionBarLayout.presentFragment(fragment, removeLast, false, true, false);
            } else {
                if (documentsUrisArray == null) {
                    documentsUrisArray = new ArrayList<>();
                }
                documentsUrisArray.add(0, exportingChatUri);
                exportingChatUri = null;
                openDialogsToSend(true);
            }
            try {
                progressDialog.dismiss();
            } catch (Exception e) {
                FileLog.e(e);
            }
        }
    }, ConnectionsManager.RequestFlagFailOnServerErrors));
    final Runnable cancelRunnableFinal = cancelRunnable;
    progressDialog.setOnCancelListener(dialog -> {
        ConnectionsManager.getInstance(intentAccount).cancelRequest(requestId[0], true);
        if (cancelRunnableFinal != null) {
            cancelRunnableFinal.run();
        }
    });
    try {
        progressDialog.showDelayed(300);
    } catch (Exception ignore) {
    }
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) UpdateAppAlertDialog(org.telegram.ui.Components.UpdateAppAlertDialog) Bundle(android.os.Bundle) NonNull(androidx.annotation.NonNull) AbstractSerializedData(org.telegram.tgnet.AbstractSerializedData) Uri(android.net.Uri) FrameLayout(android.widget.FrameLayout) ImageView(android.widget.ImageView) StickersAlert(org.telegram.ui.Components.StickersAlert) LocationController(org.telegram.messenger.LocationController) Bulletin(org.telegram.ui.Components.Bulletin) VoIPPendingCall(org.telegram.messenger.voip.VoIPPendingCall) MediaActionDrawable(org.telegram.ui.Components.MediaActionDrawable) ShortcutManagerCompat(androidx.core.content.pm.ShortcutManagerCompat) Manifest(android.Manifest) Matcher(java.util.regex.Matcher) DrawerProfileCell(org.telegram.ui.Cells.DrawerProfileCell) Map(java.util.Map) Shader(android.graphics.Shader) Canvas(android.graphics.Canvas) Function(androidx.arch.core.util.Function) UndoView(org.telegram.ui.Components.UndoView) ContactsLoadingObserver(org.telegram.messenger.ContactsLoadingObserver) Set(java.util.Set) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) NotificationCenter(org.telegram.messenger.NotificationCenter) Paint(android.graphics.Paint) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) FileLoader(org.telegram.messenger.FileLoader) GroupCallPip(org.telegram.ui.Components.GroupCallPip) ViewParent(android.view.ViewParent) PipRoundVideoView(org.telegram.ui.Components.PipRoundVideoView) SimpleDateFormat(java.text.SimpleDateFormat) SystemClock(android.os.SystemClock) AlertsCreator(org.telegram.ui.Components.AlertsCreator) WebRtcAudioTrack(org.webrtc.voiceengine.WebRtcAudioTrack) ArrayList(java.util.ArrayList) ItemTouchHelper(androidx.recyclerview.widget.ItemTouchHelper) TLRPC(org.telegram.tgnet.TLRPC) Toast(android.widget.Toast) PhoneFormat(org.telegram.PhoneFormat.PhoneFormat) Menu(android.view.Menu) PasscodeView(org.telegram.ui.Components.PasscodeView) SizeNotifierFrameLayout(org.telegram.ui.Components.SizeNotifierFrameLayout) Settings(android.provider.Settings) JoinGroupAlert(org.telegram.ui.Components.JoinGroupAlert) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) LinearGradient(android.graphics.LinearGradient) Parcelable(android.os.Parcelable) R(org.telegram.messenger.R) LanguageCell(org.telegram.ui.Cells.LanguageCell) SideMenultItemAnimator(org.telegram.ui.Components.SideMenultItemAnimator) TextUtils(android.text.TextUtils) InputStreamReader(java.io.InputStreamReader) DrawerLayoutContainer(org.telegram.ui.ActionBar.DrawerLayoutContainer) File(java.io.File) Gravity(android.view.Gravity) UserObject(org.telegram.messenger.UserObject) DrawerAddCell(org.telegram.ui.Cells.DrawerAddCell) SharedPreferences(android.content.SharedPreferences) TypedValue(android.util.TypedValue) ContactsController(org.telegram.messenger.ContactsController) MessagesStorage(org.telegram.messenger.MessagesStorage) Configuration(android.content.res.Configuration) Easings(org.telegram.ui.Components.Easings) BufferedReader(java.io.BufferedReader) ChatObject(org.telegram.messenger.ChatObject) CameraController(org.telegram.messenger.camera.CameraController) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) AudioPlayerAlert(org.telegram.ui.Components.AudioPlayerAlert) VoIPHelper(org.telegram.ui.Components.voip.VoIPHelper) ActionMode(android.view.ActionMode) LinearLayout(android.widget.LinearLayout) RadialProgress2(org.telegram.ui.Components.RadialProgress2) PackageManager(android.content.pm.PackageManager) Date(java.util.Date) DrawerLayoutAdapter(org.telegram.ui.Adapters.DrawerLayoutAdapter) WindowManager(android.view.WindowManager) AccountInstance(org.telegram.messenger.AccountInstance) AndroidUtilities(org.telegram.messenger.AndroidUtilities) CubicBezierInterpolator(org.telegram.ui.Components.CubicBezierInterpolator) VideoCapturerDevice(org.telegram.messenger.voip.VideoCapturerDevice) Animator(android.animation.Animator) ApplicationLoader(org.telegram.messenger.ApplicationLoader) ContactsContract(android.provider.ContactsContract) MediaController(org.telegram.messenger.MediaController) ThemeEditorView(org.telegram.ui.Components.ThemeEditorView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) TermsOfServiceView(org.telegram.ui.Components.TermsOfServiceView) Matrix(android.graphics.Matrix) ParseException(java.text.ParseException) DateFormat(java.text.DateFormat) ImageLoader(org.telegram.messenger.ImageLoader) DrawerUserCell(org.telegram.ui.Cells.DrawerUserCell) Utilities(org.telegram.messenger.Utilities) RLottieImageView(org.telegram.ui.Components.RLottieImageView) ObjectAnimator(android.animation.ObjectAnimator) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) BitmapDrawable(android.graphics.drawable.BitmapDrawable) ViewAnimationUtils(android.view.ViewAnimationUtils) SendMessagesHelper(org.telegram.messenger.SendMessagesHelper) ConnectionsManager(org.telegram.tgnet.ConnectionsManager) BlockingUpdateView(org.telegram.ui.Components.BlockingUpdateView) ViewGroup(android.view.ViewGroup) UserConfig(org.telegram.messenger.UserConfig) List(java.util.List) TextView(android.widget.TextView) PhonebookShareAlert(org.telegram.ui.Components.PhonebookShareAlert) RelativeLayout(android.widget.RelativeLayout) Pattern(java.util.regex.Pattern) Location(android.location.Location) LocationManager(android.location.LocationManager) Window(android.view.Window) ActivityManager(android.app.ActivityManager) Context(android.content.Context) KeyEvent(android.view.KeyEvent) VoIPService(org.telegram.messenger.voip.VoIPService) Theme(org.telegram.ui.ActionBar.Theme) BulletinFactory(org.telegram.ui.Components.BulletinFactory) Intent(android.content.Intent) LocaleController(org.telegram.messenger.LocaleController) HashMap(java.util.HashMap) ActionBarLayout(org.telegram.ui.ActionBar.ActionBarLayout) SharingLocationsAlert(org.telegram.ui.Components.SharingLocationsAlert) AudioManager(android.media.AudioManager) MotionEvent(android.view.MotionEvent) TLObject(org.telegram.tgnet.TLObject) MessageObject(org.telegram.messenger.MessageObject) SharedConfig(org.telegram.messenger.SharedConfig) BuildVars(org.telegram.messenger.BuildVars) MediaDataController(org.telegram.messenger.MediaDataController) Build(android.os.Build) ShortcutInfoCompat(androidx.core.content.pm.ShortcutInfoCompat) Cursor(android.database.Cursor) Browser(org.telegram.messenger.browser.Browser) EmbedBottomSheet(org.telegram.ui.Components.EmbedBottomSheet) DialogObject(org.telegram.messenger.DialogObject) Point(android.graphics.Point) LayoutHelper(org.telegram.ui.Components.LayoutHelper) FileLog(org.telegram.messenger.FileLog) MessagesController(org.telegram.messenger.MessagesController) Color(android.graphics.Color) StatFs(android.os.StatFs) Bitmap(android.graphics.Bitmap) Base64(android.util.Base64) ViewTreeObserver(android.view.ViewTreeObserver) UpdateAppAlertDialog(org.telegram.ui.Components.UpdateAppAlertDialog) Activity(android.app.Activity) RecyclerListView(org.telegram.ui.Components.RecyclerListView) StickerSetBulletinLayout(org.telegram.ui.Components.StickerSetBulletinLayout) RLottieDrawable(org.telegram.ui.Components.RLottieDrawable) InputStream(java.io.InputStream) Set(java.util.Set) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Bundle(android.os.Bundle) Paint(android.graphics.Paint) Point(android.graphics.Point) ParseException(java.text.ParseException) TLRPC(org.telegram.tgnet.TLRPC) BufferedReader(java.io.BufferedReader)

Example 69 with AlertDialog

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

the class LanguageSelectActivity method createView.

@Override
public View createView(Context context) {
    searching = false;
    searchWas = false;
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(true);
    actionBar.setTitle(LocaleController.getString("Language", R.string.Language));
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {

        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                finishFragment();
            }
        }
    });
    ActionBarMenu menu = actionBar.createMenu();
    ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_search).setIsSearchField(true).setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() {

        @Override
        public void onSearchExpand() {
            searching = true;
        }

        @Override
        public void onSearchCollapse() {
            search(null);
            searching = false;
            searchWas = false;
            if (listView != null) {
                emptyView.setVisibility(View.GONE);
                listView.setAdapter(listAdapter);
            }
        }

        @Override
        public void onTextChanged(EditText editText) {
            String text = editText.getText().toString();
            search(text);
            if (text.length() != 0) {
                searchWas = true;
                if (listView != null) {
                    listView.setAdapter(searchListViewAdapter);
                }
            } else {
                searching = false;
                searchWas = false;
                if (listView != null) {
                    emptyView.setVisibility(View.GONE);
                    listView.setAdapter(listAdapter);
                }
            }
        }
    });
    item.setSearchFieldHint(LocaleController.getString("Search", R.string.Search));
    listAdapter = new ListAdapter(context, false);
    searchListViewAdapter = new ListAdapter(context, true);
    fragmentView = new FrameLayout(context);
    fragmentView.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundGray));
    FrameLayout frameLayout = (FrameLayout) fragmentView;
    emptyView = new EmptyTextProgressView(context);
    emptyView.setText(LocaleController.getString("NoResult", R.string.NoResult));
    emptyView.showTextView();
    emptyView.setShowAtCenter(true);
    frameLayout.addView(emptyView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    listView = new RecyclerListView(context);
    listView.setEmptyView(emptyView);
    listView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
    listView.setVerticalScrollBarEnabled(false);
    listView.setAdapter(listAdapter);
    frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    listView.setOnItemClickListener((view, position) -> {
        try {
            if (getParentActivity() == null || parentLayout == null || !(view instanceof TextRadioCell)) {
                return;
            }
            boolean search = listView.getAdapter() == searchListViewAdapter;
            if (!search) {
                position -= 2;
            }
            LocaleController.LocaleInfo localeInfo;
            if (search) {
                localeInfo = searchResult.get(position);
            } else if (!unofficialLanguages.isEmpty() && position >= 0 && position < unofficialLanguages.size()) {
                localeInfo = unofficialLanguages.get(position);
            } else {
                if (!unofficialLanguages.isEmpty()) {
                    position -= unofficialLanguages.size() + 1;
                }
                localeInfo = sortedLanguages.get(position);
            }
            if (localeInfo != null) {
                LocaleController.LocaleInfo prevLocale = LocaleController.getInstance().getCurrentLocaleInfo();
                LocaleController.getInstance().applyLanguage(localeInfo, true, false, false, true, currentAccount);
                parentLayout.rebuildAllFragmentViews(false, false);
                String langCode = localeInfo.pluralLangCode, prevLangCode = prevLocale.pluralLangCode;
                SharedPreferences preferences = MessagesController.getGlobalMainSettings();
                HashSet<String> selectedLanguages = RestrictedLanguagesSelectActivity.getRestrictedLanguages();
                HashSet<String> newSelectedLanguages = new HashSet<String>(selectedLanguages);
                if (selectedLanguages.contains(langCode)) {
                    newSelectedLanguages.removeIf(s -> s != null && s.equals(langCode));
                    if (!selectedLanguages.contains(prevLangCode))
                        newSelectedLanguages.add(prevLangCode);
                }
                preferences.edit().putStringSet("translate_button_restricted_languages", newSelectedLanguages).apply();
                finishFragment();
            }
        } catch (Exception e) {
            FileLog.e(e);
        }
    });
    listView.setOnItemLongClickListener((view, position) -> {
        try {
            if (getParentActivity() == null || parentLayout == null || !(view instanceof TextRadioCell)) {
                return false;
            }
            boolean search = listView.getAdapter() == searchListViewAdapter;
            if (!search) {
                position -= 2;
            }
            LocaleController.LocaleInfo localeInfo;
            if (search) {
                localeInfo = searchResult.get(position);
            } else if (!unofficialLanguages.isEmpty() && position >= 0 && position < unofficialLanguages.size()) {
                localeInfo = unofficialLanguages.get(position);
            } else {
                if (!unofficialLanguages.isEmpty()) {
                    position -= unofficialLanguages.size() + 1;
                }
                localeInfo = sortedLanguages.get(position);
            }
            if (localeInfo == null || localeInfo.pathToFile == null || localeInfo.isRemote() && localeInfo.serverIndex != Integer.MAX_VALUE) {
                return false;
            }
            final LocaleController.LocaleInfo finalLocaleInfo = localeInfo;
            AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
            builder.setTitle(LocaleController.getString("DeleteLocalizationTitle", R.string.DeleteLocalizationTitle));
            builder.setMessage(AndroidUtilities.replaceTags(LocaleController.formatString("DeleteLocalizationText", R.string.DeleteLocalizationText, localeInfo.name)));
            builder.setPositiveButton(LocaleController.getString("Delete", R.string.Delete), (dialogInterface, i) -> {
                if (LocaleController.getInstance().deleteLanguage(finalLocaleInfo, currentAccount)) {
                    fillLanguages();
                    if (searchResult != null) {
                        searchResult.remove(finalLocaleInfo);
                    }
                    if (listAdapter != null) {
                        listAdapter.notifyDataSetChanged();
                    }
                    if (searchListViewAdapter != null) {
                        searchListViewAdapter.notifyDataSetChanged();
                    }
                }
            });
            builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
            AlertDialog alertDialog = builder.create();
            showDialog(alertDialog);
            TextView button = (TextView) alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
            if (button != null) {
                button.setTextColor(Theme.getColor(Theme.key_dialogTextRed2));
            }
        } catch (Exception e) {
            FileLog.e(e);
        }
        return true;
    });
    listView.setOnScrollListener(new RecyclerView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus());
            }
        }
    });
    return fragmentView;
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) RecyclerListView(org.telegram.ui.Components.RecyclerListView) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) TextRadioCell(org.telegram.ui.Cells.TextRadioCell) TextView(android.widget.TextView) ActionBar(org.telegram.ui.ActionBar.ActionBar) HashSet(java.util.HashSet) EditText(android.widget.EditText) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) LocaleController(org.telegram.messenger.LocaleController) SharedPreferences(android.content.SharedPreferences) EmptyTextProgressView(org.telegram.ui.Components.EmptyTextProgressView) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) FrameLayout(android.widget.FrameLayout) RecyclerView(androidx.recyclerview.widget.RecyclerView)

Example 70 with AlertDialog

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

the class Browser method openUrl.

public static void openUrl(final Context context, Uri uri, final boolean allowCustom, boolean tryTelegraph) {
    if (context == null || uri == null) {
        return;
    }
    final int currentAccount = UserConfig.selectedAccount;
    boolean[] forceBrowser = new boolean[] { false };
    boolean internalUri = isInternalUri(uri, forceBrowser);
    if (tryTelegraph) {
        try {
            String host = uri.getHost().toLowerCase();
            if (isTelegraphUrl(host, true) || uri.toString().toLowerCase().contains("telegram.org/faq") || uri.toString().toLowerCase().contains("telegram.org/privacy")) {
                final AlertDialog[] progressDialog = new AlertDialog[] { new AlertDialog(context, 3) };
                Uri finalUri = uri;
                TLRPC.TL_messages_getWebPagePreview req = new TLRPC.TL_messages_getWebPagePreview();
                req.message = uri.toString();
                final int reqId = ConnectionsManager.getInstance(UserConfig.selectedAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
                    try {
                        progressDialog[0].dismiss();
                    } catch (Throwable ignore) {
                    }
                    progressDialog[0] = null;
                    boolean ok = false;
                    if (response instanceof TLRPC.TL_messageMediaWebPage) {
                        TLRPC.TL_messageMediaWebPage webPage = (TLRPC.TL_messageMediaWebPage) response;
                        if (webPage.webpage instanceof TLRPC.TL_webPage && webPage.webpage.cached_page != null) {
                            NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.openArticle, webPage.webpage, finalUri.toString());
                            ok = true;
                        }
                    }
                    if (!ok) {
                        openUrl(context, finalUri, allowCustom, false);
                    }
                }));
                AndroidUtilities.runOnUIThread(() -> {
                    if (progressDialog[0] == null) {
                        return;
                    }
                    try {
                        progressDialog[0].setOnCancelListener(dialog -> ConnectionsManager.getInstance(UserConfig.selectedAccount).cancelRequest(reqId, true));
                        progressDialog[0].show();
                    } catch (Exception ignore) {
                    }
                }, 1000);
                return;
            }
        } catch (Exception ignore) {
        }
    }
    try {
        String scheme = uri.getScheme() != null ? uri.getScheme().toLowerCase() : "";
        if ("http".equals(scheme) || "https".equals(scheme)) {
            try {
                uri = uri.normalizeScheme();
            } catch (Exception e) {
                FileLog.e(e);
            }
        }
        String host = uri.getHost() != null ? uri.getHost().toLowerCase() : "";
        if (AccountInstance.getInstance(currentAccount).getMessagesController().autologinDomains.contains(host)) {
            String token = "autologin_token=" + URLEncoder.encode(AccountInstance.getInstance(UserConfig.selectedAccount).getMessagesController().autologinToken, "UTF-8");
            String url = uri.toString();
            int idx = url.indexOf("://");
            String path = idx >= 0 ? url.substring(idx + 3) : url;
            String fragment = uri.getEncodedFragment();
            String finalPath = fragment == null ? path : path.substring(0, path.indexOf("#" + fragment));
            if (finalPath.indexOf('?') >= 0) {
                finalPath += "&" + token;
            } else {
                finalPath += "?" + token;
            }
            if (fragment != null) {
                finalPath += "#" + fragment;
            }
            uri = Uri.parse("https://" + finalPath);
        }
        if (allowCustom && SharedConfig.customTabs && !internalUri && !scheme.equals("tel")) {
            String[] browserPackageNames = null;
            try {
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
                List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(browserIntent, 0);
                if (list != null && !list.isEmpty()) {
                    browserPackageNames = new String[list.size()];
                    for (int a = 0; a < list.size(); a++) {
                        browserPackageNames[a] = list.get(a).activityInfo.packageName;
                        if (BuildVars.LOGS_ENABLED) {
                            FileLog.d("default browser name = " + browserPackageNames[a]);
                        }
                    }
                }
            } catch (Exception ignore) {
            }
            List<ResolveInfo> allActivities = null;
            try {
                Intent viewIntent = new Intent(Intent.ACTION_VIEW, uri);
                allActivities = context.getPackageManager().queryIntentActivities(viewIntent, 0);
                if (browserPackageNames != null) {
                    for (int a = 0; a < allActivities.size(); a++) {
                        for (int b = 0; b < browserPackageNames.length; b++) {
                            if (browserPackageNames[b].equals(allActivities.get(a).activityInfo.packageName)) {
                                allActivities.remove(a);
                                a--;
                                break;
                            }
                        }
                    }
                } else {
                    for (int a = 0; a < allActivities.size(); a++) {
                        if (allActivities.get(a).activityInfo.packageName.toLowerCase().contains("browser") || allActivities.get(a).activityInfo.packageName.toLowerCase().contains("chrome")) {
                            allActivities.remove(a);
                            a--;
                        }
                    }
                }
                if (BuildVars.LOGS_ENABLED) {
                    for (int a = 0; a < allActivities.size(); a++) {
                        FileLog.d("device has " + allActivities.get(a).activityInfo.packageName + " to open " + uri.toString());
                    }
                }
            } catch (Exception ignore) {
            }
            if (forceBrowser[0] || allActivities == null || allActivities.isEmpty()) {
                Intent share = new Intent(ApplicationLoader.applicationContext, ShareBroadcastReceiver.class);
                share.setAction(Intent.ACTION_SEND);
                PendingIntent copy = PendingIntent.getBroadcast(ApplicationLoader.applicationContext, 0, new Intent(ApplicationLoader.applicationContext, CustomTabsCopyReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);
                CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder(getSession());
                builder.addMenuItem(LocaleController.getString("CopyLink", R.string.CopyLink), copy);
                builder.setToolbarColor(Theme.getColor(Theme.key_actionBarBrowser));
                builder.setShowTitle(true);
                builder.setActionButton(BitmapFactory.decodeResource(context.getResources(), R.drawable.abc_ic_menu_share_mtrl_alpha), LocaleController.getString("ShareFile", R.string.ShareFile), PendingIntent.getBroadcast(ApplicationLoader.applicationContext, 0, share, 0), true);
                CustomTabsIntent intent = builder.build();
                intent.setUseNewTask();
                intent.launchUrl(context, uri);
                return;
            }
        }
    } catch (Exception e) {
        FileLog.e(e);
    }
    try {
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        if (internalUri) {
            ComponentName componentName = new ComponentName(context.getPackageName(), LaunchActivity.class.getName());
            intent.setComponent(componentName);
        }
        intent.putExtra(android.provider.Browser.EXTRA_CREATE_NEW_TAB, true);
        intent.putExtra(android.provider.Browser.EXTRA_APPLICATION_ID, context.getPackageName());
        context.startActivity(intent);
    } catch (Exception e) {
        FileLog.e(e);
    }
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) Uri(android.net.Uri) TLRPC(org.telegram.tgnet.TLRPC) LaunchActivity(org.telegram.ui.LaunchActivity) ResolveInfo(android.content.pm.ResolveInfo) ComponentName(android.content.ComponentName) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) CustomTabsIntent(org.telegram.messenger.support.customtabs.CustomTabsIntent) CustomTabsIntent(org.telegram.messenger.support.customtabs.CustomTabsIntent) PendingIntent(android.app.PendingIntent) CustomTabsCopyReceiver(org.telegram.messenger.CustomTabsCopyReceiver)

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