Search in sources :

Example 1 with AvatarDrawable

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

the class SharingLiveLocationCell method setDialog.

public void setDialog(MessageObject messageObject, Location userLocation, boolean userLocationDenied) {
    long fromId = messageObject.getFromChatId();
    if (messageObject.isForwarded()) {
        fromId = MessageObject.getPeerId(messageObject.messageOwner.fwd_from.from_id);
    }
    currentAccount = messageObject.currentAccount;
    String address = null;
    String name;
    if (!TextUtils.isEmpty(messageObject.messageOwner.media.address)) {
        address = messageObject.messageOwner.media.address;
    }
    if (!TextUtils.isEmpty(messageObject.messageOwner.media.title)) {
        name = messageObject.messageOwner.media.title;
        Drawable drawable = getResources().getDrawable(R.drawable.pin);
        drawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_location_sendLocationIcon), PorterDuff.Mode.MULTIPLY));
        int color = getThemedColor(Theme.key_location_placeLocationBackground);
        Drawable circle = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(42), color, color);
        CombinedDrawable combinedDrawable = new CombinedDrawable(circle, drawable);
        combinedDrawable.setCustomSize(AndroidUtilities.dp(42), AndroidUtilities.dp(42));
        combinedDrawable.setIconSize(AndroidUtilities.dp(24), AndroidUtilities.dp(24));
        avatarImageView.setImageDrawable(combinedDrawable);
    } else {
        name = "";
        avatarDrawable = null;
        if (fromId > 0) {
            TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(fromId);
            if (user != null) {
                avatarDrawable = new AvatarDrawable(user);
                name = UserObject.getUserName(user);
                avatarImageView.setForUserOrChat(user, avatarDrawable);
            }
        } else {
            TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-fromId);
            if (chat != null) {
                avatarDrawable = new AvatarDrawable(chat);
                name = chat.title;
                avatarImageView.setForUserOrChat(chat, avatarDrawable);
            }
        }
    }
    nameTextView.setText(name);
    location.setLatitude(messageObject.messageOwner.media.geo.lat);
    location.setLongitude(messageObject.messageOwner.media.geo._long);
    if (userLocation != null) {
        float distance = location.distanceTo(userLocation);
        if (address != null) {
            distanceTextView.setText(String.format("%s - %s", address, LocaleController.formatDistance(distance, 0)));
        } else {
            distanceTextView.setText(LocaleController.formatDistance(distance, 0));
        }
    } else {
        if (address != null) {
            distanceTextView.setText(address);
        } else if (!userLocationDenied) {
            distanceTextView.setText(LocaleController.getString("Loading", R.string.Loading));
        } else {
            distanceTextView.setText("");
        }
    }
}
Also used : CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) Drawable(android.graphics.drawable.Drawable) AvatarDrawable(org.telegram.ui.Components.AvatarDrawable) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) AvatarDrawable(org.telegram.ui.Components.AvatarDrawable) GeoPoint(org.osmdroid.util.GeoPoint) TLRPC(org.telegram.tgnet.TLRPC)

Example 2 with AvatarDrawable

use of org.telegram.ui.Components.AvatarDrawable 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 3 with AvatarDrawable

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

the class LocationActivity method createUserBitmap.

private Bitmap createUserBitmap(LiveLocation liveLocation) {
    Bitmap result = null;
    try {
        TLRPC.FileLocation photo = null;
        if (liveLocation.user != null && liveLocation.user.photo != null) {
            photo = liveLocation.user.photo.photo_small;
        } else if (liveLocation.chat != null && liveLocation.chat.photo != null) {
            photo = liveLocation.chat.photo.photo_small;
        }
        result = Bitmap.createBitmap(AndroidUtilities.dp(62), AndroidUtilities.dp(85), Bitmap.Config.ARGB_8888);
        result.eraseColor(Color.TRANSPARENT);
        Canvas canvas = new Canvas(result);
        Drawable drawable = ApplicationLoader.applicationContext.getResources().getDrawable(R.drawable.map_pin_photo);
        drawable.setBounds(0, 0, AndroidUtilities.dp(62), AndroidUtilities.dp(85));
        drawable.draw(canvas);
        Paint roundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        RectF bitmapRect = new RectF();
        canvas.save();
        if (photo != null) {
            File path = FileLoader.getPathToAttach(photo, true);
            Bitmap bitmap = BitmapFactory.decodeFile(path.toString());
            if (bitmap != null) {
                BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
                Matrix matrix = new Matrix();
                float scale = AndroidUtilities.dp(50) / (float) bitmap.getWidth();
                matrix.postTranslate(AndroidUtilities.dp(6), AndroidUtilities.dp(6));
                matrix.postScale(scale, scale);
                roundPaint.setShader(shader);
                shader.setLocalMatrix(matrix);
                bitmapRect.set(AndroidUtilities.dp(6), AndroidUtilities.dp(6), AndroidUtilities.dp(50 + 6), AndroidUtilities.dp(50 + 6));
                canvas.drawRoundRect(bitmapRect, AndroidUtilities.dp(25), AndroidUtilities.dp(25), roundPaint);
            }
        } else {
            AvatarDrawable avatarDrawable = new AvatarDrawable();
            if (liveLocation.user != null) {
                avatarDrawable.setInfo(liveLocation.user);
            } else if (liveLocation.chat != null) {
                avatarDrawable.setInfo(liveLocation.chat);
            }
            canvas.translate(AndroidUtilities.dp(6), AndroidUtilities.dp(6));
            avatarDrawable.setBounds(0, 0, AndroidUtilities.dp(50), AndroidUtilities.dp(50));
            avatarDrawable.draw(canvas);
        }
        canvas.restore();
        try {
            canvas.setBitmap(null);
        } catch (Exception e) {
        // don't promt, this will crash on 2.x
        }
    } catch (Throwable e) {
        FileLog.e(e);
    }
    return result;
}
Also used : 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) Paint(android.graphics.Paint) BitmapShader(android.graphics.BitmapShader) TLRPC(org.telegram.tgnet.TLRPC) RectF(android.graphics.RectF) Bitmap(android.graphics.Bitmap) Matrix(android.graphics.Matrix) File(java.io.File) AvatarDrawable(org.telegram.ui.Components.AvatarDrawable)

Example 4 with AvatarDrawable

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

the class NewContactActivity method createView.

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

        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                finishFragment();
            } else if (id == done_button) {
                if (donePressed) {
                    return;
                }
                if (firstNameField.length() == 0) {
                    Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE);
                    if (v != null) {
                        v.vibrate(200);
                    }
                    AndroidUtilities.shakeView(firstNameField, 2, 0);
                    return;
                }
                if (codeField.length() == 0) {
                    Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE);
                    if (v != null) {
                        v.vibrate(200);
                    }
                    AndroidUtilities.shakeView(codeField, 2, 0);
                    return;
                }
                if (phoneField.length() == 0) {
                    Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE);
                    if (v != null) {
                        v.vibrate(200);
                    }
                    AndroidUtilities.shakeView(phoneField, 2, 0);
                    return;
                }
                donePressed = true;
                showEditDoneProgress(true, true);
                final TLRPC.TL_contacts_importContacts req = new TLRPC.TL_contacts_importContacts();
                final TLRPC.TL_inputPhoneContact inputPhoneContact = new TLRPC.TL_inputPhoneContact();
                inputPhoneContact.first_name = firstNameField.getText().toString();
                inputPhoneContact.last_name = lastNameField.getText().toString();
                inputPhoneContact.phone = "+" + codeField.getText().toString() + phoneField.getText().toString();
                req.contacts.add(inputPhoneContact);
                int reqId = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> {
                    final TLRPC.TL_contacts_importedContacts res = (TLRPC.TL_contacts_importedContacts) response;
                    AndroidUtilities.runOnUIThread(() -> {
                        donePressed = false;
                        if (res != null) {
                            if (!res.users.isEmpty()) {
                                MessagesController.getInstance(currentAccount).putUsers(res.users, false);
                                MessagesController.openChatOrProfileWith(res.users.get(0), null, NewContactActivity.this, 1, true);
                            } else {
                                if (getParentActivity() == null) {
                                    return;
                                }
                                showEditDoneProgress(false, true);
                                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                                builder.setTitle(LocaleController.getString("ContactNotRegisteredTitle", R.string.ContactNotRegisteredTitle));
                                builder.setMessage(LocaleController.formatString("ContactNotRegistered", R.string.ContactNotRegistered, ContactsController.formatName(inputPhoneContact.first_name, inputPhoneContact.last_name)));
                                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                                builder.setPositiveButton(LocaleController.getString("Invite", R.string.Invite), (dialog, which) -> {
                                    try {
                                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", inputPhoneContact.phone, null));
                                        intent.putExtra("sms_body", ContactsController.getInstance(currentAccount).getInviteText(1));
                                        getParentActivity().startActivityForResult(intent, 500);
                                    } catch (Exception e) {
                                        FileLog.e(e);
                                    }
                                });
                                showDialog(builder.create());
                            }
                        } else {
                            showEditDoneProgress(false, true);
                            AlertsCreator.processError(currentAccount, error, NewContactActivity.this, req);
                        }
                    });
                }, ConnectionsManager.RequestFlagFailOnServerErrors);
                ConnectionsManager.getInstance(currentAccount).bindRequestToGuid(reqId, classGuid);
            }
        }
    });
    avatarDrawable = new AvatarDrawable();
    avatarDrawable.setInfo(5, "", "");
    ActionBarMenu menu = actionBar.createMenu();
    editDoneItem = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56));
    editDoneItem.setContentDescription(LocaleController.getString("Done", R.string.Done));
    editDoneItemProgress = new ContextProgressView(context, 1);
    editDoneItem.addView(editDoneItemProgress, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    editDoneItemProgress.setVisibility(View.INVISIBLE);
    fragmentView = new ScrollView(context);
    contentLayout = new LinearLayout(context);
    contentLayout.setPadding(AndroidUtilities.dp(24), 0, AndroidUtilities.dp(24), 0);
    contentLayout.setOrientation(LinearLayout.VERTICAL);
    ((ScrollView) fragmentView).addView(contentLayout, LayoutHelper.createScroll(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP));
    contentLayout.setOnTouchListener((v, event) -> true);
    FrameLayout frameLayout = new FrameLayout(context);
    contentLayout.addView(frameLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 24, 0, 0));
    avatarImage = new BackupImageView(context);
    avatarImage.setImageDrawable(avatarDrawable);
    frameLayout.addView(avatarImage, LayoutHelper.createFrame(60, 60, Gravity.LEFT | Gravity.TOP, 0, 9, 0, 0));
    boolean needInvalidateAvatar = false;
    firstNameField = new EditTextBoldCursor(context);
    firstNameField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
    firstNameField.setHintTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteHintText));
    firstNameField.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    firstNameField.setMaxLines(1);
    firstNameField.setLines(1);
    firstNameField.setSingleLine(true);
    firstNameField.setBackgroundDrawable(Theme.createEditTextDrawable(context, false));
    firstNameField.setGravity(Gravity.LEFT);
    firstNameField.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
    firstNameField.setImeOptions(EditorInfo.IME_ACTION_NEXT);
    firstNameField.setHint(LocaleController.getString("FirstName", R.string.FirstName));
    firstNameField.setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    firstNameField.setCursorSize(AndroidUtilities.dp(20));
    firstNameField.setCursorWidth(1.5f);
    if (initialFirstName != null) {
        firstNameField.setText(initialFirstName);
        initialFirstName = null;
        needInvalidateAvatar = true;
    }
    frameLayout.addView(firstNameField, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 34, Gravity.LEFT | Gravity.TOP, 84, 0, 0, 0));
    firstNameField.setOnEditorActionListener((textView, i, keyEvent) -> {
        if (i == EditorInfo.IME_ACTION_NEXT) {
            lastNameField.requestFocus();
            lastNameField.setSelection(lastNameField.length());
            return true;
        }
        return false;
    });
    firstNameField.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            invalidateAvatar();
        }
    });
    lastNameField = new EditTextBoldCursor(context);
    lastNameField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
    lastNameField.setHintTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteHintText));
    lastNameField.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    lastNameField.setBackgroundDrawable(Theme.createEditTextDrawable(context, false));
    lastNameField.setMaxLines(1);
    lastNameField.setLines(1);
    lastNameField.setSingleLine(true);
    lastNameField.setGravity(Gravity.LEFT);
    lastNameField.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
    lastNameField.setImeOptions(EditorInfo.IME_ACTION_NEXT);
    lastNameField.setHint(LocaleController.getString("LastName", R.string.LastName));
    lastNameField.setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    lastNameField.setCursorSize(AndroidUtilities.dp(20));
    lastNameField.setCursorWidth(1.5f);
    if (initialLastName != null) {
        lastNameField.setText(initialLastName);
        initialLastName = null;
        needInvalidateAvatar = true;
    }
    frameLayout.addView(lastNameField, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 34, Gravity.LEFT | Gravity.TOP, 84, 44, 0, 0));
    lastNameField.setOnEditorActionListener((textView, i, keyEvent) -> {
        if (i == EditorInfo.IME_ACTION_NEXT) {
            phoneField.requestFocus();
            phoneField.setSelection(phoneField.length());
            return true;
        }
        return false;
    });
    lastNameField.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            invalidateAvatar();
        }
    });
    if (needInvalidateAvatar) {
        invalidateAvatar();
    }
    countryButton = new TextView(context);
    countryButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
    countryButton.setPadding(0, AndroidUtilities.dp(4), 0, AndroidUtilities.dp(4));
    countryButton.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    countryButton.setMaxLines(1);
    countryButton.setSingleLine(true);
    countryButton.setEllipsize(TextUtils.TruncateAt.END);
    countryButton.setGravity(Gravity.LEFT | Gravity.CENTER_HORIZONTAL);
    countryButton.setBackground(Theme.getSelectorDrawable(true));
    contentLayout.addView(countryButton, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 36, 0, 24, 0, 14));
    countryButton.setOnClickListener(view -> {
        CountrySelectActivity fragment = new CountrySelectActivity(true);
        fragment.setCountrySelectActivityDelegate((country) -> {
            selectCountry(country.name);
            phoneField.requestFocus();
            phoneField.setSelection(phoneField.length());
        });
        presentFragment(fragment);
    });
    lineView = new View(context);
    lineView.setPadding(AndroidUtilities.dp(8), 0, AndroidUtilities.dp(8), 0);
    lineView.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayLine));
    contentLayout.addView(lineView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 1, 0, -17.5f, 0, 0));
    LinearLayout linearLayout2 = new LinearLayout(context);
    linearLayout2.setOrientation(HORIZONTAL);
    contentLayout.addView(linearLayout2, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 20, 0, 0));
    textView = new TextView(context);
    textView.setText("+");
    textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
    textView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
    linearLayout2.addView(textView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT));
    codeField = new EditTextBoldCursor(context);
    codeField.setInputType(InputType.TYPE_CLASS_PHONE);
    codeField.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    codeField.setBackgroundDrawable(Theme.createEditTextDrawable(context, false));
    codeField.setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    codeField.setCursorSize(AndroidUtilities.dp(20));
    codeField.setCursorWidth(1.5f);
    codeField.setPadding(AndroidUtilities.dp(10), 0, 0, 0);
    codeField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
    codeField.setMaxLines(1);
    codeField.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
    codeField.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
    linearLayout2.addView(codeField, LayoutHelper.createLinear(55, 36, -9, 0, 16, 0));
    codeField.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (ignoreOnTextChange) {
                return;
            }
            ignoreOnTextChange = true;
            String text = PhoneFormat.stripExceptNumbers(codeField.getText().toString());
            codeField.setText(text);
            if (text.length() == 0) {
                countryButton.setText(LocaleController.getString("ChooseCountry", R.string.ChooseCountry));
                phoneField.setHintText(null);
                countryState = 1;
            } else {
                String country;
                boolean ok = false;
                String textToSet = null;
                if (text.length() > 4) {
                    ignoreOnTextChange = true;
                    for (int a = 4; a >= 1; a--) {
                        String sub = text.substring(0, a);
                        country = codesMap.get(sub);
                        if (country != null) {
                            ok = true;
                            textToSet = text.substring(a) + phoneField.getText().toString();
                            codeField.setText(text = sub);
                            break;
                        }
                    }
                    if (!ok) {
                        ignoreOnTextChange = true;
                        textToSet = text.substring(1) + phoneField.getText().toString();
                        codeField.setText(text = text.substring(0, 1));
                    }
                }
                country = codesMap.get(text);
                if (country != null) {
                    int index = countriesArray.indexOf(country);
                    if (index != -1) {
                        ignoreSelection = true;
                        countryButton.setText(countriesArray.get(index));
                        String hint = phoneFormatMap.get(text);
                        phoneField.setHintText(hint != null ? hint.replace('X', '–') : null);
                        countryState = 0;
                    } else {
                        countryButton.setText(LocaleController.getString("WrongCountry", R.string.WrongCountry));
                        phoneField.setHintText(null);
                        countryState = 2;
                    }
                } else {
                    countryButton.setText(LocaleController.getString("WrongCountry", R.string.WrongCountry));
                    phoneField.setHintText(null);
                    countryState = 2;
                }
                if (!ok) {
                    codeField.setSelection(codeField.getText().length());
                }
                if (textToSet != null) {
                    if (initialPhoneNumber == null) {
                        phoneField.requestFocus();
                    }
                    phoneField.setText(textToSet);
                    phoneField.setSelection(phoneField.length());
                }
            }
            ignoreOnTextChange = false;
        }
    });
    codeField.setOnEditorActionListener((textView, i, keyEvent) -> {
        if (i == EditorInfo.IME_ACTION_NEXT) {
            phoneField.requestFocus();
            phoneField.setSelection(phoneField.length());
            return true;
        }
        return false;
    });
    phoneField = new HintEditText(context);
    phoneField.setInputType(InputType.TYPE_CLASS_PHONE);
    phoneField.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    phoneField.setHintTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteHintText));
    phoneField.setBackgroundDrawable(Theme.createEditTextDrawable(context, false));
    phoneField.setPadding(0, 0, 0, 0);
    phoneField.setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    phoneField.setCursorSize(AndroidUtilities.dp(20));
    phoneField.setCursorWidth(1.5f);
    phoneField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
    phoneField.setMaxLines(1);
    phoneField.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
    phoneField.setImeOptions(EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
    linearLayout2.addView(phoneField, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 36));
    phoneField.addTextChangedListener(new TextWatcher() {

        private int characterAction = -1;

        private int actionPosition;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if (count == 0 && after == 1) {
                characterAction = 1;
            } else if (count == 1 && after == 0) {
                if (s.charAt(start) == ' ' && start > 0) {
                    characterAction = 3;
                    actionPosition = start - 1;
                } else {
                    characterAction = 2;
                }
            } else {
                characterAction = -1;
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (ignoreOnPhoneChange) {
                return;
            }
            int start = phoneField.getSelectionStart();
            String phoneChars = "0123456789";
            String str = phoneField.getText().toString();
            if (characterAction == 3) {
                str = str.substring(0, actionPosition) + str.substring(actionPosition + 1);
                start--;
            }
            StringBuilder builder = new StringBuilder(str.length());
            for (int a = 0; a < str.length(); a++) {
                String ch = str.substring(a, a + 1);
                if (phoneChars.contains(ch)) {
                    builder.append(ch);
                }
            }
            ignoreOnPhoneChange = true;
            String hint = phoneField.getHintText();
            if (hint != null) {
                for (int a = 0; a < builder.length(); a++) {
                    if (a < hint.length()) {
                        if (hint.charAt(a) == ' ') {
                            builder.insert(a, ' ');
                            a++;
                            if (start == a && characterAction != 2 && characterAction != 3) {
                                start++;
                            }
                        }
                    } else {
                        builder.insert(a, ' ');
                        if (start == a + 1 && characterAction != 2 && characterAction != 3) {
                            start++;
                        }
                        break;
                    }
                }
            }
            phoneField.setText(builder);
            if (start >= 0) {
                phoneField.setSelection(Math.min(start, phoneField.length()));
            }
            phoneField.onTextChange();
            ignoreOnPhoneChange = false;
        }
    });
    phoneField.setOnEditorActionListener((textView, i, keyEvent) -> {
        if (i == EditorInfo.IME_ACTION_DONE) {
            editDoneItem.performClick();
            return true;
        }
        return false;
    });
    phoneField.setOnKeyListener((v, keyCode, event) -> {
        if (keyCode == KeyEvent.KEYCODE_DEL && phoneField.length() == 0) {
            codeField.requestFocus();
            codeField.setSelection(codeField.length());
            codeField.dispatchKeyEvent(event);
            return true;
        }
        return false;
    });
    HashMap<String, String> languageMap = new HashMap<>();
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(context.getResources().getAssets().open("countries.txt")));
        String line;
        while ((line = reader.readLine()) != null) {
            String[] args = line.split(";");
            countriesArray.add(0, args[2]);
            countriesMap.put(args[2], args[0]);
            codesMap.put(args[0], args[2]);
            if (args.length > 3) {
                phoneFormatMap.put(args[0], args[3]);
            }
            languageMap.put(args[1], args[2]);
        }
        reader.close();
    } catch (Exception e) {
        FileLog.e(e);
    }
    Collections.sort(countriesArray, String::compareTo);
    if (!TextUtils.isEmpty(initialPhoneNumber)) {
        TLRPC.User user = getUserConfig().getCurrentUser();
        if (initialPhoneNumber.startsWith("+")) {
            codeField.setText(initialPhoneNumber.substring(1));
        } else if (initialPhoneNumberWithCountryCode || user == null || TextUtils.isEmpty(user.phone)) {
            codeField.setText(initialPhoneNumber);
        } else {
            String phone = user.phone;
            for (int a = 4; a >= 1; a--) {
                String sub = phone.substring(0, a);
                String country = codesMap.get(sub);
                if (country != null) {
                    codeField.setText(sub);
                    break;
                }
            }
            phoneField.setText(initialPhoneNumber);
        }
        initialPhoneNumber = null;
    } else {
        String country = null;
        try {
            TelephonyManager telephonyManager = (TelephonyManager) ApplicationLoader.applicationContext.getSystemService(Context.TELEPHONY_SERVICE);
            if (telephonyManager != null) {
                country = telephonyManager.getSimCountryIso().toUpperCase();
            }
        } catch (Exception e) {
            FileLog.e(e);
        }
        if (country != null) {
            String countryName = languageMap.get(country);
            if (countryName != null) {
                int index = countriesArray.indexOf(countryName);
                if (index != -1) {
                    codeField.setText(countriesMap.get(countryName));
                    countryState = 0;
                }
            }
        }
        if (codeField.length() == 0) {
            countryButton.setText(LocaleController.getString("ChooseCountry", R.string.ChooseCountry));
            phoneField.setHintText(null);
            countryState = 1;
        }
    }
    return fragmentView;
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) HashMap(java.util.HashMap) ContextProgressView(org.telegram.ui.Components.ContextProgressView) TLRPC(org.telegram.tgnet.TLRPC) TelephonyManager(android.telephony.TelephonyManager) BackupImageView(org.telegram.ui.Components.BackupImageView) TextWatcher(android.text.TextWatcher) Editable(android.text.Editable) TextView(android.widget.TextView) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) ActionBar(org.telegram.ui.ActionBar.ActionBar) InputStreamReader(java.io.InputStreamReader) Intent(android.content.Intent) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) View(android.view.View) AdapterView(android.widget.AdapterView) ContextProgressView(org.telegram.ui.Components.ContextProgressView) TextView(android.widget.TextView) BackupImageView(org.telegram.ui.Components.BackupImageView) ScrollView(android.widget.ScrollView) HintEditText(org.telegram.ui.Components.HintEditText) ScrollView(android.widget.ScrollView) FrameLayout(android.widget.FrameLayout) BufferedReader(java.io.BufferedReader) Vibrator(android.os.Vibrator) AvatarDrawable(org.telegram.ui.Components.AvatarDrawable) LinearLayout(android.widget.LinearLayout)

Example 5 with AvatarDrawable

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

the class MemberRequestsDelegate method hideChatJoinRequest.

private void hideChatJoinRequest(TLRPC.TL_chatInviteImporter importer, boolean isApproved) {
    TLRPC.User user = users.get(importer.user_id);
    if (user == null) {
        return;
    }
    TLRPC.TL_messages_hideChatJoinRequest req = new TLRPC.TL_messages_hideChatJoinRequest();
    req.approved = isApproved;
    req.peer = MessagesController.getInstance(currentAccount).getInputPeer(-chatId);
    req.user_id = MessagesController.getInstance(currentAccount).getInputUser(user);
    ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> {
        if (error == null) {
            TLRPC.TL_updates updates = (TLRPC.TL_updates) response;
            MessagesController.getInstance(currentAccount).processUpdates(updates, false);
        }
        AndroidUtilities.runOnUIThread(() -> {
            if (error == null) {
                TLRPC.TL_updates updates = (TLRPC.TL_updates) response;
                if (!updates.chats.isEmpty()) {
                    TLRPC.Chat chat = updates.chats.get(0);
                    MessagesController.getInstance(currentAccount).loadFullChat(chat.id, 0, true);
                }
                for (int i = 0; i < allImporters.size(); ++i) {
                    if (allImporters.get(i).user_id == importer.user_id) {
                        allImporters.remove(i);
                        break;
                    }
                }
                adapter.removeItem(importer);
                onImportersChanged(query, false, true);
                if (isApproved) {
                    Bulletin.MultiLineLayout layout = new Bulletin.MultiLineLayout(fragment.getParentActivity(), fragment.getResourceProvider());
                    layout.imageView.setRoundRadius(AndroidUtilities.dp(15));
                    layout.imageView.setForUserOrChat(user, new AvatarDrawable(user));
                    String userName = UserObject.getFirstName(user);
                    String message = isChannel ? LocaleController.formatString("HasBeenAddedToChannel", R.string.HasBeenAddedToChannel, userName) : LocaleController.formatString("HasBeenAddedToGroup", R.string.HasBeenAddedToGroup, userName);
                    SpannableStringBuilder stringBuilder = new SpannableStringBuilder(message);
                    int start = message.indexOf(userName);
                    stringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")), start, start + userName.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                    layout.textView.setText(stringBuilder);
                    if (allImporters.isEmpty()) {
                        Bulletin.make(fragment, layout, Bulletin.DURATION_LONG).show();
                    } else {
                        Bulletin.make(layoutContainer, layout, Bulletin.DURATION_LONG).show();
                    }
                }
                ActionBarMenu menu = fragment.getActionBar().createMenu();
                if (TextUtils.isEmpty(query) && showSearchMenu) {
                    menu.getItem(MemberRequestsActivity.searchMenuItem).setVisibility(allImporters.isEmpty() ? GONE : VISIBLE);
                }
            } else {
                AlertsCreator.processError(currentAccount, error, fragment, req);
            }
        });
    });
}
Also used : ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) TLRPC(org.telegram.tgnet.TLRPC) SuppressLint(android.annotation.SuppressLint) Bulletin(org.telegram.ui.Components.Bulletin) AvatarDrawable(org.telegram.ui.Components.AvatarDrawable) SpannableStringBuilder(android.text.SpannableStringBuilder) TypefaceSpan(org.telegram.ui.Components.TypefaceSpan)

Aggregations

AvatarDrawable (org.telegram.ui.Components.AvatarDrawable)28 TLRPC (org.telegram.tgnet.TLRPC)22 Paint (android.graphics.Paint)19 BackupImageView (org.telegram.ui.Components.BackupImageView)15 Canvas (android.graphics.Canvas)14 View (android.view.View)14 TextView (android.widget.TextView)13 Drawable (android.graphics.drawable.Drawable)12 FrameLayout (android.widget.FrameLayout)12 ImageView (android.widget.ImageView)12 Intent (android.content.Intent)11 Bitmap (android.graphics.Bitmap)11 ArrayList (java.util.ArrayList)10 ViewGroup (android.view.ViewGroup)9 ActionBar (org.telegram.ui.ActionBar.ActionBar)9 CombinedDrawable (org.telegram.ui.Components.CombinedDrawable)9 LinearLayout (android.widget.LinearLayout)8 RecyclerView (androidx.recyclerview.widget.RecyclerView)8 AndroidUtilities (org.telegram.messenger.AndroidUtilities)8 Animator (android.animation.Animator)7