Search in sources :

Example 26 with AlertDialog

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

the class TwoStepVerificationSetupActivity method needShowProgress.

private void needShowProgress() {
    if (getParentActivity() == null || getParentActivity().isFinishing() || progressDialog != null) {
        return;
    }
    progressDialog = new AlertDialog(getParentActivity(), 3);
    progressDialog.setCanCacnel(false);
    progressDialog.show();
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog)

Example 27 with AlertDialog

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

the class LocationActivity method createView.

@Override
public View createView(Context context) {
    searchWas = false;
    searching = false;
    searchInProgress = false;
    if (adapter != null) {
        adapter.destroy();
    }
    if (searchAdapter != null) {
        searchAdapter.destroy();
    }
    if (chatLocation != null) {
        userLocation = new Location("network");
        userLocation.setLatitude(chatLocation.geo_point.lat);
        userLocation.setLongitude(chatLocation.geo_point._long);
    } else if (messageObject != null) {
        userLocation = new Location("network");
        userLocation.setLatitude(messageObject.messageOwner.media.geo.lat);
        userLocation.setLongitude(messageObject.messageOwner.media.geo._long);
    }
    locationDenied = Build.VERSION.SDK_INT >= 23 && getParentActivity() != null && getParentActivity().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED;
    actionBar.setBackgroundColor(Theme.getColor(Theme.key_dialogBackground));
    actionBar.setTitleColor(Theme.getColor(Theme.key_dialogTextBlack));
    actionBar.setItemsColor(Theme.getColor(Theme.key_dialogTextBlack), false);
    actionBar.setItemsBackgroundColor(Theme.getColor(Theme.key_dialogButtonSelector), false);
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(true);
    if (AndroidUtilities.isTablet()) {
        actionBar.setOccupyStatusBar(false);
    }
    actionBar.setAddToContainer(false);
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {

        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                finishFragment();
            } else if (id == open_in) {
                try {
                    double lat = messageObject.messageOwner.media.geo.lat;
                    double lon = messageObject.messageOwner.media.geo._long;
                    getParentActivity().startActivity(new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("geo:" + lat + "," + lon + "?q=" + lat + "," + lon)));
                } catch (Exception e) {
                    FileLog.e(e);
                }
            } else if (id == share_live_location) {
                openShareLiveLocation(0);
            }
        }
    });
    ActionBarMenu menu = actionBar.createMenu();
    if (chatLocation != null) {
        actionBar.setTitle(LocaleController.getString("ChatLocation", R.string.ChatLocation));
    } else if (messageObject != null) {
        if (messageObject.isLiveLocation()) {
            actionBar.setTitle(LocaleController.getString("AttachLiveLocation", R.string.AttachLiveLocation));
        } else {
            if (messageObject.messageOwner.media.title != null && messageObject.messageOwner.media.title.length() > 0) {
                actionBar.setTitle(LocaleController.getString("SharedPlace", R.string.SharedPlace));
            } else {
                actionBar.setTitle(LocaleController.getString("ChatLocation", R.string.ChatLocation));
            }
            otherItem = menu.addItem(0, R.drawable.ic_ab_other);
            otherItem.addSubItem(open_in, R.drawable.msg_openin, LocaleController.getString("OpenInExternalApp", R.string.OpenInExternalApp));
            if (!getLocationController().isSharingLocation(dialogId)) {
                otherItem.addSubItem(share_live_location, R.drawable.menu_location, LocaleController.getString("SendLiveLocationMenu", R.string.SendLiveLocationMenu));
            }
            otherItem.setContentDescription(LocaleController.getString("AccDescrMoreOptions", R.string.AccDescrMoreOptions));
        }
    } else {
        actionBar.setTitle(LocaleController.getString("ShareLocation", R.string.ShareLocation));
        if (locationType != LOCATION_TYPE_GROUP) {
            overlayView = new MapOverlayView(context);
            searchItem = menu.addItem(0, R.drawable.ic_ab_search).setIsSearchField(true).setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() {

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

                @Override
                public void onSearchCollapse() {
                    searching = false;
                    searchWas = false;
                    searchAdapter.searchDelayed(null, null);
                    updateEmptyView();
                }

                @Override
                public void onTextChanged(EditText editText) {
                    if (searchAdapter == null) {
                        return;
                    }
                    String text = editText.getText().toString();
                    if (text.length() != 0) {
                        searchWas = true;
                        searchItem.setShowSearchProgress(true);
                        if (otherItem != null) {
                            otherItem.setVisibility(View.GONE);
                        }
                        listView.setVisibility(View.GONE);
                        mapViewClip.setVisibility(View.GONE);
                        if (searchListView.getAdapter() != searchAdapter) {
                            searchListView.setAdapter(searchAdapter);
                        }
                        searchListView.setVisibility(View.VISIBLE);
                        searchInProgress = searchAdapter.getItemCount() == 0;
                    } else {
                        if (otherItem != null) {
                            otherItem.setVisibility(View.VISIBLE);
                        }
                        listView.setVisibility(View.VISIBLE);
                        mapViewClip.setVisibility(View.VISIBLE);
                        searchListView.setAdapter(null);
                        searchListView.setVisibility(View.GONE);
                    }
                    updateEmptyView();
                    searchAdapter.searchDelayed(text, userLocation);
                }
            });
            searchItem.setSearchFieldHint(LocaleController.getString("Search", R.string.Search));
            searchItem.setContentDescription(LocaleController.getString("Search", R.string.Search));
            EditTextBoldCursor editText = searchItem.getSearchField();
            editText.setTextColor(Theme.getColor(Theme.key_dialogTextBlack));
            editText.setCursorColor(Theme.getColor(Theme.key_dialogTextBlack));
            editText.setHintTextColor(Theme.getColor(Theme.key_chat_messagePanelHint));
        }
    }
    fragmentView = new FrameLayout(context) {

        private boolean first = true;

        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            super.onLayout(changed, left, top, right, bottom);
            if (changed) {
                fixLayoutInternal(first);
                first = false;
            } else {
                updateClipView(true);
            }
        }

        @Override
        protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
            boolean result = super.drawChild(canvas, child, drawingTime);
            if (child == actionBar && parentLayout != null) {
                parentLayout.drawHeaderShadow(canvas, actionBar.getMeasuredHeight());
            }
            return result;
        }
    };
    FrameLayout frameLayout = (FrameLayout) fragmentView;
    fragmentView.setBackgroundColor(Theme.getColor(Theme.key_dialogBackground));
    shadowDrawable = context.getResources().getDrawable(R.drawable.sheet_shadow_round).mutate();
    shadowDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogBackground), PorterDuff.Mode.MULTIPLY));
    Rect padding = new Rect();
    shadowDrawable.getPadding(padding);
    FrameLayout.LayoutParams layoutParams;
    if (locationType == LOCATION_TYPE_SEND || locationType == LOCATION_TYPE_SEND_WITH_LIVE) {
        layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, AndroidUtilities.dp(21) + padding.top);
    } else {
        layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, AndroidUtilities.dp(6) + padding.top);
    }
    layoutParams.gravity = Gravity.LEFT | Gravity.BOTTOM;
    mapViewClip = new FrameLayout(context) {

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            if (overlayView != null) {
                overlayView.updatePositions();
            }
        }
    };
    mapViewClip.setBackgroundDrawable(new MapPlaceholderDrawable());
    if (messageObject == null && (locationType == LOCATION_TYPE_SEND || locationType == LOCATION_TYPE_SEND_WITH_LIVE)) {
        searchAreaButton = new SearchButton(context);
        searchAreaButton.setTranslationX(-AndroidUtilities.dp(80));
        Drawable drawable = Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(40), Theme.getColor(Theme.key_location_actionBackground), Theme.getColor(Theme.key_location_actionPressedBackground));
        if (Build.VERSION.SDK_INT < 21) {
            Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.places_btn).mutate();
            shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY));
            CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, AndroidUtilities.dp(2), AndroidUtilities.dp(2));
            combinedDrawable.setFullsize(true);
            drawable = combinedDrawable;
        } else {
            StateListAnimator animator = new StateListAnimator();
            animator.addState(new int[] { android.R.attr.state_pressed }, ObjectAnimator.ofFloat(searchAreaButton, View.TRANSLATION_Z, AndroidUtilities.dp(2), AndroidUtilities.dp(4)).setDuration(200));
            animator.addState(new int[] {}, ObjectAnimator.ofFloat(searchAreaButton, View.TRANSLATION_Z, AndroidUtilities.dp(4), AndroidUtilities.dp(2)).setDuration(200));
            searchAreaButton.setStateListAnimator(animator);
            searchAreaButton.setOutlineProvider(new ViewOutlineProvider() {

                @SuppressLint("NewApi")
                @Override
                public void getOutline(View view, Outline outline) {
                    outline.setRoundRect(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight(), view.getMeasuredHeight() / 2);
                }
            });
        }
        searchAreaButton.setBackgroundDrawable(drawable);
        searchAreaButton.setTextColor(Theme.getColor(Theme.key_location_actionActiveIcon));
        searchAreaButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
        searchAreaButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
        searchAreaButton.setText(LocaleController.getString("PlacesInThisArea", R.string.PlacesInThisArea));
        searchAreaButton.setGravity(Gravity.CENTER);
        searchAreaButton.setPadding(AndroidUtilities.dp(20), 0, AndroidUtilities.dp(20), 0);
        mapViewClip.addView(searchAreaButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, Build.VERSION.SDK_INT >= 21 ? 40 : 44, Gravity.CENTER_HORIZONTAL | Gravity.TOP, 80, 12, 80, 0));
        searchAreaButton.setOnClickListener(v -> {
            showSearchPlacesButton(false);
            adapter.searchPlacesWithQuery(null, userLocation, true, true);
            searchedForCustomLocations = true;
            showResults();
        });
    }
    mapTypeButton = new ActionBarMenuItem(context, null, 0, Theme.getColor(Theme.key_location_actionIcon));
    mapTypeButton.setClickable(true);
    mapTypeButton.setSubMenuOpenSide(2);
    mapTypeButton.setAdditionalXOffset(AndroidUtilities.dp(10));
    mapTypeButton.setAdditionalYOffset(-AndroidUtilities.dp(10));
    mapTypeButton.addSubItem(map_list_menu_osm, R.drawable.msg_map, "Standard OSM");
    mapTypeButton.addSubItem(map_list_menu_wiki, R.drawable.msg_map, "Wikimedia");
    mapTypeButton.addSubItem(map_list_menu_cartodark, R.drawable.msg_map, "Carto Dark");
    mapTypeButton.setContentDescription(LocaleController.getString("AccDescrMoreOptions", R.string.AccDescrMoreOptions));
    Drawable drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(40), Theme.getColor(Theme.key_location_actionBackground), Theme.getColor(Theme.key_location_actionPressedBackground));
    if (Build.VERSION.SDK_INT < 21) {
        Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow_profile).mutate();
        shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY));
        CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0);
        combinedDrawable.setIconSize(AndroidUtilities.dp(40), AndroidUtilities.dp(40));
        drawable = combinedDrawable;
    } else {
        StateListAnimator animator = new StateListAnimator();
        animator.addState(new int[] { android.R.attr.state_pressed }, ObjectAnimator.ofFloat(mapTypeButton, View.TRANSLATION_Z, AndroidUtilities.dp(2), AndroidUtilities.dp(4)).setDuration(200));
        animator.addState(new int[] {}, ObjectAnimator.ofFloat(mapTypeButton, View.TRANSLATION_Z, AndroidUtilities.dp(4), AndroidUtilities.dp(2)).setDuration(200));
        mapTypeButton.setStateListAnimator(animator);
        mapTypeButton.setOutlineProvider(new ViewOutlineProvider() {

            @SuppressLint("NewApi")
            @Override
            public void getOutline(View view, Outline outline) {
                outline.setOval(0, 0, AndroidUtilities.dp(40), AndroidUtilities.dp(40));
            }
        });
    }
    mapTypeButton.setBackgroundDrawable(drawable);
    mapTypeButton.setIcon(R.drawable.location_type);
    mapViewClip.addView(mapTypeButton, LayoutHelper.createFrame(Build.VERSION.SDK_INT >= 21 ? 40 : 44, Build.VERSION.SDK_INT >= 21 ? 40 : 44, Gravity.RIGHT | Gravity.TOP, 0, 12, 12, 0));
    mapTypeButton.setOnClickListener(v -> mapTypeButton.toggleSubMenu());
    mapTypeButton.setDelegate(id -> {
        if (mapView == null) {
            return;
        }
        if (id == map_list_menu_osm) {
            attributionOverlay.setText(Html.fromHtml("© <a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a> contributors"));
            mapView.setTileSource(TileSourceFactory.MAPNIK);
        } else if (id == map_list_menu_wiki) {
            // Create a custom tile source
            ITileSource tileSource = new XYTileSource("Wikimedia", 0, 19, 256, ".png", new String[] { "https://maps.wikimedia.org/osm-intl/" }, "© OpenStreetMap contributors");
            attributionOverlay.setText(Html.fromHtml("© <a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a> contributors"));
            mapView.setTileSource(tileSource);
        } else if (id == map_list_menu_cartodark) {
            // Create a custom tile source
            ITileSource tileSource = new XYTileSource("Carto Dark", 0, 20, 256, ".png", new String[] { "https://cartodb-basemaps-a.global.ssl.fastly.net/dark_all/", "https://cartodb-basemaps-b.global.ssl.fastly.net/dark_all/", "https://cartodb-basemaps-c.global.ssl.fastly.net/dark_all/", "https://cartodb-basemaps-d.global.ssl.fastly.net/dark_all/" }, "© OpenStreetMap contributors, © CARTO");
            attributionOverlay.setText(Html.fromHtml("© <a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a> contributors, © <a href=\"https://carto.com/attributions\">CARTO</a>"));
            mapView.setTileSource(tileSource);
        }
    });
    mapViewClip.addView(getAttributionOverlay(context), LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.BOTTOM, LocaleController.isRTL ? 0 : 4, 0, LocaleController.isRTL ? 4 : 0, 20));
    locationButton = new ImageView(context);
    drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(40), Theme.getColor(Theme.key_location_actionBackground), Theme.getColor(Theme.key_location_actionPressedBackground));
    if (Build.VERSION.SDK_INT < 21) {
        Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow_profile).mutate();
        shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY));
        CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0);
        combinedDrawable.setIconSize(AndroidUtilities.dp(40), AndroidUtilities.dp(40));
        drawable = combinedDrawable;
    } else {
        StateListAnimator animator = new StateListAnimator();
        animator.addState(new int[] { android.R.attr.state_pressed }, ObjectAnimator.ofFloat(locationButton, View.TRANSLATION_Z, AndroidUtilities.dp(2), AndroidUtilities.dp(4)).setDuration(200));
        animator.addState(new int[] {}, ObjectAnimator.ofFloat(locationButton, View.TRANSLATION_Z, AndroidUtilities.dp(4), AndroidUtilities.dp(2)).setDuration(200));
        locationButton.setStateListAnimator(animator);
        locationButton.setOutlineProvider(new ViewOutlineProvider() {

            @SuppressLint("NewApi")
            @Override
            public void getOutline(View view, Outline outline) {
                outline.setOval(0, 0, AndroidUtilities.dp(40), AndroidUtilities.dp(40));
            }
        });
    }
    locationButton.setBackgroundDrawable(drawable);
    locationButton.setImageResource(R.drawable.location_current);
    locationButton.setScaleType(ImageView.ScaleType.CENTER);
    locationButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_location_actionActiveIcon), PorterDuff.Mode.MULTIPLY));
    locationButton.setTag(Theme.key_location_actionActiveIcon);
    locationButton.setContentDescription(LocaleController.getString("AccDescrMyLocation", R.string.AccDescrMyLocation));
    FrameLayout.LayoutParams layoutParams1 = LayoutHelper.createFrame(Build.VERSION.SDK_INT >= 21 ? 40 : 44, Build.VERSION.SDK_INT >= 21 ? 40 : 44, Gravity.RIGHT | Gravity.BOTTOM, 0, 0, 12, 12);
    layoutParams1.bottomMargin += layoutParams.height - padding.top;
    mapViewClip.addView(locationButton, layoutParams1);
    locationButton.setOnClickListener(v -> {
        if (Build.VERSION.SDK_INT >= 23) {
            Activity activity = getParentActivity();
            if (activity != null) {
                if (activity.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    showPermissionAlert(false);
                    return;
                }
            }
        }
        if (!checkGpsEnabled()) {
            return;
        }
        if (messageObject != null || chatLocation != null) {
            if (myLocation != null && mapView != null) {
                final IMapController controller = mapView.getController();
                controller.animateTo(new GeoPoint(myLocation.getLatitude(), myLocation.getLongitude()), mapView.getMaxZoomLevel() - 2, null);
            }
        } else {
            if (myLocation != null && mapView != null) {
                locationButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_location_actionActiveIcon), PorterDuff.Mode.MULTIPLY));
                locationButton.setTag(Theme.key_location_actionActiveIcon);
                adapter.setCustomLocation(null);
                userLocationMoved = false;
                showSearchPlacesButton(false);
                final IMapController controller = mapView.getController();
                controller.animateTo(new GeoPoint(myLocation.getLatitude(), myLocation.getLongitude()));
                if (searchedForCustomLocations) {
                    if (myLocation != null) {
                        adapter.searchPlacesWithQuery(null, myLocation, true, true);
                    }
                    searchedForCustomLocations = false;
                    showResults();
                }
            }
        }
        removeInfoView();
    });
    proximityButton = new ImageView(context);
    drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(40), Theme.getColor(Theme.key_location_actionBackground), Theme.getColor(Theme.key_location_actionPressedBackground));
    if (Build.VERSION.SDK_INT < 21) {
        Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow_profile).mutate();
        shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY));
        CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0);
        combinedDrawable.setIconSize(AndroidUtilities.dp(40), AndroidUtilities.dp(40));
        drawable = combinedDrawable;
    } else {
        StateListAnimator animator = new StateListAnimator();
        animator.addState(new int[] { android.R.attr.state_pressed }, ObjectAnimator.ofFloat(proximityButton, View.TRANSLATION_Z, AndroidUtilities.dp(2), AndroidUtilities.dp(4)).setDuration(200));
        animator.addState(new int[] {}, ObjectAnimator.ofFloat(proximityButton, View.TRANSLATION_Z, AndroidUtilities.dp(4), AndroidUtilities.dp(2)).setDuration(200));
        proximityButton.setStateListAnimator(animator);
        proximityButton.setOutlineProvider(new ViewOutlineProvider() {

            @SuppressLint("NewApi")
            @Override
            public void getOutline(View view, Outline outline) {
                outline.setOval(0, 0, AndroidUtilities.dp(40), AndroidUtilities.dp(40));
            }
        });
    }
    proximityButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_location_actionIcon), PorterDuff.Mode.MULTIPLY));
    proximityButton.setBackgroundDrawable(drawable);
    proximityButton.setScaleType(ImageView.ScaleType.CENTER);
    proximityButton.setContentDescription(LocaleController.getString("AccDescrLocationNotify", R.string.AccDescrLocationNotify));
    mapViewClip.addView(proximityButton, LayoutHelper.createFrame(Build.VERSION.SDK_INT >= 21 ? 40 : 44, Build.VERSION.SDK_INT >= 21 ? 40 : 44, Gravity.RIGHT | Gravity.TOP, 0, 12 + 50, 12, 0));
    proximityButton.setOnClickListener(v -> {
        if (getParentActivity() == null || myLocation == null || !checkGpsEnabled() || mapView == null) {
            return;
        }
        if (hintView != null) {
            hintView.hide();
        }
        SharedPreferences preferences = MessagesController.getGlobalMainSettings();
        preferences.edit().putInt("proximityhint", 3).commit();
        LocationController.SharingLocationInfo info = getLocationController().getSharingLocationInfo(dialogId);
        if (canUndo) {
            undoView[0].hide(true, 1);
        }
        if (info != null && info.proximityMeters > 0) {
            proximityButton.setImageResource(R.drawable.msg_location_alert);
            if (proximityCircle != null) {
                mapView.getOverlayManager().remove(proximityCircle);
                proximityCircle = null;
            }
            canUndo = true;
            getUndoView().showWithAction(0, UndoView.ACTION_PROXIMITY_REMOVED, 0, null, () -> {
                getLocationController().setProximityLocation(dialogId, 0, true);
                canUndo = false;
            }, () -> {
                proximityButton.setImageResource(R.drawable.msg_location_alert2);
                createCircle(info.proximityMeters);
                canUndo = false;
            });
            return;
        }
        openProximityAlert();
    });
    TLRPC.Chat chat = null;
    if (DialogObject.isChatDialog(dialogId)) {
        chat = getMessagesController().getChat(-dialogId);
    }
    if (messageObject == null || !messageObject.isLiveLocation() || messageObject.isExpiredLiveLocation(getConnectionsManager().getCurrentTime()) || ChatObject.isChannel(chat) && !chat.megagroup) {
        proximityButton.setVisibility(View.GONE);
        proximityButton.setImageResource(R.drawable.msg_location_alert);
    } else {
        LocationController.SharingLocationInfo myInfo = getLocationController().getSharingLocationInfo(dialogId);
        if (myInfo != null && myInfo.proximityMeters > 0) {
            proximityButton.setImageResource(R.drawable.msg_location_alert2);
        } else {
            if (DialogObject.isUserDialog(dialogId) && messageObject.getFromChatId() == getUserConfig().getClientUserId()) {
                proximityButton.setVisibility(View.INVISIBLE);
                proximityButton.setAlpha(0.0f);
                proximityButton.setScaleX(0.4f);
                proximityButton.setScaleY(0.4f);
            }
            proximityButton.setImageResource(R.drawable.msg_location_alert);
        }
    }
    hintView = new HintView(context, 6, true);
    hintView.setVisibility(View.INVISIBLE);
    hintView.setShowingDuration(4000);
    mapViewClip.addView(hintView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 10, 0, 10, 0));
    emptyView = new LinearLayout(context);
    emptyView.setOrientation(LinearLayout.VERTICAL);
    emptyView.setGravity(Gravity.CENTER_HORIZONTAL);
    emptyView.setPadding(0, AndroidUtilities.dp(60 + 100), 0, 0);
    emptyView.setVisibility(View.GONE);
    frameLayout.addView(emptyView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    emptyView.setOnTouchListener((v, event) -> true);
    emptyImageView = new ImageView(context);
    emptyImageView.setImageResource(R.drawable.location_empty);
    emptyImageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogEmptyImage), PorterDuff.Mode.MULTIPLY));
    emptyView.addView(emptyImageView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT));
    emptyTitleTextView = new TextView(context);
    emptyTitleTextView.setTextColor(Theme.getColor(Theme.key_dialogEmptyText));
    emptyTitleTextView.setGravity(Gravity.CENTER);
    emptyTitleTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    emptyTitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17);
    emptyTitleTextView.setText(LocaleController.getString("NoPlacesFound", R.string.NoPlacesFound));
    emptyView.addView(emptyTitleTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 11, 0, 0));
    emptySubtitleTextView = new TextView(context);
    emptySubtitleTextView.setTextColor(Theme.getColor(Theme.key_dialogEmptyText));
    emptySubtitleTextView.setGravity(Gravity.CENTER);
    emptySubtitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
    emptySubtitleTextView.setPadding(AndroidUtilities.dp(40), 0, AndroidUtilities.dp(40), 0);
    emptyView.addView(emptySubtitleTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 6, 0, 0));
    listView = new RecyclerListView(context);
    listView.setAdapter(adapter = new LocationActivityAdapter(context, locationType, dialogId, false, null) {

        @Override
        protected void onDirectionClick() {
            if (Build.VERSION.SDK_INT >= 23) {
                Activity activity = getParentActivity();
                if (activity != null) {
                    if (activity.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        showPermissionAlert(true);
                        return;
                    }
                }
            }
            if (myLocation != null) {
                try {
                    Intent intent;
                    if (messageObject != null) {
                        intent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format(Locale.US, "http://maps.google.com/maps?saddr=%f,%f&daddr=%f,%f", myLocation.getLatitude(), myLocation.getLongitude(), messageObject.messageOwner.media.geo.lat, messageObject.messageOwner.media.geo._long)));
                    } else {
                        intent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format(Locale.US, "http://maps.google.com/maps?saddr=%f,%f&daddr=%f,%f", myLocation.getLatitude(), myLocation.getLongitude(), chatLocation.geo_point.lat, chatLocation.geo_point._long)));
                    }
                    getParentActivity().startActivity(intent);
                } catch (Exception e) {
                    FileLog.e(e);
                }
            }
        }
    });
    adapter.setMyLocationDenied(locationDenied);
    adapter.setUpdateRunnable(() -> updateClipView(false));
    listView.setVerticalScrollBarEnabled(false);
    listView.setLayoutManager(layoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
    frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
    listView.setOnScrollListener(new RecyclerView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            scrolling = newState != RecyclerView.SCROLL_STATE_IDLE;
            if (!scrolling && forceUpdate != null) {
                forceUpdate = null;
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            updateClipView(false);
            if (forceUpdate != null) {
                yOffset += dy;
            }
        }
    });
    ((DefaultItemAnimator) listView.getItemAnimator()).setDelayAnimations(false);
    listView.setOnItemClickListener((view, position) -> {
        if (locationType == LOCATION_TYPE_GROUP) {
            if (position == 1) {
                TLRPC.TL_messageMediaVenue venue = (TLRPC.TL_messageMediaVenue) adapter.getItem(position);
                if (venue == null) {
                    return;
                }
                if (dialogId == 0) {
                    delegate.didSelectLocation(venue, LOCATION_TYPE_GROUP, true, 0);
                    finishFragment();
                } else {
                    final AlertDialog[] progressDialog = new AlertDialog[] { new AlertDialog(getParentActivity(), 3) };
                    TLRPC.TL_channels_editLocation req = new TLRPC.TL_channels_editLocation();
                    req.address = venue.address;
                    req.channel = getMessagesController().getInputChannel(-dialogId);
                    req.geo_point = new TLRPC.TL_inputGeoPoint();
                    req.geo_point.lat = venue.geo.lat;
                    req.geo_point._long = venue.geo._long;
                    int requestId = getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
                        try {
                            progressDialog[0].dismiss();
                        } catch (Throwable ignore) {
                        }
                        progressDialog[0] = null;
                        delegate.didSelectLocation(venue, LOCATION_TYPE_GROUP, true, 0);
                        finishFragment();
                    }));
                    progressDialog[0].setOnCancelListener(dialog -> getConnectionsManager().cancelRequest(requestId, true));
                    showDialog(progressDialog[0]);
                }
            }
        } else if (locationType == LOCATION_TYPE_GROUP_VIEW) {
            if (mapView != null) {
                final IMapController controller = mapView.getController();
                controller.animateTo(new GeoPoint(chatLocation.geo_point.lat, chatLocation.geo_point._long), mapView.getMaxZoomLevel() - 2, null);
            }
        } else if (position == 1 && messageObject != null && (!messageObject.isLiveLocation() || locationType == LOCATION_TYPE_LIVE_VIEW)) {
            if (mapView != null) {
                final IMapController controller = mapView.getController();
                controller.animateTo(new GeoPoint(messageObject.messageOwner.media.geo.lat, messageObject.messageOwner.media.geo._long), mapView.getMaxZoomLevel() - 2, null);
            }
        } else if (position == 1 && locationType != 2) {
            if (delegate != null && userLocation != null) {
                if (lastPressedMarkerView != null) {
                    lastPressedMarkerView.callOnClick();
                } else {
                    TLRPC.TL_messageMediaGeo location = new TLRPC.TL_messageMediaGeo();
                    location.geo = new TLRPC.TL_geoPoint();
                    location.geo.lat = AndroidUtilities.fixLocationCoord(userLocation.getLatitude());
                    location.geo._long = AndroidUtilities.fixLocationCoord(userLocation.getLongitude());
                    if (parentFragment != null && parentFragment.isInScheduleMode()) {
                        AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), parentFragment.getDialogId(), (notify, scheduleDate) -> {
                            delegate.didSelectLocation(location, locationType, notify, scheduleDate);
                            finishFragment();
                        });
                    } else {
                        delegate.didSelectLocation(location, locationType, true, 0);
                        finishFragment();
                    }
                }
            }
        } else if (position == 2 && locationType == 1 || position == 1 && locationType == 2 || position == 3 && locationType == 3) {
            if (getLocationController().isSharingLocation(dialogId)) {
                getLocationController().removeSharingLocation(dialogId);
                finishFragment();
            } else {
                openShareLiveLocation(0);
            }
        } else {
            Object object = adapter.getItem(position);
            if (object instanceof TLRPC.TL_messageMediaVenue) {
                if (parentFragment != null && parentFragment.isInScheduleMode()) {
                    AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), parentFragment.getDialogId(), (notify, scheduleDate) -> {
                        delegate.didSelectLocation((TLRPC.TL_messageMediaVenue) object, locationType, notify, scheduleDate);
                        finishFragment();
                    });
                } else {
                    delegate.didSelectLocation((TLRPC.TL_messageMediaVenue) object, locationType, true, 0);
                    finishFragment();
                }
            } else if (object instanceof LiveLocation) {
                LiveLocation liveLocation = (LiveLocation) object;
                final IMapController controller = mapView.getController();
                controller.animateTo(liveLocation.marker.getPosition(), mapView.getMaxZoomLevel() - 2, null);
            }
        }
    });
    adapter.setDelegate(dialogId, this::updatePlacesMarkers);
    adapter.setOverScrollHeight(overScrollHeight);
    frameLayout.addView(mapViewClip, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
    mapView = new MapView(context) {

        @Override
        public boolean dispatchTouchEvent(MotionEvent ev) {
            MotionEvent eventToRecycle = null;
            if (yOffset != 0) {
                ev = eventToRecycle = MotionEvent.obtain(ev);
                eventToRecycle.offsetLocation(0, -yOffset / 2);
            }
            boolean result = super.dispatchTouchEvent(ev);
            if (eventToRecycle != null) {
                eventToRecycle.recycle();
            }
            return result;
        }

        @Override
        public boolean onTouchEvent(MotionEvent ev) {
            if (messageObject == null && chatLocation == null) {
                if (ev.getAction() == MotionEvent.ACTION_DOWN) {
                    if (animatorSet != null) {
                        animatorSet.cancel();
                    }
                    animatorSet = new AnimatorSet();
                    animatorSet.setDuration(200);
                    animatorSet.playTogether(ObjectAnimator.ofFloat(markerImageView, View.TRANSLATION_Y, markerTop - AndroidUtilities.dp(10)));
                    animatorSet.start();
                } else if (ev.getAction() == MotionEvent.ACTION_UP) {
                    if (animatorSet != null) {
                        animatorSet.cancel();
                    }
                    yOffset = 0;
                    animatorSet = new AnimatorSet();
                    animatorSet.setDuration(200);
                    animatorSet.playTogether(ObjectAnimator.ofFloat(markerImageView, View.TRANSLATION_Y, markerTop));
                    animatorSet.start();
                    adapter.fetchLocationAddress();
                }
                if (ev.getAction() == MotionEvent.ACTION_MOVE) {
                    if (!userLocationMoved) {
                        locationButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_location_actionIcon), PorterDuff.Mode.MULTIPLY));
                        locationButton.setTag(Theme.key_location_actionIcon);
                        userLocationMoved = true;
                    }
                    if (mapView != null) {
                        if (userLocation != null) {
                            userLocation.setLatitude(mapView.getMapCenter().getLatitude());
                            userLocation.setLongitude(mapView.getMapCenter().getLongitude());
                        }
                    }
                    adapter.setCustomLocation(userLocation);
                }
            }
            return super.onTouchEvent(ev);
        }

        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            super.onLayout(changed, left, top, right, bottom);
            AndroidUtilities.runOnUIThread(() -> {
                if (moveToBounds != null) {
                    mapView.zoomToBoundingBox(moveToBounds, false, AndroidUtilities.dp(80 + 33));
                    moveToBounds = null;
                }
            });
        }
    };
    AndroidUtilities.runOnUIThread(() -> {
        if (mapView != null && getParentActivity() != null) {
            mapView.setPadding(AndroidUtilities.dp(70), 0, AndroidUtilities.dp(70), AndroidUtilities.dp(10));
            onMapInit();
            mapsInitialized = true;
            if (isActiveThemeDark()) {
            /*currentMapStyleDark = true;
                    MapStyleOptions style = MapStyleOptions.loadRawResourceStyle(ApplicationLoader.applicationContext, R.raw.mapstyle_night);
                    googleMap.setMapStyle(style);
                    */
            // TODO Dark?
            }
            if (onResumeCalled) {
                mapView.onResume();
            }
        }
    });
    if (messageObject == null && chatLocation == null) {
        if (chat != null && locationType == LOCATION_TYPE_GROUP && dialogId != 0) {
            FrameLayout frameLayout1 = new FrameLayout(context);
            frameLayout1.setBackgroundResource(R.drawable.livepin);
            mapViewClip.addView(frameLayout1, LayoutHelper.createFrame(62, 76, Gravity.TOP | Gravity.CENTER_HORIZONTAL));
            BackupImageView backupImageView = new BackupImageView(context);
            backupImageView.setRoundRadius(AndroidUtilities.dp(26));
            backupImageView.setForUserOrChat(chat, new AvatarDrawable(chat));
            frameLayout1.addView(backupImageView, LayoutHelper.createFrame(52, 52, Gravity.LEFT | Gravity.TOP, 5, 5, 0, 0));
            markerImageView = frameLayout1;
            markerImageView.setTag(1);
        }
        if (markerImageView == null) {
            ImageView imageView = new ImageView(context);
            imageView.setImageResource(R.drawable.map_pin2);
            mapViewClip.addView(imageView, LayoutHelper.createFrame(28, 48, Gravity.TOP | Gravity.CENTER_HORIZONTAL));
            markerImageView = imageView;
        }
        searchListView = new RecyclerListView(context);
        searchListView.setVisibility(View.GONE);
        searchListView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
        searchAdapter = new LocationActivitySearchAdapter(context) {

            @Override
            public void notifyDataSetChanged() {
                if (searchItem != null) {
                    searchItem.setShowSearchProgress(searchAdapter.isSearching());
                }
                if (emptySubtitleTextView != null) {
                    emptySubtitleTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("NoPlacesFoundInfo", R.string.NoPlacesFoundInfo, searchAdapter.getLastSearchString())));
                }
                super.notifyDataSetChanged();
            }
        };
        searchAdapter.setDelegate(0, places -> {
            searchInProgress = false;
            updateEmptyView();
        });
        frameLayout.addView(searchListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
        searchListView.setOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_DRAGGING && searching && searchWas) {
                    AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus());
                }
            }
        });
        searchListView.setOnItemClickListener((view, position) -> {
            TLRPC.TL_messageMediaVenue object = searchAdapter.getItem(position);
            if (object != null && delegate != null) {
                if (parentFragment != null && parentFragment.isInScheduleMode()) {
                    AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), parentFragment.getDialogId(), (notify, scheduleDate) -> {
                        delegate.didSelectLocation(object, locationType, notify, scheduleDate);
                        finishFragment();
                    });
                } else {
                    delegate.didSelectLocation(object, locationType, true, 0);
                    finishFragment();
                }
            }
        });
    } else if (messageObject != null && !messageObject.isLiveLocation() || chatLocation != null) {
        if (chatLocation != null) {
            adapter.setChatLocation(chatLocation);
        } else if (messageObject != null) {
            adapter.setMessageObject(messageObject);
        }
    }
    if (messageObject != null && locationType == LOCATION_TYPE_LIVE_VIEW) {
        adapter.setMessageObject(messageObject);
    }
    for (int a = 0; a < 2; a++) {
        undoView[a] = new UndoView(context);
        undoView[a].setAdditionalTranslationY(AndroidUtilities.dp(10));
        if (Build.VERSION.SDK_INT >= 21) {
            undoView[a].setTranslationZ(AndroidUtilities.dp(5));
        }
        mapViewClip.addView(undoView[a], LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 8, 0, 8, 8));
    }
    shadow = new View(context) {

        private RectF rect = new RectF();

        @Override
        protected void onDraw(Canvas canvas) {
            shadowDrawable.setBounds(-padding.left, 0, getMeasuredWidth() + padding.right, getMeasuredHeight());
            shadowDrawable.draw(canvas);
            if (locationType == LOCATION_TYPE_SEND || locationType == LOCATION_TYPE_SEND_WITH_LIVE) {
                int w = AndroidUtilities.dp(36);
                int y = padding.top + AndroidUtilities.dp(10);
                rect.set((getMeasuredWidth() - w) / 2, y, (getMeasuredWidth() + w) / 2, y + AndroidUtilities.dp(4));
                int color = Theme.getColor(Theme.key_sheet_scrollUp);
                int alpha = Color.alpha(color);
                Theme.dialogs_onlineCirclePaint.setColor(color);
                canvas.drawRoundRect(rect, AndroidUtilities.dp(2), AndroidUtilities.dp(2), Theme.dialogs_onlineCirclePaint);
            }
        }
    };
    if (Build.VERSION.SDK_INT >= 21) {
        shadow.setTranslationZ(AndroidUtilities.dp(6));
    }
    mapViewClip.addView(shadow, layoutParams);
    if (messageObject == null && chatLocation == null && initialLocation != null) {
        userLocationMoved = true;
        locationButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_location_actionIcon), PorterDuff.Mode.MULTIPLY));
        locationButton.setTag(Theme.key_location_actionIcon);
    }
    frameLayout.addView(actionBar);
    updateEmptyView();
    return fragmentView;
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) Arrays(java.util.Arrays) Uri(android.net.Uri) FrameLayout(android.widget.FrameLayout) ImageView(android.widget.ImageView) LocationController(org.telegram.messenger.LocationController) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) Drawable(android.graphics.drawable.Drawable) AvatarDrawable(org.telegram.ui.Components.AvatarDrawable) Manifest(android.Manifest) StateListAnimator(android.animation.StateListAnimator) ITileSource(org.osmdroid.tileprovider.tilesource.ITileSource) Shader(android.graphics.Shader) Canvas(android.graphics.Canvas) XYTileSource(org.osmdroid.tileprovider.tilesource.XYTileSource) Configuration(org.osmdroid.config.Configuration) LocationActivitySearchAdapter(org.telegram.ui.Adapters.LocationActivitySearchAdapter) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) ScrollEvent(org.osmdroid.events.ScrollEvent) UndoView(org.telegram.ui.Components.UndoView) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) Polygon(org.osmdroid.views.overlay.Polygon) NotificationCenter(org.telegram.messenger.NotificationCenter) Outline(android.graphics.Outline) LocationActivityAdapter(org.telegram.ui.Adapters.LocationActivityAdapter) Html(android.text.Html) HintView(org.telegram.ui.Components.HintView) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) Paint(android.graphics.Paint) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) FileLoader(org.telegram.messenger.FileLoader) ZoomEvent(org.osmdroid.events.ZoomEvent) BitmapFactory(android.graphics.BitmapFactory) AlertsCreator(org.telegram.ui.Components.AlertsCreator) ArrayList(java.util.ArrayList) TileSourceFactory(org.osmdroid.tileprovider.tilesource.TileSourceFactory) TLRPC(org.telegram.tgnet.TLRPC) Toast(android.widget.Toast) BuildConfig(org.telegram.messenger.BuildConfig) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) R(org.telegram.messenger.R) TextUtils(android.text.TextUtils) SharingLiveLocationCell(org.telegram.ui.Cells.SharingLiveLocationCell) MapView(org.osmdroid.views.MapView) File(java.io.File) Gravity(android.view.Gravity) UserObject(org.telegram.messenger.UserObject) SharedPreferences(android.content.SharedPreferences) TypedValue(android.util.TypedValue) LocationCell(org.telegram.ui.Cells.LocationCell) ChatObject(org.telegram.messenger.ChatObject) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) EditText(android.widget.EditText) ValueAnimator(android.animation.ValueAnimator) IMyLocationProvider(org.osmdroid.views.overlay.mylocation.IMyLocationProvider) ThemeDescription(org.telegram.ui.ActionBar.ThemeDescription) Rect(android.graphics.Rect) MyLocationNewOverlay(org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay) LinearLayout(android.widget.LinearLayout) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) PackageManager(android.content.pm.PackageManager) AndroidUtilities(org.telegram.messenger.AndroidUtilities) CubicBezierInterpolator(org.telegram.ui.Components.CubicBezierInterpolator) Animator(android.animation.Animator) LinkMovementMethod(android.text.method.LinkMovementMethod) ShadowSectionCell(org.telegram.ui.Cells.ShadowSectionCell) ApplicationLoader(org.telegram.messenger.ApplicationLoader) SendLocationCell(org.telegram.ui.Cells.SendLocationCell) Locale(java.util.Locale) View(android.view.View) IMapController(org.osmdroid.api.IMapController) RecyclerView(androidx.recyclerview.widget.RecyclerView) Matrix(android.graphics.Matrix) RectF(android.graphics.RectF) BitmapShader(android.graphics.BitmapShader) LocationLoadingCell(org.telegram.ui.Cells.LocationLoadingCell) IGeoPoint(org.osmdroid.api.IGeoPoint) GpsMyLocationProvider(org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider) LocationPoweredCell(org.telegram.ui.Cells.LocationPoweredCell) ObjectAnimator(android.animation.ObjectAnimator) ImageLocation(org.telegram.messenger.ImageLocation) Marker(org.osmdroid.views.overlay.Marker) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) BitmapDrawable(android.graphics.drawable.BitmapDrawable) PorterDuff(android.graphics.PorterDuff) MapPlaceholderDrawable(org.telegram.ui.Components.MapPlaceholderDrawable) ViewGroup(android.view.ViewGroup) DefaultItemAnimator(androidx.recyclerview.widget.DefaultItemAnimator) List(java.util.List) TextView(android.widget.TextView) Location(android.location.Location) ProximitySheet(org.telegram.ui.Components.ProximitySheet) LocationManager(android.location.LocationManager) Context(android.content.Context) Theme(org.telegram.ui.ActionBar.Theme) ViewOutlineProvider(android.view.ViewOutlineProvider) Intent(android.content.Intent) LocaleController(org.telegram.messenger.LocaleController) HashMap(java.util.HashMap) HeaderCell(org.telegram.ui.Cells.HeaderCell) GeoPoint(org.osmdroid.util.GeoPoint) SuppressLint(android.annotation.SuppressLint) LocationDirectionCell(org.telegram.ui.Cells.LocationDirectionCell) MapListener(org.osmdroid.events.MapListener) MotionEvent(android.view.MotionEvent) ActionBar(org.telegram.ui.ActionBar.ActionBar) AnimatorSet(android.animation.AnimatorSet) MessageObject(org.telegram.messenger.MessageObject) Build(android.os.Build) Projection(org.osmdroid.views.Projection) LongSparseArray(androidx.collection.LongSparseArray) DialogObject(org.telegram.messenger.DialogObject) BackupImageView(org.telegram.ui.Components.BackupImageView) Point(android.graphics.Point) LayoutHelper(org.telegram.ui.Components.LayoutHelper) FileLog(org.telegram.messenger.FileLog) BoundingBox(org.osmdroid.util.BoundingBox) MessagesController(org.telegram.messenger.MessagesController) Color(android.graphics.Color) Bitmap(android.graphics.Bitmap) OvershootInterpolator(android.view.animation.OvershootInterpolator) Activity(android.app.Activity) RecyclerListView(org.telegram.ui.Components.RecyclerListView) LocationActivitySearchAdapter(org.telegram.ui.Adapters.LocationActivitySearchAdapter) Activity(android.app.Activity) LocationController(org.telegram.messenger.LocationController) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) MapPlaceholderDrawable(org.telegram.ui.Components.MapPlaceholderDrawable) TLRPC(org.telegram.tgnet.TLRPC) DefaultItemAnimator(androidx.recyclerview.widget.DefaultItemAnimator) IGeoPoint(org.osmdroid.api.IGeoPoint) GeoPoint(org.osmdroid.util.GeoPoint) BackupImageView(org.telegram.ui.Components.BackupImageView) MapView(org.osmdroid.views.MapView) IMapController(org.osmdroid.api.IMapController) TextView(android.widget.TextView) ImageView(android.widget.ImageView) BackupImageView(org.telegram.ui.Components.BackupImageView) ActionBar(org.telegram.ui.ActionBar.ActionBar) EditText(android.widget.EditText) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) Rect(android.graphics.Rect) Canvas(android.graphics.Canvas) Drawable(android.graphics.drawable.Drawable) AvatarDrawable(org.telegram.ui.Components.AvatarDrawable) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) BitmapDrawable(android.graphics.drawable.BitmapDrawable) MapPlaceholderDrawable(org.telegram.ui.Components.MapPlaceholderDrawable) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) ITileSource(org.osmdroid.tileprovider.tilesource.ITileSource) UserObject(org.telegram.messenger.UserObject) ChatObject(org.telegram.messenger.ChatObject) MessageObject(org.telegram.messenger.MessageObject) DialogObject(org.telegram.messenger.DialogObject) AvatarDrawable(org.telegram.ui.Components.AvatarDrawable) StateListAnimator(android.animation.StateListAnimator) LocationActivityAdapter(org.telegram.ui.Adapters.LocationActivityAdapter) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) AnimatorSet(android.animation.AnimatorSet) RecyclerListView(org.telegram.ui.Components.RecyclerListView) XYTileSource(org.osmdroid.tileprovider.tilesource.XYTileSource) UndoView(org.telegram.ui.Components.UndoView) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) SharedPreferences(android.content.SharedPreferences) Intent(android.content.Intent) Outline(android.graphics.Outline) ImageView(android.widget.ImageView) UndoView(org.telegram.ui.Components.UndoView) HintView(org.telegram.ui.Components.HintView) MapView(org.osmdroid.views.MapView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) TextView(android.widget.TextView) BackupImageView(org.telegram.ui.Components.BackupImageView) RecyclerListView(org.telegram.ui.Components.RecyclerListView) ViewOutlineProvider(android.view.ViewOutlineProvider) Paint(android.graphics.Paint) IGeoPoint(org.osmdroid.api.IGeoPoint) GeoPoint(org.osmdroid.util.GeoPoint) SuppressLint(android.annotation.SuppressLint) Point(android.graphics.Point) HintView(org.telegram.ui.Components.HintView) MotionEvent(android.view.MotionEvent) RectF(android.graphics.RectF) FrameLayout(android.widget.FrameLayout) SuppressLint(android.annotation.SuppressLint) RecyclerView(androidx.recyclerview.widget.RecyclerView) LinearLayout(android.widget.LinearLayout) ImageLocation(org.telegram.messenger.ImageLocation) Location(android.location.Location)

Example 28 with AlertDialog

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

the class LaunchActivity method handleIntent.

private boolean handleIntent(Intent intent, boolean isNew, boolean restore, boolean fromPassword) {
    if (AndroidUtilities.handleProxyIntent(this, intent)) {
        actionBarLayout.showLastFragment();
        if (AndroidUtilities.isTablet()) {
            layersActionBarLayout.showLastFragment();
            rightActionBarLayout.showLastFragment();
        }
        return true;
    }
    if (PhotoViewer.hasInstance() && PhotoViewer.getInstance().isVisible()) {
        if (intent == null || !Intent.ACTION_MAIN.equals(intent.getAction())) {
            PhotoViewer.getInstance().closePhoto(false, true);
        }
    }
    int flags = intent.getFlags();
    String action = intent.getAction();
    final int[] intentAccount = new int[] { intent.getIntExtra("currentAccount", UserConfig.selectedAccount) };
    switchToAccount(intentAccount[0], true);
    boolean isVoipIntent = action != null && action.equals("voip");
    if (!fromPassword && (AndroidUtilities.needShowPasscode(true) || SharedConfig.isWaitingForPasscodeEnter)) {
        showPasscodeActivity(true, false, -1, -1, null, null);
        UserConfig.getInstance(currentAccount).saveConfig(false);
        if (!isVoipIntent) {
            passcodeSaveIntent = intent;
            passcodeSaveIntentIsNew = isNew;
            passcodeSaveIntentIsRestore = restore;
            return false;
        }
    }
    boolean pushOpened = false;
    long push_user_id = 0;
    long push_chat_id = 0;
    int push_enc_id = 0;
    int push_msg_id = 0;
    int open_settings = 0;
    int open_widget_edit = -1;
    int open_widget_edit_type = -1;
    int open_new_dialog = 0;
    long dialogId = 0;
    boolean showDialogsList = false;
    boolean showPlayer = false;
    boolean showLocations = false;
    boolean showGroupVoip = false;
    boolean showCallLog = false;
    boolean audioCallUser = false;
    boolean videoCallUser = false;
    boolean needCallAlert = false;
    boolean newContact = false;
    boolean newContactAlert = false;
    boolean scanQr = false;
    String searchQuery = null;
    String callSearchQuery = null;
    String newContactName = null;
    String newContactPhone = null;
    photoPathsArray = null;
    videoPath = null;
    sendingText = null;
    sendingLocation = null;
    documentsPathsArray = null;
    documentsOriginalPathsArray = null;
    documentsMimeType = null;
    documentsUrisArray = null;
    exportingChatUri = null;
    contactsToSend = null;
    contactsToSendUri = null;
    importingStickers = null;
    importingStickersEmoji = null;
    importingStickersSoftware = null;
    if ((flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0) {
        if (intent != null && intent.getAction() != null && !restore) {
            if (Intent.ACTION_SEND.equals(intent.getAction())) {
                if (SharedConfig.directShare && intent != null && intent.getExtras() != null) {
                    dialogId = intent.getExtras().getLong("dialogId", 0);
                    String hash = null;
                    if (dialogId == 0) {
                        try {
                            String id = intent.getExtras().getString(ShortcutManagerCompat.EXTRA_SHORTCUT_ID);
                            if (id != null) {
                                List<ShortcutInfoCompat> list = ShortcutManagerCompat.getDynamicShortcuts(ApplicationLoader.applicationContext);
                                for (int a = 0, N = list.size(); a < N; a++) {
                                    ShortcutInfoCompat info = list.get(a);
                                    if (id.equals(info.getId())) {
                                        Bundle extras = info.getIntent().getExtras();
                                        dialogId = extras.getLong("dialogId", 0);
                                        hash = extras.getString("hash", null);
                                        break;
                                    }
                                }
                            }
                        } catch (Throwable e) {
                            FileLog.e(e);
                        }
                    } else {
                        hash = intent.getExtras().getString("hash", null);
                    }
                    if (SharedConfig.directShareHash == null || !SharedConfig.directShareHash.equals(hash)) {
                        dialogId = 0;
                    }
                }
                boolean error = false;
                String type = intent.getType();
                if (type != null && type.equals(ContactsContract.Contacts.CONTENT_VCARD_TYPE)) {
                    try {
                        Uri uri = (Uri) intent.getExtras().get(Intent.EXTRA_STREAM);
                        if (uri != null) {
                            contactsToSend = AndroidUtilities.loadVCardFromStream(uri, currentAccount, false, null, null);
                            if (contactsToSend.size() > 5) {
                                contactsToSend = null;
                                documentsUrisArray = new ArrayList<>();
                                documentsUrisArray.add(uri);
                                documentsMimeType = type;
                            } else {
                                contactsToSendUri = uri;
                            }
                        } else {
                            error = true;
                        }
                    } catch (Exception e) {
                        FileLog.e(e);
                        error = true;
                    }
                } else {
                    String text = intent.getStringExtra(Intent.EXTRA_TEXT);
                    if (text == null) {
                        CharSequence textSequence = intent.getCharSequenceExtra(Intent.EXTRA_TEXT);
                        if (textSequence != null) {
                            text = textSequence.toString();
                        }
                    }
                    String subject = intent.getStringExtra(Intent.EXTRA_SUBJECT);
                    if (!TextUtils.isEmpty(text)) {
                        Matcher m = locationRegex.matcher(text);
                        if (m.find()) {
                            String[] lines = text.split("\\n");
                            String venueTitle = null;
                            String venueAddress = null;
                            if (lines[0].equals("My Position")) {
                            // Use normal GeoPoint message (user position)
                            } else if (!lines[0].contains("geo:")) {
                                venueTitle = lines[0];
                                if (!lines[1].contains("geo:")) {
                                    venueAddress = lines[1];
                                }
                            }
                            sendingLocation = new Location("");
                            sendingLocation.setLatitude(Double.parseDouble(m.group(1)));
                            sendingLocation.setLongitude(Double.parseDouble(m.group(2)));
                            Bundle bundle = new Bundle();
                            bundle.putCharSequence("venueTitle", venueTitle);
                            bundle.putCharSequence("venueAddress", venueAddress);
                            sendingLocation.setExtras(bundle);
                        } else if ((text.startsWith("http://") || text.startsWith("https://")) && !TextUtils.isEmpty(subject)) {
                            text = subject + "\n" + text;
                        }
                        sendingText = text;
                    } else if (!TextUtils.isEmpty(subject)) {
                        sendingText = subject;
                    }
                    Parcelable parcelable = intent.getParcelableExtra(Intent.EXTRA_STREAM);
                    if (parcelable != null) {
                        String path;
                        if (!(parcelable instanceof Uri)) {
                            parcelable = Uri.parse(parcelable.toString());
                        }
                        Uri uri = (Uri) parcelable;
                        if (uri != null) {
                            if (AndroidUtilities.isInternalUri(uri)) {
                                error = true;
                            }
                        }
                        if (!error && uri != null) {
                            if (type != null && type.startsWith("image/") || uri.toString().toLowerCase().endsWith(".jpg")) {
                                if (photoPathsArray == null) {
                                    photoPathsArray = new ArrayList<>();
                                }
                                SendMessagesHelper.SendingMediaInfo info = new SendMessagesHelper.SendingMediaInfo();
                                info.uri = uri;
                                photoPathsArray.add(info);
                            } else {
                                String originalPath = uri.toString();
                                if (dialogId == 0 && originalPath != null) {
                                    if (BuildVars.LOGS_ENABLED) {
                                        FileLog.d("export path = " + originalPath);
                                    }
                                    Set<String> exportUris = MessagesController.getInstance(intentAccount[0]).exportUri;
                                    String fileName = FileLoader.fixFileName(MediaController.getFileName(uri));
                                    for (String u : exportUris) {
                                        try {
                                            Pattern pattern = Pattern.compile(u);
                                            if (pattern.matcher(originalPath).find() || pattern.matcher(fileName).find()) {
                                                exportingChatUri = uri;
                                                break;
                                            }
                                        } catch (Exception e) {
                                            FileLog.e(e);
                                        }
                                    }
                                    if (exportingChatUri == null) {
                                        if (originalPath.startsWith("content://com.kakao.talk") && originalPath.endsWith("KakaoTalkChats.txt")) {
                                            exportingChatUri = uri;
                                        }
                                    }
                                }
                                if (exportingChatUri == null) {
                                    path = AndroidUtilities.getPath(uri);
                                    if (!BuildVars.NO_SCOPED_STORAGE) {
                                        path = MediaController.copyFileToCache(uri, "file");
                                    }
                                    if (path != null) {
                                        if (path.startsWith("file:")) {
                                            path = path.replace("file://", "");
                                        }
                                        if (type != null && type.startsWith("video/")) {
                                            videoPath = path;
                                        } else {
                                            if (documentsPathsArray == null) {
                                                documentsPathsArray = new ArrayList<>();
                                                documentsOriginalPathsArray = new ArrayList<>();
                                            }
                                            documentsPathsArray.add(path);
                                            documentsOriginalPathsArray.add(uri.toString());
                                        }
                                    } else {
                                        if (documentsUrisArray == null) {
                                            documentsUrisArray = new ArrayList<>();
                                        }
                                        documentsUrisArray.add(uri);
                                        documentsMimeType = type;
                                    }
                                }
                            }
                        }
                    } else if (sendingText == null && sendingLocation == null) {
                        error = true;
                    }
                }
                if (error) {
                    Toast.makeText(this, "Unsupported content", Toast.LENGTH_SHORT).show();
                }
            } else if ("org.telegram.messenger.CREATE_STICKER_PACK".equals(intent.getAction())) {
                try {
                    importingStickers = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
                    importingStickersEmoji = intent.getStringArrayListExtra("STICKER_EMOJIS");
                    importingStickersSoftware = intent.getStringExtra("IMPORTER");
                } catch (Throwable e) {
                    FileLog.e(e);
                    importingStickers = null;
                    importingStickersEmoji = null;
                    importingStickersSoftware = null;
                }
            } else if (Intent.ACTION_SEND_MULTIPLE.equals(intent.getAction())) {
                boolean error = false;
                try {
                    ArrayList<Parcelable> uris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
                    String type = intent.getType();
                    if (uris != null) {
                        for (int a = 0; a < uris.size(); a++) {
                            Parcelable parcelable = uris.get(a);
                            if (!(parcelable instanceof Uri)) {
                                parcelable = Uri.parse(parcelable.toString());
                            }
                            Uri uri = (Uri) parcelable;
                            if (uri != null) {
                                if (AndroidUtilities.isInternalUri(uri)) {
                                    uris.remove(a);
                                    a--;
                                }
                            }
                        }
                        if (uris.isEmpty()) {
                            uris = null;
                        }
                    }
                    if (uris != null) {
                        if (type != null && type.startsWith("image/")) {
                            for (int a = 0; a < uris.size(); a++) {
                                Parcelable parcelable = uris.get(a);
                                if (!(parcelable instanceof Uri)) {
                                    parcelable = Uri.parse(parcelable.toString());
                                }
                                Uri uri = (Uri) parcelable;
                                if (photoPathsArray == null) {
                                    photoPathsArray = new ArrayList<>();
                                }
                                SendMessagesHelper.SendingMediaInfo info = new SendMessagesHelper.SendingMediaInfo();
                                info.uri = uri;
                                photoPathsArray.add(info);
                            }
                        } else {
                            Set<String> exportUris = MessagesController.getInstance(intentAccount[0]).exportUri;
                            for (int a = 0; a < uris.size(); a++) {
                                Parcelable parcelable = uris.get(a);
                                if (!(parcelable instanceof Uri)) {
                                    parcelable = Uri.parse(parcelable.toString());
                                }
                                Uri uri = (Uri) parcelable;
                                String path = AndroidUtilities.getPath(uri);
                                String originalPath = parcelable.toString();
                                if (originalPath == null) {
                                    originalPath = path;
                                }
                                if (BuildVars.LOGS_ENABLED) {
                                    FileLog.d("export path = " + originalPath);
                                }
                                if (dialogId == 0 && originalPath != null && exportingChatUri == null) {
                                    boolean ok = false;
                                    String fileName = FileLoader.fixFileName(MediaController.getFileName(uri));
                                    for (String u : exportUris) {
                                        try {
                                            Pattern pattern = Pattern.compile(u);
                                            if (pattern.matcher(originalPath).find() || pattern.matcher(fileName).find()) {
                                                exportingChatUri = uri;
                                                ok = true;
                                                break;
                                            }
                                        } catch (Exception e) {
                                            FileLog.e(e);
                                        }
                                    }
                                    if (ok) {
                                        continue;
                                    } else if (originalPath.startsWith("content://com.kakao.talk") && originalPath.endsWith("KakaoTalkChats.txt")) {
                                        exportingChatUri = uri;
                                        continue;
                                    }
                                }
                                if (path != null) {
                                    if (path.startsWith("file:")) {
                                        path = path.replace("file://", "");
                                    }
                                    if (documentsPathsArray == null) {
                                        documentsPathsArray = new ArrayList<>();
                                        documentsOriginalPathsArray = new ArrayList<>();
                                    }
                                    documentsPathsArray.add(path);
                                    documentsOriginalPathsArray.add(originalPath);
                                } else {
                                    if (documentsUrisArray == null) {
                                        documentsUrisArray = new ArrayList<>();
                                    }
                                    documentsUrisArray.add(uri);
                                    documentsMimeType = type;
                                }
                            }
                        }
                    } else {
                        error = true;
                    }
                } catch (Exception e) {
                    FileLog.e(e);
                    error = true;
                }
                if (error) {
                    Toast.makeText(this, "Unsupported content", Toast.LENGTH_SHORT).show();
                }
            } else if (Intent.ACTION_VIEW.equals(intent.getAction())) {
                Uri data = intent.getData();
                if (data != null) {
                    String username = null;
                    String login = null;
                    String group = null;
                    String sticker = null;
                    HashMap<String, String> auth = null;
                    String unsupportedUrl = null;
                    String botUser = null;
                    String botChat = null;
                    String message = null;
                    String phone = null;
                    String game = null;
                    String voicechat = null;
                    String livestream = null;
                    String phoneHash = null;
                    String lang = null;
                    String theme = null;
                    String code = null;
                    TLRPC.TL_wallPaper wallPaper = null;
                    Integer messageId = null;
                    Long channelId = null;
                    Integer threadId = null;
                    Integer commentId = null;
                    int videoTimestamp = -1;
                    boolean hasUrl = false;
                    final String scheme = data.getScheme();
                    if (scheme != null) {
                        switch(scheme) {
                            case "http":
                            case "https":
                                {
                                    String host = data.getHost().toLowerCase();
                                    if (host.equals("telegram.me") || host.equals("t.me") || host.equals("telegram.dog")) {
                                        String path = data.getPath();
                                        if (path != null && path.length() > 1) {
                                            path = path.substring(1);
                                            if (path.startsWith("bg/")) {
                                                wallPaper = new TLRPC.TL_wallPaper();
                                                wallPaper.settings = new TLRPC.TL_wallPaperSettings();
                                                wallPaper.slug = path.replace("bg/", "");
                                                boolean ok = false;
                                                if (wallPaper.slug != null && wallPaper.slug.length() == 6) {
                                                    try {
                                                        wallPaper.settings.background_color = Integer.parseInt(wallPaper.slug, 16) | 0xff000000;
                                                        wallPaper.slug = null;
                                                        ok = true;
                                                    } catch (Exception ignore) {
                                                    }
                                                } else if (wallPaper.slug != null && wallPaper.slug.length() >= 13 && AndroidUtilities.isValidWallChar(wallPaper.slug.charAt(6))) {
                                                    try {
                                                        wallPaper.settings.background_color = Integer.parseInt(wallPaper.slug.substring(0, 6), 16) | 0xff000000;
                                                        wallPaper.settings.second_background_color = Integer.parseInt(wallPaper.slug.substring(7, 13), 16) | 0xff000000;
                                                        if (wallPaper.slug.length() >= 20 && AndroidUtilities.isValidWallChar(wallPaper.slug.charAt(13))) {
                                                            wallPaper.settings.third_background_color = Integer.parseInt(wallPaper.slug.substring(14, 20), 16) | 0xff000000;
                                                        }
                                                        if (wallPaper.slug.length() == 27 && AndroidUtilities.isValidWallChar(wallPaper.slug.charAt(20))) {
                                                            wallPaper.settings.fourth_background_color = Integer.parseInt(wallPaper.slug.substring(21), 16) | 0xff000000;
                                                        }
                                                        try {
                                                            String rotation = data.getQueryParameter("rotation");
                                                            if (!TextUtils.isEmpty(rotation)) {
                                                                wallPaper.settings.rotation = Utilities.parseInt(rotation);
                                                            }
                                                        } catch (Exception ignore) {
                                                        }
                                                        wallPaper.slug = null;
                                                        ok = true;
                                                    } catch (Exception ignore) {
                                                    }
                                                }
                                                if (!ok) {
                                                    String mode = data.getQueryParameter("mode");
                                                    if (mode != null) {
                                                        mode = mode.toLowerCase();
                                                        String[] modes = mode.split(" ");
                                                        if (modes != null && modes.length > 0) {
                                                            for (int a = 0; a < modes.length; a++) {
                                                                if ("blur".equals(modes[a])) {
                                                                    wallPaper.settings.blur = true;
                                                                } else if ("motion".equals(modes[a])) {
                                                                    wallPaper.settings.motion = true;
                                                                }
                                                            }
                                                        }
                                                    }
                                                    String intensity = data.getQueryParameter("intensity");
                                                    if (!TextUtils.isEmpty(intensity)) {
                                                        wallPaper.settings.intensity = Utilities.parseInt(intensity);
                                                    } else {
                                                        wallPaper.settings.intensity = 50;
                                                    }
                                                    try {
                                                        String bgColor = data.getQueryParameter("bg_color");
                                                        if (!TextUtils.isEmpty(bgColor)) {
                                                            wallPaper.settings.background_color = Integer.parseInt(bgColor.substring(0, 6), 16) | 0xff000000;
                                                            if (bgColor.length() >= 13) {
                                                                wallPaper.settings.second_background_color = Integer.parseInt(bgColor.substring(7, 13), 16) | 0xff000000;
                                                                if (bgColor.length() >= 20 && AndroidUtilities.isValidWallChar(bgColor.charAt(13))) {
                                                                    wallPaper.settings.third_background_color = Integer.parseInt(bgColor.substring(14, 20), 16) | 0xff000000;
                                                                }
                                                                if (bgColor.length() == 27 && AndroidUtilities.isValidWallChar(bgColor.charAt(20))) {
                                                                    wallPaper.settings.fourth_background_color = Integer.parseInt(bgColor.substring(21), 16) | 0xff000000;
                                                                }
                                                            }
                                                        } else {
                                                            wallPaper.settings.background_color = 0xffffffff;
                                                        }
                                                    } catch (Exception ignore) {
                                                    }
                                                    try {
                                                        String rotation = data.getQueryParameter("rotation");
                                                        if (!TextUtils.isEmpty(rotation)) {
                                                            wallPaper.settings.rotation = Utilities.parseInt(rotation);
                                                        }
                                                    } catch (Exception ignore) {
                                                    }
                                                }
                                            } else if (path.startsWith("login/")) {
                                                int intCode = Utilities.parseInt(path.replace("login/", ""));
                                                if (intCode != 0) {
                                                    code = "" + intCode;
                                                }
                                            } else if (path.startsWith("joinchat/")) {
                                                group = path.replace("joinchat/", "");
                                            } else if (path.startsWith("+")) {
                                                group = path.replace("+", "");
                                            } else if (path.startsWith("addstickers/")) {
                                                sticker = path.replace("addstickers/", "");
                                            } else if (path.startsWith("msg/") || path.startsWith("share/")) {
                                                message = data.getQueryParameter("url");
                                                if (message == null) {
                                                    message = "";
                                                }
                                                if (data.getQueryParameter("text") != null) {
                                                    if (message.length() > 0) {
                                                        hasUrl = true;
                                                        message += "\n";
                                                    }
                                                    message += data.getQueryParameter("text");
                                                }
                                                if (message.length() > 4096 * 4) {
                                                    message = message.substring(0, 4096 * 4);
                                                }
                                                while (message.endsWith("\n")) {
                                                    message = message.substring(0, message.length() - 1);
                                                }
                                            } else if (path.startsWith("confirmphone")) {
                                                phone = data.getQueryParameter("phone");
                                                phoneHash = data.getQueryParameter("hash");
                                            } else if (path.startsWith("setlanguage/")) {
                                                lang = path.substring(12);
                                            } else if (path.startsWith("addtheme/")) {
                                                theme = path.substring(9);
                                            } else if (path.startsWith("c/")) {
                                                List<String> segments = data.getPathSegments();
                                                if (segments.size() == 3) {
                                                    channelId = Utilities.parseLong(segments.get(1));
                                                    messageId = Utilities.parseInt(segments.get(2));
                                                    if (messageId == 0 || channelId == 0) {
                                                        messageId = null;
                                                        channelId = null;
                                                    }
                                                    threadId = Utilities.parseInt(data.getQueryParameter("thread"));
                                                    if (threadId == 0) {
                                                        threadId = null;
                                                    }
                                                }
                                            } else if (path.length() >= 1) {
                                                ArrayList<String> segments = new ArrayList<>(data.getPathSegments());
                                                if (segments.size() > 0 && segments.get(0).equals("s")) {
                                                    segments.remove(0);
                                                }
                                                if (segments.size() > 0) {
                                                    username = segments.get(0);
                                                    if (segments.size() > 1) {
                                                        messageId = Utilities.parseInt(segments.get(1));
                                                        if (messageId == 0) {
                                                            messageId = null;
                                                        }
                                                    }
                                                }
                                                if (messageId != null) {
                                                    videoTimestamp = getTimestampFromLink(data);
                                                }
                                                botUser = data.getQueryParameter("start");
                                                botChat = data.getQueryParameter("startgroup");
                                                game = data.getQueryParameter("game");
                                                voicechat = data.getQueryParameter("voicechat");
                                                livestream = data.getQueryParameter("livestream");
                                                threadId = Utilities.parseInt(data.getQueryParameter("thread"));
                                                if (threadId == 0) {
                                                    threadId = null;
                                                }
                                                commentId = Utilities.parseInt(data.getQueryParameter("comment"));
                                                if (commentId == 0) {
                                                    commentId = null;
                                                }
                                            }
                                        }
                                    }
                                    break;
                                }
                            case "tg":
                                {
                                    String url = data.toString();
                                    if (url.startsWith("tg:resolve") || url.startsWith("tg://resolve")) {
                                        url = url.replace("tg:resolve", "tg://telegram.org").replace("tg://resolve", "tg://telegram.org");
                                        data = Uri.parse(url);
                                        username = data.getQueryParameter("domain");
                                        if ("telegrampassport".equals(username)) {
                                            username = null;
                                            auth = new HashMap<>();
                                            String scope = data.getQueryParameter("scope");
                                            if (!TextUtils.isEmpty(scope) && scope.startsWith("{") && scope.endsWith("}")) {
                                                auth.put("nonce", data.getQueryParameter("nonce"));
                                            } else {
                                                auth.put("payload", data.getQueryParameter("payload"));
                                            }
                                            auth.put("bot_id", data.getQueryParameter("bot_id"));
                                            auth.put("scope", scope);
                                            auth.put("public_key", data.getQueryParameter("public_key"));
                                            auth.put("callback_url", data.getQueryParameter("callback_url"));
                                        } else {
                                            botUser = data.getQueryParameter("start");
                                            botChat = data.getQueryParameter("startgroup");
                                            game = data.getQueryParameter("game");
                                            voicechat = data.getQueryParameter("voicechat");
                                            livestream = data.getQueryParameter("livestream");
                                            messageId = Utilities.parseInt(data.getQueryParameter("post"));
                                            if (messageId == 0) {
                                                messageId = null;
                                            }
                                            threadId = Utilities.parseInt(data.getQueryParameter("thread"));
                                            if (threadId == 0) {
                                                threadId = null;
                                            }
                                            commentId = Utilities.parseInt(data.getQueryParameter("comment"));
                                            if (commentId == 0) {
                                                commentId = null;
                                            }
                                        }
                                    } else if (url.startsWith("tg:privatepost") || url.startsWith("tg://privatepost")) {
                                        url = url.replace("tg:privatepost", "tg://telegram.org").replace("tg://privatepost", "tg://telegram.org");
                                        data = Uri.parse(url);
                                        messageId = Utilities.parseInt(data.getQueryParameter("post"));
                                        channelId = Utilities.parseLong(data.getQueryParameter("channel"));
                                        if (messageId == 0 || channelId == 0) {
                                            messageId = null;
                                            channelId = null;
                                        }
                                        threadId = Utilities.parseInt(data.getQueryParameter("thread"));
                                        if (threadId == 0) {
                                            threadId = null;
                                        }
                                        commentId = Utilities.parseInt(data.getQueryParameter("comment"));
                                        if (commentId == 0) {
                                            commentId = null;
                                        }
                                    } else if (url.startsWith("tg:bg") || url.startsWith("tg://bg")) {
                                        url = url.replace("tg:bg", "tg://telegram.org").replace("tg://bg", "tg://telegram.org");
                                        data = Uri.parse(url);
                                        wallPaper = new TLRPC.TL_wallPaper();
                                        wallPaper.settings = new TLRPC.TL_wallPaperSettings();
                                        wallPaper.slug = data.getQueryParameter("slug");
                                        if (wallPaper.slug == null) {
                                            wallPaper.slug = data.getQueryParameter("color");
                                        }
                                        boolean ok = false;
                                        if (wallPaper.slug != null && wallPaper.slug.length() == 6) {
                                            try {
                                                wallPaper.settings.background_color = Integer.parseInt(wallPaper.slug, 16) | 0xff000000;
                                                wallPaper.slug = null;
                                                ok = true;
                                            } catch (Exception ignore) {
                                            }
                                        } else if (wallPaper.slug != null && wallPaper.slug.length() >= 13 && AndroidUtilities.isValidWallChar(wallPaper.slug.charAt(6))) {
                                            try {
                                                wallPaper.settings.background_color = Integer.parseInt(wallPaper.slug.substring(0, 6), 16) | 0xff000000;
                                                wallPaper.settings.second_background_color = Integer.parseInt(wallPaper.slug.substring(7, 13), 16) | 0xff000000;
                                                if (wallPaper.slug.length() >= 20 && AndroidUtilities.isValidWallChar(wallPaper.slug.charAt(13))) {
                                                    wallPaper.settings.third_background_color = Integer.parseInt(wallPaper.slug.substring(14, 20), 16) | 0xff000000;
                                                }
                                                if (wallPaper.slug.length() == 27 && AndroidUtilities.isValidWallChar(wallPaper.slug.charAt(20))) {
                                                    wallPaper.settings.fourth_background_color = Integer.parseInt(wallPaper.slug.substring(21), 16) | 0xff000000;
                                                }
                                                try {
                                                    String rotation = data.getQueryParameter("rotation");
                                                    if (!TextUtils.isEmpty(rotation)) {
                                                        wallPaper.settings.rotation = Utilities.parseInt(rotation);
                                                    }
                                                } catch (Exception ignore) {
                                                }
                                                wallPaper.slug = null;
                                                ok = true;
                                            } catch (Exception ignore) {
                                            }
                                        }
                                        if (!ok) {
                                            String mode = data.getQueryParameter("mode");
                                            if (mode != null) {
                                                mode = mode.toLowerCase();
                                                String[] modes = mode.split(" ");
                                                if (modes != null && modes.length > 0) {
                                                    for (int a = 0; a < modes.length; a++) {
                                                        if ("blur".equals(modes[a])) {
                                                            wallPaper.settings.blur = true;
                                                        } else if ("motion".equals(modes[a])) {
                                                            wallPaper.settings.motion = true;
                                                        }
                                                    }
                                                }
                                            }
                                            wallPaper.settings.intensity = Utilities.parseInt(data.getQueryParameter("intensity"));
                                            try {
                                                String bgColor = data.getQueryParameter("bg_color");
                                                if (!TextUtils.isEmpty(bgColor)) {
                                                    wallPaper.settings.background_color = Integer.parseInt(bgColor.substring(0, 6), 16) | 0xff000000;
                                                    if (bgColor.length() >= 13) {
                                                        wallPaper.settings.second_background_color = Integer.parseInt(bgColor.substring(8, 13), 16) | 0xff000000;
                                                        if (bgColor.length() >= 20 && AndroidUtilities.isValidWallChar(bgColor.charAt(13))) {
                                                            wallPaper.settings.third_background_color = Integer.parseInt(bgColor.substring(14, 20), 16) | 0xff000000;
                                                        }
                                                        if (bgColor.length() == 27 && AndroidUtilities.isValidWallChar(bgColor.charAt(20))) {
                                                            wallPaper.settings.fourth_background_color = Integer.parseInt(bgColor.substring(21), 16) | 0xff000000;
                                                        }
                                                    }
                                                }
                                            } catch (Exception ignore) {
                                            }
                                            try {
                                                String rotation = data.getQueryParameter("rotation");
                                                if (!TextUtils.isEmpty(rotation)) {
                                                    wallPaper.settings.rotation = Utilities.parseInt(rotation);
                                                }
                                            } catch (Exception ignore) {
                                            }
                                        }
                                    } else if (url.startsWith("tg:join") || url.startsWith("tg://join")) {
                                        url = url.replace("tg:join", "tg://telegram.org").replace("tg://join", "tg://telegram.org");
                                        data = Uri.parse(url);
                                        group = data.getQueryParameter("invite");
                                    } else if (url.startsWith("tg:addstickers") || url.startsWith("tg://addstickers")) {
                                        url = url.replace("tg:addstickers", "tg://telegram.org").replace("tg://addstickers", "tg://telegram.org");
                                        data = Uri.parse(url);
                                        sticker = data.getQueryParameter("set");
                                    } else if (url.startsWith("tg:msg") || url.startsWith("tg://msg") || url.startsWith("tg://share") || url.startsWith("tg:share")) {
                                        url = url.replace("tg:msg", "tg://telegram.org").replace("tg://msg", "tg://telegram.org").replace("tg://share", "tg://telegram.org").replace("tg:share", "tg://telegram.org");
                                        data = Uri.parse(url);
                                        message = data.getQueryParameter("url");
                                        if (message == null) {
                                            message = "";
                                        }
                                        if (data.getQueryParameter("text") != null) {
                                            if (message.length() > 0) {
                                                hasUrl = true;
                                                message += "\n";
                                            }
                                            message += data.getQueryParameter("text");
                                        }
                                        if (message.length() > 4096 * 4) {
                                            message = message.substring(0, 4096 * 4);
                                        }
                                        while (message.endsWith("\n")) {
                                            message = message.substring(0, message.length() - 1);
                                        }
                                    } else if (url.startsWith("tg:confirmphone") || url.startsWith("tg://confirmphone")) {
                                        url = url.replace("tg:confirmphone", "tg://telegram.org").replace("tg://confirmphone", "tg://telegram.org");
                                        data = Uri.parse(url);
                                        phone = data.getQueryParameter("phone");
                                        phoneHash = data.getQueryParameter("hash");
                                    } else if (url.startsWith("tg:login") || url.startsWith("tg://login")) {
                                        url = url.replace("tg:login", "tg://telegram.org").replace("tg://login", "tg://telegram.org");
                                        data = Uri.parse(url);
                                        login = data.getQueryParameter("token");
                                        int intCode = Utilities.parseInt(data.getQueryParameter("code"));
                                        if (intCode != 0) {
                                            code = "" + intCode;
                                        }
                                    } else if (url.startsWith("tg:openmessage") || url.startsWith("tg://openmessage")) {
                                        url = url.replace("tg:openmessage", "tg://telegram.org").replace("tg://openmessage", "tg://telegram.org");
                                        data = Uri.parse(url);
                                        String userID = data.getQueryParameter("user_id");
                                        String chatID = data.getQueryParameter("chat_id");
                                        String msgID = data.getQueryParameter("message_id");
                                        if (userID != null) {
                                            try {
                                                push_user_id = Long.parseLong(userID);
                                            } catch (NumberFormatException ignore) {
                                            }
                                        } else if (chatID != null) {
                                            try {
                                                push_chat_id = Long.parseLong(chatID);
                                            } catch (NumberFormatException ignore) {
                                            }
                                        }
                                        if (msgID != null) {
                                            try {
                                                push_msg_id = Integer.parseInt(msgID);
                                            } catch (NumberFormatException ignore) {
                                            }
                                        }
                                    } else if (url.startsWith("tg:passport") || url.startsWith("tg://passport") || url.startsWith("tg:secureid")) {
                                        url = url.replace("tg:passport", "tg://telegram.org").replace("tg://passport", "tg://telegram.org").replace("tg:secureid", "tg://telegram.org");
                                        data = Uri.parse(url);
                                        auth = new HashMap<>();
                                        String scope = data.getQueryParameter("scope");
                                        if (!TextUtils.isEmpty(scope) && scope.startsWith("{") && scope.endsWith("}")) {
                                            auth.put("nonce", data.getQueryParameter("nonce"));
                                        } else {
                                            auth.put("payload", data.getQueryParameter("payload"));
                                        }
                                        auth.put("bot_id", data.getQueryParameter("bot_id"));
                                        auth.put("scope", scope);
                                        auth.put("public_key", data.getQueryParameter("public_key"));
                                        auth.put("callback_url", data.getQueryParameter("callback_url"));
                                    } else if (url.startsWith("tg:setlanguage") || url.startsWith("tg://setlanguage")) {
                                        url = url.replace("tg:setlanguage", "tg://telegram.org").replace("tg://setlanguage", "tg://telegram.org");
                                        data = Uri.parse(url);
                                        lang = data.getQueryParameter("lang");
                                    } else if (url.startsWith("tg:addtheme") || url.startsWith("tg://addtheme")) {
                                        url = url.replace("tg:addtheme", "tg://telegram.org").replace("tg://addtheme", "tg://telegram.org");
                                        data = Uri.parse(url);
                                        theme = data.getQueryParameter("slug");
                                    } else if (url.startsWith("tg:settings") || url.startsWith("tg://settings")) {
                                        if (url.contains("themes")) {
                                            open_settings = 2;
                                        } else if (url.contains("devices")) {
                                            open_settings = 3;
                                        } else if (url.contains("folders")) {
                                            open_settings = 4;
                                        } else if (url.contains("change_number")) {
                                            open_settings = 5;
                                        } else {
                                            open_settings = 1;
                                        }
                                    } else if ((url.startsWith("tg:search") || url.startsWith("tg://search"))) {
                                        url = url.replace("tg:search", "tg://telegram.org").replace("tg://search", "tg://telegram.org");
                                        data = Uri.parse(url);
                                        searchQuery = data.getQueryParameter("query");
                                        if (searchQuery != null) {
                                            searchQuery = searchQuery.trim();
                                        } else {
                                            searchQuery = "";
                                        }
                                    } else if ((url.startsWith("tg:calllog") || url.startsWith("tg://calllog"))) {
                                        showCallLog = true;
                                    } else if ((url.startsWith("tg:call") || url.startsWith("tg://call"))) {
                                        if (UserConfig.getInstance(currentAccount).isClientActivated()) {
                                            final String extraForceCall = "extra_force_call";
                                            if (ContactsController.getInstance(currentAccount).contactsLoaded || intent.hasExtra(extraForceCall)) {
                                                final String callFormat = data.getQueryParameter("format");
                                                final String callUserName = data.getQueryParameter("name");
                                                final String callPhone = data.getQueryParameter("phone");
                                                final List<TLRPC.TL_contact> contacts = findContacts(callUserName, callPhone, false);
                                                if (contacts.isEmpty() && callPhone != null) {
                                                    newContactName = callUserName;
                                                    newContactPhone = callPhone;
                                                    newContactAlert = true;
                                                } else {
                                                    if (contacts.size() == 1) {
                                                        push_user_id = contacts.get(0).user_id;
                                                    }
                                                    if (push_user_id == 0) {
                                                        callSearchQuery = callUserName != null ? callUserName : "";
                                                    }
                                                    if ("video".equalsIgnoreCase(callFormat)) {
                                                        videoCallUser = true;
                                                    } else {
                                                        audioCallUser = true;
                                                    }
                                                    needCallAlert = true;
                                                }
                                            } else {
                                                final Intent copyIntent = new Intent(intent);
                                                copyIntent.removeExtra(EXTRA_ACTION_TOKEN);
                                                copyIntent.putExtra(extraForceCall, true);
                                                ContactsLoadingObserver.observe((contactsLoaded) -> handleIntent(copyIntent, true, false, false), 1000);
                                            }
                                        }
                                    } else if ((url.startsWith("tg:scanqr") || url.startsWith("tg://scanqr"))) {
                                        scanQr = true;
                                    } else if ((url.startsWith("tg:addcontact") || url.startsWith("tg://addcontact"))) {
                                        url = url.replace("tg:addcontact", "tg://telegram.org").replace("tg://addcontact", "tg://telegram.org");
                                        data = Uri.parse(url);
                                        newContactName = data.getQueryParameter("name");
                                        newContactPhone = data.getQueryParameter("phone");
                                        newContact = true;
                                    } else {
                                        unsupportedUrl = url.replace("tg://", "").replace("tg:", "");
                                        int index;
                                        if ((index = unsupportedUrl.indexOf('?')) >= 0) {
                                            unsupportedUrl = unsupportedUrl.substring(0, index);
                                        }
                                    }
                                    break;
                                }
                        }
                    }
                    if (intent.hasExtra(EXTRA_ACTION_TOKEN)) {
                        final boolean success = UserConfig.getInstance(currentAccount).isClientActivated() && "tg".equals(scheme) && unsupportedUrl == null;
                        intent.removeExtra(EXTRA_ACTION_TOKEN);
                    }
                    if (code != null || UserConfig.getInstance(currentAccount).isClientActivated()) {
                        if (phone != null || phoneHash != null) {
                            final Bundle args = new Bundle();
                            args.putString("phone", phone);
                            args.putString("hash", phoneHash);
                            AndroidUtilities.runOnUIThread(() -> presentFragment(new CancelAccountDeletionActivity(args)));
                        } else if (username != null || group != null || sticker != null || message != null || game != null || voicechat != null || auth != null || unsupportedUrl != null || lang != null || code != null || wallPaper != null || channelId != null || theme != null || login != null) {
                            if (message != null && message.startsWith("@")) {
                                message = " " + message;
                            }
                            runLinkRequest(intentAccount[0], username, group, sticker, botUser, botChat, message, hasUrl, messageId, channelId, threadId, commentId, game, auth, lang, unsupportedUrl, code, login, wallPaper, theme, voicechat, livestream, 0, videoTimestamp);
                        } else {
                            try (Cursor cursor = getContentResolver().query(intent.getData(), null, null, null, null)) {
                                if (cursor != null) {
                                    if (cursor.moveToFirst()) {
                                        int accountId = Utilities.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_NAME)));
                                        for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
                                            if (UserConfig.getInstance(a).getClientUserId() == accountId) {
                                                intentAccount[0] = a;
                                                switchToAccount(intentAccount[0], true);
                                                break;
                                            }
                                        }
                                        long userId = cursor.getLong(cursor.getColumnIndex(ContactsContract.Data.DATA4));
                                        NotificationCenter.getInstance(intentAccount[0]).postNotificationName(NotificationCenter.closeChats);
                                        push_user_id = userId;
                                        String mimeType = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE));
                                        if (TextUtils.equals(mimeType, "vnd.android.cursor.item/vnd.org.telegram.messenger.android.call")) {
                                            audioCallUser = true;
                                        } else if (TextUtils.equals(mimeType, "vnd.android.cursor.item/vnd.org.telegram.messenger.android.call.video")) {
                                            videoCallUser = true;
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                FileLog.e(e);
                            }
                        }
                    }
                }
            } else if (intent.getAction().equals("org.telegram.messenger.OPEN_ACCOUNT")) {
                open_settings = 1;
            } else if (intent.getAction().equals("new_dialog")) {
                open_new_dialog = 1;
            } else if (intent.getAction().startsWith("com.tmessages.openchat")) {
                long chatId = intent.getLongExtra("chatId", intent.getIntExtra("chatId", 0));
                long userId = intent.getLongExtra("userId", intent.getIntExtra("userId", 0));
                int encId = intent.getIntExtra("encId", 0);
                int widgetId = intent.getIntExtra("appWidgetId", 0);
                if (widgetId != 0) {
                    open_settings = 6;
                    open_widget_edit = widgetId;
                    open_widget_edit_type = intent.getIntExtra("appWidgetType", 0);
                } else {
                    if (push_msg_id == 0) {
                        push_msg_id = intent.getIntExtra("message_id", 0);
                    }
                    if (chatId != 0) {
                        NotificationCenter.getInstance(intentAccount[0]).postNotificationName(NotificationCenter.closeChats);
                        push_chat_id = chatId;
                    } else if (userId != 0) {
                        NotificationCenter.getInstance(intentAccount[0]).postNotificationName(NotificationCenter.closeChats);
                        push_user_id = userId;
                    } else if (encId != 0) {
                        NotificationCenter.getInstance(intentAccount[0]).postNotificationName(NotificationCenter.closeChats);
                        push_enc_id = encId;
                    } else {
                        showDialogsList = true;
                    }
                }
            } else if (intent.getAction().equals("com.tmessages.openplayer")) {
                showPlayer = true;
            } else if (intent.getAction().equals("org.tmessages.openlocations")) {
                showLocations = true;
            } else if (action.equals("voip_chat")) {
                showGroupVoip = true;
            }
        }
    }
    if (UserConfig.getInstance(currentAccount).isClientActivated()) {
        if (searchQuery != null) {
            final BaseFragment lastFragment = actionBarLayout.getLastFragment();
            if (lastFragment instanceof DialogsActivity) {
                final DialogsActivity dialogsActivity = (DialogsActivity) lastFragment;
                if (dialogsActivity.isMainDialogList()) {
                    if (dialogsActivity.getFragmentView() != null) {
                        dialogsActivity.search(searchQuery, true);
                    } else {
                        dialogsActivity.setInitialSearchString(searchQuery);
                    }
                }
            } else {
                showDialogsList = true;
            }
        }
        if (push_user_id != 0) {
            if (audioCallUser || videoCallUser) {
                if (needCallAlert) {
                    final BaseFragment lastFragment = actionBarLayout.getLastFragment();
                    if (lastFragment != null) {
                        AlertsCreator.createCallDialogAlert(lastFragment, lastFragment.getMessagesController().getUser(push_user_id), videoCallUser);
                    }
                } else {
                    VoIPPendingCall.startOrSchedule(this, push_user_id, videoCallUser, AccountInstance.getInstance(intentAccount[0]));
                }
            } else {
                Bundle args = new Bundle();
                args.putLong("user_id", push_user_id);
                if (push_msg_id != 0) {
                    args.putInt("message_id", push_msg_id);
                }
                if (mainFragmentsStack.isEmpty() || MessagesController.getInstance(intentAccount[0]).checkCanOpenChat(args, mainFragmentsStack.get(mainFragmentsStack.size() - 1))) {
                    ChatActivity fragment = new ChatActivity(args);
                    if (actionBarLayout.presentFragment(fragment, false, true, true, false)) {
                        pushOpened = true;
                        drawerLayoutContainer.closeDrawer();
                    }
                }
            }
        } else if (push_chat_id != 0) {
            Bundle args = new Bundle();
            args.putLong("chat_id", push_chat_id);
            if (push_msg_id != 0) {
                args.putInt("message_id", push_msg_id);
            }
            if (mainFragmentsStack.isEmpty() || MessagesController.getInstance(intentAccount[0]).checkCanOpenChat(args, mainFragmentsStack.get(mainFragmentsStack.size() - 1))) {
                ChatActivity fragment = new ChatActivity(args);
                if (actionBarLayout.presentFragment(fragment, false, true, true, false)) {
                    pushOpened = true;
                    drawerLayoutContainer.closeDrawer();
                }
            }
        } else if (push_enc_id != 0) {
            Bundle args = new Bundle();
            args.putInt("enc_id", push_enc_id);
            ChatActivity fragment = new ChatActivity(args);
            if (actionBarLayout.presentFragment(fragment, false, true, true, false)) {
                pushOpened = true;
                drawerLayoutContainer.closeDrawer();
            }
        } else if (showDialogsList) {
            if (!AndroidUtilities.isTablet()) {
                actionBarLayout.removeAllFragments();
            } else {
                if (!layersActionBarLayout.fragmentsStack.isEmpty()) {
                    for (int a = 0; a < layersActionBarLayout.fragmentsStack.size() - 1; a++) {
                        layersActionBarLayout.removeFragmentFromStack(layersActionBarLayout.fragmentsStack.get(0));
                        a--;
                    }
                    layersActionBarLayout.closeLastFragment(false);
                }
            }
            pushOpened = false;
            isNew = false;
        } else if (showPlayer) {
            if (!actionBarLayout.fragmentsStack.isEmpty()) {
                BaseFragment fragment = actionBarLayout.fragmentsStack.get(0);
                fragment.showDialog(new AudioPlayerAlert(this, null));
            }
            pushOpened = false;
        } else if (showLocations) {
            if (!actionBarLayout.fragmentsStack.isEmpty()) {
                BaseFragment fragment = actionBarLayout.fragmentsStack.get(0);
                fragment.showDialog(new SharingLocationsAlert(this, info -> {
                    intentAccount[0] = info.messageObject.currentAccount;
                    switchToAccount(intentAccount[0], true);
                    LocationActivity locationActivity = new LocationActivity(2);
                    locationActivity.setMessageObject(info.messageObject);
                    final long dialog_id = info.messageObject.getDialogId();
                    locationActivity.setDelegate((location, live, notify, scheduleDate) -> SendMessagesHelper.getInstance(intentAccount[0]).sendMessage(location, dialog_id, null, null, null, null, notify, scheduleDate));
                    presentFragment(locationActivity);
                }, null));
            }
            pushOpened = false;
        } else if (exportingChatUri != null) {
            runImportRequest(exportingChatUri, documentsUrisArray);
        } else if (importingStickers != null) {
            AndroidUtilities.runOnUIThread(() -> {
                if (!actionBarLayout.fragmentsStack.isEmpty()) {
                    BaseFragment fragment = actionBarLayout.fragmentsStack.get(0);
                    fragment.showDialog(new StickersAlert(this, importingStickersSoftware, importingStickers, importingStickersEmoji, null));
                }
            });
            pushOpened = false;
        } else if (videoPath != null || photoPathsArray != null || sendingText != null || sendingLocation != null || documentsPathsArray != null || contactsToSend != null || documentsUrisArray != null) {
            if (!AndroidUtilities.isTablet()) {
                NotificationCenter.getInstance(intentAccount[0]).postNotificationName(NotificationCenter.closeChats);
            }
            if (dialogId == 0) {
                openDialogsToSend(false);
                pushOpened = true;
            } else {
                ArrayList<Long> dids = new ArrayList<>();
                dids.add(dialogId);
                didSelectDialogs(null, dids, null, false);
            }
        } else if (open_settings != 0) {
            BaseFragment fragment;
            boolean closePrevious = false;
            if (open_settings == 1) {
                Bundle args = new Bundle();
                args.putLong("user_id", UserConfig.getInstance(currentAccount).clientUserId);
                fragment = new ProfileActivity(args);
            } else if (open_settings == 2) {
                fragment = new ThemeActivity(ThemeActivity.THEME_TYPE_BASIC);
            } else if (open_settings == 3) {
                fragment = new SessionsActivity(0);
            } else if (open_settings == 4) {
                fragment = new FiltersSetupActivity();
            } else if (open_settings == 5) {
                fragment = new ActionIntroActivity(ActionIntroActivity.ACTION_TYPE_CHANGE_PHONE_NUMBER);
                closePrevious = true;
            } else if (open_settings == 6) {
                fragment = new EditWidgetActivity(open_widget_edit_type, open_widget_edit);
            } else {
                fragment = null;
            }
            boolean closePreviousFinal = closePrevious;
            if (open_settings == 6) {
                actionBarLayout.presentFragment(fragment, false, true, true, false);
            } else {
                AndroidUtilities.runOnUIThread(() -> presentFragment(fragment, closePreviousFinal, false));
            }
            if (AndroidUtilities.isTablet()) {
                actionBarLayout.showLastFragment();
                rightActionBarLayout.showLastFragment();
                drawerLayoutContainer.setAllowOpenDrawer(false, false);
            } else {
                drawerLayoutContainer.setAllowOpenDrawer(true, false);
            }
            pushOpened = true;
        } else if (open_new_dialog != 0) {
            Bundle args = new Bundle();
            args.putBoolean("destroyAfterSelect", true);
            actionBarLayout.presentFragment(new ContactsActivity(args), false, true, true, false);
            if (AndroidUtilities.isTablet()) {
                actionBarLayout.showLastFragment();
                rightActionBarLayout.showLastFragment();
                drawerLayoutContainer.setAllowOpenDrawer(false, false);
            } else {
                drawerLayoutContainer.setAllowOpenDrawer(true, false);
            }
            pushOpened = true;
        } else if (callSearchQuery != null) {
            final Bundle args = new Bundle();
            args.putBoolean("destroyAfterSelect", true);
            args.putBoolean("returnAsResult", true);
            args.putBoolean("onlyUsers", true);
            args.putBoolean("allowSelf", false);
            final ContactsActivity contactsFragment = new ContactsActivity(args);
            contactsFragment.setInitialSearchString(callSearchQuery);
            final boolean videoCall = videoCallUser;
            contactsFragment.setDelegate((user, param, activity) -> {
                final TLRPC.UserFull userFull = MessagesController.getInstance(currentAccount).getUserFull(user.id);
                VoIPHelper.startCall(user, videoCall, userFull != null && userFull.video_calls_available, LaunchActivity.this, userFull, AccountInstance.getInstance(intentAccount[0]));
            });
            actionBarLayout.presentFragment(contactsFragment, actionBarLayout.getLastFragment() instanceof ContactsActivity, true, true, false);
            if (AndroidUtilities.isTablet()) {
                actionBarLayout.showLastFragment();
                rightActionBarLayout.showLastFragment();
                drawerLayoutContainer.setAllowOpenDrawer(false, false);
            } else {
                drawerLayoutContainer.setAllowOpenDrawer(true, false);
            }
            pushOpened = true;
        } else if (scanQr) {
            ActionIntroActivity fragment = new ActionIntroActivity(ActionIntroActivity.ACTION_TYPE_QR_LOGIN);
            fragment.setQrLoginDelegate(code -> {
                AlertDialog progressDialog = new AlertDialog(LaunchActivity.this, 3);
                progressDialog.setCanCacnel(false);
                progressDialog.show();
                byte[] token = Base64.decode(code.substring("tg://login?token=".length()), Base64.URL_SAFE);
                TLRPC.TL_auth_acceptLoginToken req = new TLRPC.TL_auth_acceptLoginToken();
                req.token = token;
                ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
                    try {
                        progressDialog.dismiss();
                    } catch (Exception ignore) {
                    }
                    if (!(response instanceof TLRPC.TL_authorization)) {
                        AndroidUtilities.runOnUIThread(() -> AlertsCreator.showSimpleAlert(fragment, LocaleController.getString("AuthAnotherClient", R.string.AuthAnotherClient), LocaleController.getString("ErrorOccurred", R.string.ErrorOccurred) + "\n" + error.text));
                    }
                }));
            });
            actionBarLayout.presentFragment(fragment, false, true, true, false);
            if (AndroidUtilities.isTablet()) {
                actionBarLayout.showLastFragment();
                rightActionBarLayout.showLastFragment();
                drawerLayoutContainer.setAllowOpenDrawer(false, false);
            } else {
                drawerLayoutContainer.setAllowOpenDrawer(true, false);
            }
            pushOpened = true;
        } else if (newContact) {
            final NewContactActivity fragment = new NewContactActivity();
            if (newContactName != null) {
                final String[] names = newContactName.split(" ", 2);
                fragment.setInitialName(names[0], names.length > 1 ? names[1] : null);
            }
            if (newContactPhone != null) {
                fragment.setInitialPhoneNumber(PhoneFormat.stripExceptNumbers(newContactPhone, true), false);
            }
            actionBarLayout.presentFragment(fragment, false, true, true, false);
            if (AndroidUtilities.isTablet()) {
                actionBarLayout.showLastFragment();
                rightActionBarLayout.showLastFragment();
                drawerLayoutContainer.setAllowOpenDrawer(false, false);
            } else {
                drawerLayoutContainer.setAllowOpenDrawer(true, false);
            }
            pushOpened = true;
        } else if (showGroupVoip) {
            GroupCallActivity.create(this, AccountInstance.getInstance(currentAccount), null, null, false, null);
            if (GroupCallActivity.groupCallInstance != null) {
                GroupCallActivity.groupCallUiVisible = true;
            }
        } else if (newContactAlert) {
            final BaseFragment lastFragment = actionBarLayout.getLastFragment();
            if (lastFragment != null && lastFragment.getParentActivity() != null) {
                final String finalNewContactName = newContactName;
                final String finalNewContactPhone = NewContactActivity.getPhoneNumber(this, UserConfig.getInstance(currentAccount).getCurrentUser(), newContactPhone, false);
                final AlertDialog newContactAlertDialog = new AlertDialog.Builder(lastFragment.getParentActivity()).setTitle(LocaleController.getString("NewContactAlertTitle", R.string.NewContactAlertTitle)).setMessage(AndroidUtilities.replaceTags(LocaleController.formatString("NewContactAlertMessage", R.string.NewContactAlertMessage, PhoneFormat.getInstance().format(finalNewContactPhone)))).setPositiveButton(LocaleController.getString("NewContactAlertButton", R.string.NewContactAlertButton), (d, i) -> {
                    final NewContactActivity fragment = new NewContactActivity();
                    fragment.setInitialPhoneNumber(finalNewContactPhone, false);
                    if (finalNewContactName != null) {
                        final String[] names = finalNewContactName.split(" ", 2);
                        fragment.setInitialName(names[0], names.length > 1 ? names[1] : null);
                    }
                    lastFragment.presentFragment(fragment);
                }).setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null).create();
                lastFragment.showDialog(newContactAlertDialog);
                pushOpened = true;
            }
        } else if (showCallLog) {
            actionBarLayout.presentFragment(new CallLogActivity(), false, true, true, false);
            if (AndroidUtilities.isTablet()) {
                actionBarLayout.showLastFragment();
                rightActionBarLayout.showLastFragment();
                drawerLayoutContainer.setAllowOpenDrawer(false, false);
            } else {
                drawerLayoutContainer.setAllowOpenDrawer(true, false);
            }
            pushOpened = true;
        }
    }
    if (!pushOpened && !isNew) {
        if (AndroidUtilities.isTablet()) {
            if (!UserConfig.getInstance(currentAccount).isClientActivated()) {
                if (layersActionBarLayout.fragmentsStack.isEmpty()) {
                    layersActionBarLayout.addFragmentToStack(new LoginActivity());
                    drawerLayoutContainer.setAllowOpenDrawer(false, false);
                }
            } else {
                if (actionBarLayout.fragmentsStack.isEmpty()) {
                    DialogsActivity dialogsActivity = new DialogsActivity(null);
                    dialogsActivity.setSideMenu(sideMenu);
                    if (searchQuery != null) {
                        dialogsActivity.setInitialSearchString(searchQuery);
                    }
                    actionBarLayout.addFragmentToStack(dialogsActivity);
                    drawerLayoutContainer.setAllowOpenDrawer(true, false);
                }
            }
        } else {
            if (actionBarLayout.fragmentsStack.isEmpty()) {
                if (!UserConfig.getInstance(currentAccount).isClientActivated()) {
                    actionBarLayout.addFragmentToStack(new LoginActivity());
                    drawerLayoutContainer.setAllowOpenDrawer(false, false);
                } else {
                    DialogsActivity dialogsActivity = new DialogsActivity(null);
                    dialogsActivity.setSideMenu(sideMenu);
                    if (searchQuery != null) {
                        dialogsActivity.setInitialSearchString(searchQuery);
                    }
                    actionBarLayout.addFragmentToStack(dialogsActivity);
                    drawerLayoutContainer.setAllowOpenDrawer(true, false);
                }
            }
        }
        actionBarLayout.showLastFragment();
        if (AndroidUtilities.isTablet()) {
            layersActionBarLayout.showLastFragment();
            rightActionBarLayout.showLastFragment();
        }
    }
    if (isVoipIntent) {
        VoIPFragment.show(this, intentAccount[0]);
    }
    if (!showGroupVoip && (intent == null || !Intent.ACTION_MAIN.equals(intent.getAction())) && GroupCallActivity.groupCallInstance != null) {
        GroupCallActivity.groupCallInstance.dismiss();
    }
    intent.setAction(null);
    return pushOpened;
}
Also used : 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) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) UpdateAppAlertDialog(org.telegram.ui.Components.UpdateAppAlertDialog) SendMessagesHelper(org.telegram.messenger.SendMessagesHelper) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Cursor(android.database.Cursor) TLRPC(org.telegram.tgnet.TLRPC) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) SharingLocationsAlert(org.telegram.ui.Components.SharingLocationsAlert) ArrayList(java.util.ArrayList) List(java.util.List) ShortcutInfoCompat(androidx.core.content.pm.ShortcutInfoCompat) Parcelable(android.os.Parcelable) StickersAlert(org.telegram.ui.Components.StickersAlert) Matcher(java.util.regex.Matcher) AudioPlayerAlert(org.telegram.ui.Components.AudioPlayerAlert) Uri(android.net.Uri) Pattern(java.util.regex.Pattern) Bundle(android.os.Bundle) Intent(android.content.Intent) Paint(android.graphics.Paint) Point(android.graphics.Point) ParseException(java.text.ParseException) Location(android.location.Location)

Example 29 with AlertDialog

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

the class GroupCallActivity method onLeaveClick.

public static void onLeaveClick(Context context, Runnable onLeave, boolean fromOverlayWindow) {
    VoIPService service = VoIPService.getSharedInstance();
    if (service == null) {
        return;
    }
    TLRPC.Chat currentChat = service.getChat();
    ChatObject.Call call = service.groupCall;
    long selfId = service.getSelfId();
    if (!ChatObject.canManageCalls(currentChat)) {
        processOnLeave(call, false, selfId, onLeave);
        return;
    }
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    if (ChatObject.isChannelOrGiga(currentChat)) {
        builder.setTitle(LocaleController.getString("VoipChannelLeaveAlertTitle", R.string.VoipChannelLeaveAlertTitle));
        builder.setMessage(LocaleController.getString("VoipChannelLeaveAlertText", R.string.VoipChannelLeaveAlertText));
    } else {
        builder.setTitle(LocaleController.getString("VoipGroupLeaveAlertTitle", R.string.VoipGroupLeaveAlertTitle));
        builder.setMessage(LocaleController.getString("VoipGroupLeaveAlertText", R.string.VoipGroupLeaveAlertText));
    }
    int currentAccount = service.getAccount();
    CheckBoxCell[] cells = new CheckBoxCell[1];
    LinearLayout linearLayout = new LinearLayout(context);
    linearLayout.setOrientation(LinearLayout.VERTICAL);
    cells[0] = new CheckBoxCell(context, 1);
    cells[0].setBackgroundDrawable(Theme.getSelectorDrawable(false));
    if (fromOverlayWindow) {
        cells[0].setTextColor(Theme.getColor(Theme.key_dialogTextBlack));
    } else {
        cells[0].setTextColor(Theme.getColor(Theme.key_voipgroup_actionBarItems));
        CheckBoxSquare checkBox = (CheckBoxSquare) cells[0].getCheckBoxView();
        checkBox.setColors(Theme.key_voipgroup_mutedIcon, Theme.key_voipgroup_listeningText, Theme.key_voipgroup_nameText);
    }
    cells[0].setTag(0);
    if (ChatObject.isChannelOrGiga(currentChat)) {
        cells[0].setText(LocaleController.getString("VoipChannelLeaveAlertEndChat", R.string.VoipChannelLeaveAlertEndChat), "", false, false);
    } else {
        cells[0].setText(LocaleController.getString("VoipGroupLeaveAlertEndChat", R.string.VoipGroupLeaveAlertEndChat), "", false, false);
    }
    cells[0].setPadding(LocaleController.isRTL ? AndroidUtilities.dp(16) : AndroidUtilities.dp(8), 0, LocaleController.isRTL ? AndroidUtilities.dp(8) : AndroidUtilities.dp(16), 0);
    linearLayout.addView(cells[0], LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    cells[0].setOnClickListener(v -> {
        Integer num = (Integer) v.getTag();
        cells[num].setChecked(!cells[num].isChecked(), true);
    });
    builder.setCustomViewOffset(12);
    builder.setView(linearLayout);
    builder.setDialogButtonColorKey(Theme.key_voipgroup_listeningText);
    builder.setPositiveButton(LocaleController.getString("VoipGroupLeave", R.string.VoipGroupLeave), (dialogInterface, position) -> processOnLeave(call, cells[0].isChecked(), selfId, onLeave));
    builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
    if (fromOverlayWindow) {
        builder.setDimEnabled(false);
    }
    AlertDialog dialog = builder.create();
    if (fromOverlayWindow) {
        if (Build.VERSION.SDK_INT >= 26) {
            dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
        } else {
            dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        }
        dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }
    if (!fromOverlayWindow) {
        dialog.setBackgroundColor(Theme.getColor(Theme.key_voipgroup_dialogBackground));
    }
    dialog.show();
    if (!fromOverlayWindow) {
        TextView button = (TextView) dialog.getButton(DialogInterface.BUTTON_POSITIVE);
        if (button != null) {
            button.setTextColor(Theme.getColor(Theme.key_voipgroup_leaveCallMenu));
        }
        dialog.setTextColor(Theme.getColor(Theme.key_voipgroup_actionBarItems));
    }
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) CheckBoxSquare(org.telegram.ui.Components.CheckBoxSquare) ChatObject(org.telegram.messenger.ChatObject) SpannableStringBuilder(android.text.SpannableStringBuilder) TLRPC(org.telegram.tgnet.TLRPC) Paint(android.graphics.Paint) SuppressLint(android.annotation.SuppressLint) CheckBoxCell(org.telegram.ui.Cells.CheckBoxCell) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) TextView(android.widget.TextView) LinearLayout(android.widget.LinearLayout) VoIPService(org.telegram.messenger.voip.VoIPService)

Example 30 with AlertDialog

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

the class NotificationsSettingsActivity method createView.

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

        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                finishFragment();
            }
        }
    });
    fragmentView = new FrameLayout(context);
    FrameLayout frameLayout = (FrameLayout) fragmentView;
    frameLayout.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundGray));
    listView = new RecyclerListView(context);
    listView.setItemAnimator(null);
    listView.setLayoutAnimation(null);
    listView.setLayoutManager(layoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) {

        @Override
        public boolean supportsPredictiveItemAnimations() {
            return false;
        }
    });
    listView.setVerticalScrollBarEnabled(false);
    frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    listView.setAdapter(adapter = new ListAdapter(context));
    listView.setOnItemClickListener((view, position, x, y) -> {
        boolean enabled = false;
        if (getParentActivity() == null) {
            return;
        }
        if (position == privateRow || position == groupRow || position == channelsRow) {
            int type;
            ArrayList<NotificationException> exceptions;
            if (position == privateRow) {
                type = NotificationsController.TYPE_PRIVATE;
                exceptions = exceptionUsers;
            } else if (position == groupRow) {
                type = NotificationsController.TYPE_GROUP;
                exceptions = exceptionChats;
            } else {
                type = NotificationsController.TYPE_CHANNEL;
                exceptions = exceptionChannels;
            }
            if (exceptions == null) {
                return;
            }
            NotificationsCheckCell checkCell = (NotificationsCheckCell) view;
            enabled = getNotificationsController().isGlobalNotificationsEnabled(type);
            if (LocaleController.isRTL && x <= AndroidUtilities.dp(76) || !LocaleController.isRTL && x >= view.getMeasuredWidth() - AndroidUtilities.dp(76)) {
                getNotificationsController().setGlobalNotificationsEnabled(type, !enabled ? 0 : Integer.MAX_VALUE);
                showExceptionsAlert(position);
                checkCell.setChecked(!enabled, 0);
                adapter.notifyItemChanged(position);
            } else {
                presentFragment(new NotificationsCustomSettingsActivity(type, exceptions));
            }
        } else if (position == callsRingtoneRow) {
            try {
                SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount);
                Intent tmpIntent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
                tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_RINGTONE);
                tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true);
                tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, true);
                tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE));
                Uri currentSound = null;
                String defaultPath = null;
                Uri defaultUri = Settings.System.DEFAULT_RINGTONE_URI;
                if (defaultUri != null) {
                    defaultPath = defaultUri.getPath();
                }
                String path = preferences.getString("CallsRingtonePath", defaultPath);
                if (path != null && !path.equals("NoSound")) {
                    if (path.equals(defaultPath)) {
                        currentSound = defaultUri;
                    } else {
                        currentSound = Uri.parse(path);
                    }
                }
                tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, currentSound);
                startActivityForResult(tmpIntent, position);
            } catch (Exception e) {
                FileLog.e(e);
            }
        } else if (position == resetNotificationsRow) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
            builder.setTitle(LocaleController.getString("ResetNotificationsAlertTitle", R.string.ResetNotificationsAlertTitle));
            builder.setMessage(LocaleController.getString("ResetNotificationsAlert", R.string.ResetNotificationsAlert));
            builder.setPositiveButton(LocaleController.getString("Reset", R.string.Reset), (dialogInterface, i) -> {
                if (reseting) {
                    return;
                }
                reseting = true;
                TLRPC.TL_account_resetNotifySettings req = new TLRPC.TL_account_resetNotifySettings();
                ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
                    getMessagesController().enableJoined = true;
                    reseting = false;
                    SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount);
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.clear();
                    editor.commit();
                    exceptionChats.clear();
                    exceptionUsers.clear();
                    adapter.notifyDataSetChanged();
                    if (getParentActivity() != null) {
                        Toast toast = Toast.makeText(getParentActivity(), LocaleController.getString("ResetNotificationsText", R.string.ResetNotificationsText), Toast.LENGTH_SHORT);
                        toast.show();
                    }
                    getMessagesStorage().updateMutedDialogsFiltersCounters();
                }));
            });
            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));
            }
        } else if (position == inappSoundRow) {
            SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount);
            SharedPreferences.Editor editor = preferences.edit();
            enabled = preferences.getBoolean("EnableInAppSounds", true);
            editor.putBoolean("EnableInAppSounds", !enabled);
            editor.commit();
        } else if (position == inappVibrateRow) {
            SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount);
            SharedPreferences.Editor editor = preferences.edit();
            enabled = preferences.getBoolean("EnableInAppVibrate", true);
            editor.putBoolean("EnableInAppVibrate", !enabled);
            editor.commit();
        } else if (position == inappPreviewRow) {
            SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount);
            SharedPreferences.Editor editor = preferences.edit();
            enabled = preferences.getBoolean("EnableInAppPreview", true);
            editor.putBoolean("EnableInAppPreview", !enabled);
            editor.commit();
        } else if (position == inchatSoundRow) {
            SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount);
            SharedPreferences.Editor editor = preferences.edit();
            enabled = preferences.getBoolean("EnableInChatSound", true);
            editor.putBoolean("EnableInChatSound", !enabled);
            editor.commit();
            getNotificationsController().setInChatSoundEnabled(!enabled);
        } else if (position == inappPriorityRow) {
            SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount);
            SharedPreferences.Editor editor = preferences.edit();
            enabled = preferences.getBoolean("EnableInAppPriority", false);
            editor.putBoolean("EnableInAppPriority", !enabled);
            editor.commit();
        } else if (position == contactJoinedRow) {
            SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount);
            SharedPreferences.Editor editor = preferences.edit();
            enabled = preferences.getBoolean("EnableContactJoined", true);
            MessagesController.getInstance(currentAccount).enableJoined = !enabled;
            editor.putBoolean("EnableContactJoined", !enabled);
            editor.commit();
            TLRPC.TL_account_setContactSignUpNotification req = new TLRPC.TL_account_setContactSignUpNotification();
            req.silent = enabled;
            ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> {
            });
        } else if (position == pinnedMessageRow) {
            SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount);
            SharedPreferences.Editor editor = preferences.edit();
            enabled = preferences.getBoolean("PinnedMessages", true);
            editor.putBoolean("PinnedMessages", !enabled);
            editor.commit();
        } else if (position == androidAutoAlertRow) {
            SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount);
            SharedPreferences.Editor editor = preferences.edit();
            enabled = preferences.getBoolean("EnableAutoNotifications", false);
            editor.putBoolean("EnableAutoNotifications", !enabled);
            editor.commit();
        } else if (position == badgeNumberShowRow) {
            SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount);
            SharedPreferences.Editor editor = preferences.edit();
            enabled = getNotificationsController().showBadgeNumber;
            getNotificationsController().showBadgeNumber = !enabled;
            editor.putBoolean("badgeNumber", getNotificationsController().showBadgeNumber);
            editor.commit();
            getNotificationsController().updateBadge();
        } else if (position == badgeNumberMutedRow) {
            SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount);
            SharedPreferences.Editor editor = preferences.edit();
            enabled = getNotificationsController().showBadgeMuted;
            getNotificationsController().showBadgeMuted = !enabled;
            editor.putBoolean("badgeNumberMuted", getNotificationsController().showBadgeMuted);
            editor.commit();
            getNotificationsController().updateBadge();
            getMessagesStorage().updateMutedDialogsFiltersCounters();
        } else if (position == badgeNumberMessagesRow) {
            SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount);
            SharedPreferences.Editor editor = preferences.edit();
            enabled = getNotificationsController().showBadgeMessages;
            getNotificationsController().showBadgeMessages = !enabled;
            editor.putBoolean("badgeNumberMessages", getNotificationsController().showBadgeMessages);
            editor.commit();
            getNotificationsController().updateBadge();
        } else if (position == notificationsServiceConnectionRow) {
            SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount);
            enabled = preferences.getBoolean("pushConnection", getMessagesController().backgroundConnection);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putBoolean("pushConnection", !enabled);
            enabled = preferences.getBoolean("pushService", getMessagesController().keepAliveService);
            editor.putBoolean("pushService", !enabled);
            editor.commit();
            if (!enabled) {
                ConnectionsManager.getInstance(currentAccount).setPushConnectionEnabled(true);
            } else {
                ConnectionsManager.getInstance(currentAccount).setPushConnectionEnabled(false);
            }
            ApplicationLoader.startPushService();
        } else if (position == accountsAllRow) {
            SharedPreferences preferences = MessagesController.getGlobalNotificationsSettings();
            enabled = preferences.getBoolean("AllAccounts", true);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putBoolean("AllAccounts", !enabled);
            editor.commit();
            SharedConfig.showNotificationsForAllAccounts = !enabled;
            for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
                if (SharedConfig.showNotificationsForAllAccounts) {
                    NotificationsController.getInstance(a).showNotifications();
                } else {
                    if (a == currentAccount) {
                        NotificationsController.getInstance(a).showNotifications();
                    } else {
                        NotificationsController.getInstance(a).hideNotifications();
                    }
                }
            }
        } else if (position == callsVibrateRow) {
            if (getParentActivity() == null) {
                return;
            }
            String key = null;
            if (position == callsVibrateRow) {
                key = "vibrate_calls";
            }
            showDialog(AlertsCreator.createVibrationSelectDialog(getParentActivity(), 0, key, () -> adapter.notifyItemChanged(position)));
        } else if (position == repeatRow) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
            builder.setTitle(LocaleController.getString("RepeatNotifications", R.string.RepeatNotifications));
            builder.setItems(new CharSequence[] { LocaleController.getString("RepeatDisabled", R.string.RepeatDisabled), LocaleController.formatPluralString("Minutes", 5), LocaleController.formatPluralString("Minutes", 10), LocaleController.formatPluralString("Minutes", 30), LocaleController.formatPluralString("Hours", 1), LocaleController.formatPluralString("Hours", 2), LocaleController.formatPluralString("Hours", 4) }, (dialog, which) -> {
                int minutes = 0;
                if (which == 1) {
                    minutes = 5;
                } else if (which == 2) {
                    minutes = 10;
                } else if (which == 3) {
                    minutes = 30;
                } else if (which == 4) {
                    minutes = 60;
                } else if (which == 5) {
                    minutes = 60 * 2;
                } else if (which == 6) {
                    minutes = 60 * 4;
                }
                SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount);
                preferences.edit().putInt("repeat_messages", minutes).commit();
                adapter.notifyItemChanged(position);
            });
            builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
            showDialog(builder.create());
        }
        if (view instanceof TextCheckCell) {
            ((TextCheckCell) view).setChecked(!enabled);
        }
    });
    return fragmentView;
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) ThemeDescription(org.telegram.ui.ActionBar.ThemeDescription) Ringtone(android.media.Ringtone) Uri(android.net.Uri) FrameLayout(android.widget.FrameLayout) AndroidUtilities(org.telegram.messenger.AndroidUtilities) ShadowSectionCell(org.telegram.ui.Cells.ShadowSectionCell) ApplicationLoader(org.telegram.messenger.ApplicationLoader) Map(java.util.Map) NotificationsCheckCell(org.telegram.ui.Cells.NotificationsCheckCell) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) NotificationsController(org.telegram.messenger.NotificationsController) Utilities(org.telegram.messenger.Utilities) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) ConnectionsManager(org.telegram.tgnet.ConnectionsManager) ViewGroup(android.view.ViewGroup) NotificationCenter(org.telegram.messenger.NotificationCenter) UserConfig(org.telegram.messenger.UserConfig) TextView(android.widget.TextView) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) LongSparseArray(android.util.LongSparseArray) Context(android.content.Context) Theme(org.telegram.ui.ActionBar.Theme) Intent(android.content.Intent) LocaleController(org.telegram.messenger.LocaleController) HeaderCell(org.telegram.ui.Cells.HeaderCell) AlertsCreator(org.telegram.ui.Components.AlertsCreator) TextInfoPrivacyCell(org.telegram.ui.Cells.TextInfoPrivacyCell) ArrayList(java.util.ArrayList) TextDetailSettingsCell(org.telegram.ui.Cells.TextDetailSettingsCell) TLRPC(org.telegram.tgnet.TLRPC) Toast(android.widget.Toast) ActionBar(org.telegram.ui.ActionBar.ActionBar) Settings(android.provider.Settings) SharedConfig(org.telegram.messenger.SharedConfig) Build(android.os.Build) DialogInterface(android.content.DialogInterface) TextSettingsCell(org.telegram.ui.Cells.TextSettingsCell) DialogObject(org.telegram.messenger.DialogObject) R(org.telegram.messenger.R) TextUtils(android.text.TextUtils) LayoutHelper(org.telegram.ui.Components.LayoutHelper) FileLog(org.telegram.messenger.FileLog) MessagesController(org.telegram.messenger.MessagesController) SharedPreferences(android.content.SharedPreferences) MessagesStorage(org.telegram.messenger.MessagesStorage) RingtoneManager(android.media.RingtoneManager) TextCheckCell(org.telegram.ui.Cells.TextCheckCell) Activity(android.app.Activity) ChatObject(org.telegram.messenger.ChatObject) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) RecyclerListView(org.telegram.ui.Components.RecyclerListView) TextCheckCell(org.telegram.ui.Cells.TextCheckCell) RecyclerListView(org.telegram.ui.Components.RecyclerListView) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) Uri(android.net.Uri) TLRPC(org.telegram.tgnet.TLRPC) Toast(android.widget.Toast) TextView(android.widget.TextView) ActionBar(org.telegram.ui.ActionBar.ActionBar) SharedPreferences(android.content.SharedPreferences) Intent(android.content.Intent) NotificationsCheckCell(org.telegram.ui.Cells.NotificationsCheckCell) FrameLayout(android.widget.FrameLayout)

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