Search in sources :

Example 16 with BaseFragment

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

the class ThemeEditorView method show.

public void show(Activity activity, final Theme.ThemeInfo theme) {
    if (Instance != null) {
        Instance.destroy();
    }
    hidden = false;
    themeInfo = theme;
    windowView = new FrameLayout(activity) {

        private float startX;

        private float startY;

        private boolean dragging;

        @Override
        public boolean onInterceptTouchEvent(MotionEvent event) {
            return true;
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            float x = event.getRawX();
            float y = event.getRawY();
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                startX = x;
                startY = y;
            } else if (event.getAction() == MotionEvent.ACTION_MOVE && !dragging) {
                if (Math.abs(startX - x) >= AndroidUtilities.getPixelsInCM(0.3f, true) || Math.abs(startY - y) >= AndroidUtilities.getPixelsInCM(0.3f, false)) {
                    dragging = true;
                    startX = x;
                    startY = y;
                }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                if (!dragging) {
                    if (editorAlert == null) {
                        LaunchActivity launchActivity = (LaunchActivity) parentActivity;
                        ActionBarLayout actionBarLayout = null;
                        if (AndroidUtilities.isTablet()) {
                            actionBarLayout = launchActivity.getLayersActionBarLayout();
                            if (actionBarLayout != null && actionBarLayout.fragmentsStack.isEmpty()) {
                                actionBarLayout = null;
                            }
                            if (actionBarLayout == null) {
                                actionBarLayout = launchActivity.getRightActionBarLayout();
                                if (actionBarLayout != null && actionBarLayout.fragmentsStack.isEmpty()) {
                                    actionBarLayout = null;
                                }
                            }
                        }
                        if (actionBarLayout == null) {
                            actionBarLayout = launchActivity.getActionBarLayout();
                        }
                        if (actionBarLayout != null) {
                            BaseFragment fragment;
                            if (!actionBarLayout.fragmentsStack.isEmpty()) {
                                fragment = actionBarLayout.fragmentsStack.get(actionBarLayout.fragmentsStack.size() - 1);
                            } else {
                                fragment = null;
                            }
                            if (fragment != null) {
                                ArrayList<ThemeDescription> items = fragment.getThemeDescriptions();
                                if (items != null) {
                                    editorAlert = new EditorAlert(parentActivity, items);
                                    editorAlert.setOnDismissListener(dialog -> {
                                    });
                                    editorAlert.setOnDismissListener(dialog -> {
                                        editorAlert = null;
                                        show();
                                    });
                                    editorAlert.show();
                                    hide();
                                }
                            }
                        }
                    }
                }
            }
            if (dragging) {
                if (event.getAction() == MotionEvent.ACTION_MOVE) {
                    float dx = (x - startX);
                    float dy = (y - startY);
                    windowLayoutParams.x += dx;
                    windowLayoutParams.y += dy;
                    int maxDiff = editorWidth / 2;
                    if (windowLayoutParams.x < -maxDiff) {
                        windowLayoutParams.x = -maxDiff;
                    } else if (windowLayoutParams.x > AndroidUtilities.displaySize.x - windowLayoutParams.width + maxDiff) {
                        windowLayoutParams.x = AndroidUtilities.displaySize.x - windowLayoutParams.width + maxDiff;
                    }
                    float alpha = 1.0f;
                    if (windowLayoutParams.x < 0) {
                        alpha = 1.0f + windowLayoutParams.x / (float) maxDiff * 0.5f;
                    } else if (windowLayoutParams.x > AndroidUtilities.displaySize.x - windowLayoutParams.width) {
                        alpha = 1.0f - (windowLayoutParams.x - AndroidUtilities.displaySize.x + windowLayoutParams.width) / (float) maxDiff * 0.5f;
                    }
                    if (windowView.getAlpha() != alpha) {
                        windowView.setAlpha(alpha);
                    }
                    maxDiff = 0;
                    if (windowLayoutParams.y < -maxDiff) {
                        windowLayoutParams.y = -maxDiff;
                    } else if (windowLayoutParams.y > AndroidUtilities.displaySize.y - windowLayoutParams.height + maxDiff) {
                        windowLayoutParams.y = AndroidUtilities.displaySize.y - windowLayoutParams.height + maxDiff;
                    }
                    windowManager.updateViewLayout(windowView, windowLayoutParams);
                    startX = x;
                    startY = y;
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    dragging = false;
                    animateToBoundsMaybe();
                }
            }
            return true;
        }
    };
    windowManager = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
    preferences = ApplicationLoader.applicationContext.getSharedPreferences("themeconfig", Context.MODE_PRIVATE);
    int sidex = preferences.getInt("sidex", 1);
    int sidey = preferences.getInt("sidey", 0);
    float px = preferences.getFloat("px", 0);
    float py = preferences.getFloat("py", 0);
    try {
        windowLayoutParams = new WindowManager.LayoutParams();
        windowLayoutParams.width = editorWidth;
        windowLayoutParams.height = editorHeight;
        windowLayoutParams.x = getSideCoord(true, sidex, px, editorWidth);
        windowLayoutParams.y = getSideCoord(false, sidey, py, editorHeight);
        windowLayoutParams.format = PixelFormat.TRANSLUCENT;
        windowLayoutParams.gravity = Gravity.TOP | Gravity.LEFT;
        windowLayoutParams.type = WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
        windowLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
        windowManager.addView(windowView, windowLayoutParams);
    } catch (Exception e) {
        FileLog.e(e);
        return;
    }
    wallpaperUpdater = new WallpaperUpdater(activity, null, new WallpaperUpdater.WallpaperUpdaterDelegate() {

        @Override
        public void didSelectWallpaper(File file, Bitmap bitmap, boolean gallery) {
            Theme.setThemeWallpaper(themeInfo, bitmap, file);
        }

        @Override
        public void needOpenColorPicker() {
            for (int a = 0; a < currentThemeDesription.size(); a++) {
                ThemeDescription description = currentThemeDesription.get(a);
                description.startEditing();
                if (a == 0) {
                    editorAlert.colorPicker.setColor(description.getCurrentColor());
                }
            }
            editorAlert.setColorPickerVisible(true);
        }
    });
    Instance = this;
    parentActivity = activity;
    showWithAnimation();
}
Also used : ThemeDescription(org.telegram.ui.ActionBar.ThemeDescription) LinearLayout(android.widget.LinearLayout) WindowManager(android.view.WindowManager) FrameLayout(android.widget.FrameLayout) ImageView(android.widget.ImageView) AndroidUtilities(org.telegram.messenger.AndroidUtilities) Animator(android.animation.Animator) Drawable(android.graphics.drawable.Drawable) RadialGradient(android.graphics.RadialGradient) ComposeShader(android.graphics.ComposeShader) Keep(androidx.annotation.Keep) ApplicationLoader(org.telegram.messenger.ApplicationLoader) Shader(android.graphics.Shader) View(android.view.View) Canvas(android.graphics.Canvas) RecyclerView(androidx.recyclerview.widget.RecyclerView) ForegroundColorSpan(android.text.style.ForegroundColorSpan) RectF(android.graphics.RectF) Utilities(org.telegram.messenger.Utilities) ObjectAnimator(android.animation.ObjectAnimator) InputType(android.text.InputType) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) PorterDuff(android.graphics.PorterDuff) ViewGroup(android.view.ViewGroup) TextView(android.widget.TextView) LaunchActivity(org.telegram.ui.LaunchActivity) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) Paint(android.graphics.Paint) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) InputFilter(android.text.InputFilter) EditorInfo(android.view.inputmethod.EditorInfo) DecelerateInterpolator(android.view.animation.DecelerateInterpolator) TextWatcher(android.text.TextWatcher) Context(android.content.Context) Spanned(android.text.Spanned) KeyEvent(android.view.KeyEvent) Theme(org.telegram.ui.ActionBar.Theme) Intent(android.content.Intent) LocaleController(org.telegram.messenger.LocaleController) HashMap(java.util.HashMap) ActionBarLayout(org.telegram.ui.ActionBar.ActionBarLayout) PixelFormat(android.graphics.PixelFormat) Editable(android.text.Editable) ArrayList(java.util.ArrayList) SuppressLint(android.annotation.SuppressLint) SpannableStringBuilder(android.text.SpannableStringBuilder) MotionEvent(android.view.MotionEvent) ActionBar(org.telegram.ui.ActionBar.ActionBar) AnimatorSet(android.animation.AnimatorSet) SweepGradient(android.graphics.SweepGradient) Build(android.os.Build) TextColorThemeCell(org.telegram.ui.Cells.TextColorThemeCell) LinearGradient(android.graphics.LinearGradient) R(org.telegram.messenger.R) BottomSheet(org.telegram.ui.ActionBar.BottomSheet) TextUtils(android.text.TextUtils) FileLog(org.telegram.messenger.FileLog) File(java.io.File) Color(android.graphics.Color) Gravity(android.view.Gravity) SharedPreferences(android.content.SharedPreferences) TypedValue(android.util.TypedValue) Bitmap(android.graphics.Bitmap) Activity(android.app.Activity) ArrayList(java.util.ArrayList) ActionBarLayout(org.telegram.ui.ActionBar.ActionBarLayout) ThemeDescription(org.telegram.ui.ActionBar.ThemeDescription) LaunchActivity(org.telegram.ui.LaunchActivity) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) Paint(android.graphics.Paint) SuppressLint(android.annotation.SuppressLint) MotionEvent(android.view.MotionEvent) WindowManager(android.view.WindowManager) Bitmap(android.graphics.Bitmap) FrameLayout(android.widget.FrameLayout) File(java.io.File)

Example 17 with BaseFragment

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

the class GroupCallActivity method inviteUserToCall.

private void inviteUserToCall(long id, boolean shouldAdd) {
    if (call == null) {
        return;
    }
    TLRPC.User user = accountInstance.getMessagesController().getUser(id);
    if (user == null) {
        return;
    }
    final AlertDialog[] progressDialog = new AlertDialog[] { new AlertDialog(getContext(), 3) };
    TLRPC.TL_phone_inviteToGroupCall req = new TLRPC.TL_phone_inviteToGroupCall();
    req.call = call.getInputGroupCall();
    TLRPC.TL_inputUser inputUser = new TLRPC.TL_inputUser();
    inputUser.user_id = user.id;
    inputUser.access_hash = user.access_hash;
    req.users.add(inputUser);
    int requestId = accountInstance.getConnectionsManager().sendRequest(req, (response, error) -> {
        if (response != null) {
            accountInstance.getMessagesController().processUpdates((TLRPC.Updates) response, false);
            AndroidUtilities.runOnUIThread(() -> {
                if (call != null && !delayedGroupCallUpdated) {
                    call.addInvitedUser(id);
                    applyCallParticipantUpdates(true);
                    if (groupVoipInviteAlert != null) {
                        groupVoipInviteAlert.dismiss();
                    }
                    try {
                        progressDialog[0].dismiss();
                    } catch (Throwable ignore) {
                    }
                    progressDialog[0] = null;
                    getUndoView().showWithAction(0, UndoView.ACTION_VOIP_INVITED, user, currentChat, null, null);
                }
            });
        } else {
            AndroidUtilities.runOnUIThread(() -> {
                try {
                    progressDialog[0].dismiss();
                } catch (Throwable ignore) {
                }
                progressDialog[0] = null;
                if (shouldAdd && "USER_NOT_PARTICIPANT".equals(error.text)) {
                    processSelectedOption(null, id, 3);
                } else {
                    BaseFragment fragment = parentActivity.getActionBarLayout().fragmentsStack.get(parentActivity.getActionBarLayout().fragmentsStack.size() - 1);
                    AlertsCreator.processError(currentAccount, error, fragment, req);
                }
            });
        }
    });
    if (requestId != 0) {
        AndroidUtilities.runOnUIThread(() -> {
            if (progressDialog[0] == null) {
                return;
            }
            progressDialog[0].setOnCancelListener(dialog -> accountInstance.getConnectionsManager().cancelRequest(requestId, true));
            progressDialog[0].show();
        }, 500);
    }
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) TLRPC(org.telegram.tgnet.TLRPC) Paint(android.graphics.Paint) SuppressLint(android.annotation.SuppressLint) BaseFragment(org.telegram.ui.ActionBar.BaseFragment)

Example 18 with BaseFragment

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

the class ProfileActivity method createView.

@Override
public View createView(Context context) {
    Theme.createProfileResources(context);
    Theme.createChatResources(context, false);
    searchTransitionOffset = 0;
    searchTransitionProgress = 1f;
    searchMode = false;
    hasOwnBackground = true;
    extraHeight = AndroidUtilities.dp(88f);
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {

        @Override
        public void onItemClick(final int id) {
            if (getParentActivity() == null) {
                return;
            }
            if (id == -1) {
                finishFragment();
            } else if (id == block_contact) {
                TLRPC.User user = getMessagesController().getUser(userId);
                if (user == null) {
                    return;
                }
                if (!isBot || MessagesController.isSupportUser(user)) {
                    if (userBlocked) {
                        getMessagesController().unblockPeer(userId);
                        if (BulletinFactory.canShowBulletin(ProfileActivity.this)) {
                            BulletinFactory.createBanBulletin(ProfileActivity.this, false).show();
                        }
                    } else {
                        if (reportSpam) {
                            AlertsCreator.showBlockReportSpamAlert(ProfileActivity.this, userId, user, null, currentEncryptedChat, false, null, param -> {
                                if (param == 1) {
                                    getNotificationCenter().removeObserver(ProfileActivity.this, NotificationCenter.closeChats);
                                    getNotificationCenter().postNotificationName(NotificationCenter.closeChats);
                                    playProfileAnimation = 0;
                                    finishFragment();
                                } else {
                                    getNotificationCenter().postNotificationName(NotificationCenter.peerSettingsDidLoad, userId);
                                }
                            }, null);
                        } else {
                            AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                            builder.setTitle(LocaleController.getString("BlockUser", R.string.BlockUser));
                            builder.setMessage(AndroidUtilities.replaceTags(LocaleController.formatString("AreYouSureBlockContact2", R.string.AreYouSureBlockContact2, ContactsController.formatName(user.first_name, user.last_name))));
                            builder.setPositiveButton(LocaleController.getString("BlockContact", R.string.BlockContact), (dialogInterface, i) -> {
                                getMessagesController().blockPeer(userId);
                                if (BulletinFactory.canShowBulletin(ProfileActivity.this)) {
                                    BulletinFactory.createBanBulletin(ProfileActivity.this, true).show();
                                }
                            });
                            builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                            AlertDialog dialog = builder.create();
                            showDialog(dialog);
                            TextView button = (TextView) dialog.getButton(DialogInterface.BUTTON_POSITIVE);
                            if (button != null) {
                                button.setTextColor(Theme.getColor(Theme.key_dialogTextRed2));
                            }
                        }
                    }
                } else {
                    if (!userBlocked) {
                        getMessagesController().blockPeer(userId);
                    } else {
                        getMessagesController().unblockPeer(userId);
                        getSendMessagesHelper().sendMessage("/start", userId, null, null, null, false, null, null, null, true, 0, null);
                        finishFragment();
                    }
                }
            } else if (id == add_contact) {
                TLRPC.User user = getMessagesController().getUser(userId);
                Bundle args = new Bundle();
                args.putLong("user_id", user.id);
                args.putBoolean("addContact", true);
                presentFragment(new ContactAddActivity(args));
            } else if (id == share_contact) {
                Bundle args = new Bundle();
                args.putBoolean("onlySelect", true);
                args.putInt("dialogsType", 3);
                args.putString("selectAlertString", LocaleController.getString("SendContactToText", R.string.SendContactToText));
                args.putString("selectAlertStringGroup", LocaleController.getString("SendContactToGroupText", R.string.SendContactToGroupText));
                DialogsActivity fragment = new DialogsActivity(args);
                fragment.setDelegate(ProfileActivity.this);
                presentFragment(fragment);
            } else if (id == edit_contact) {
                Bundle args = new Bundle();
                args.putLong("user_id", userId);
                presentFragment(new ContactAddActivity(args));
            } else if (id == delete_contact) {
                final TLRPC.User user = getMessagesController().getUser(userId);
                if (user == null || getParentActivity() == null) {
                    return;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setTitle(LocaleController.getString("DeleteContact", R.string.DeleteContact));
                builder.setMessage(LocaleController.getString("AreYouSureDeleteContact", R.string.AreYouSureDeleteContact));
                builder.setPositiveButton(LocaleController.getString("Delete", R.string.Delete), (dialogInterface, i) -> {
                    ArrayList<TLRPC.User> arrayList = new ArrayList<>();
                    arrayList.add(user);
                    getContactsController().deleteContact(arrayList, true);
                });
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                AlertDialog dialog = builder.create();
                showDialog(dialog);
                TextView button = (TextView) dialog.getButton(DialogInterface.BUTTON_POSITIVE);
                if (button != null) {
                    button.setTextColor(Theme.getColor(Theme.key_dialogTextRed2));
                }
            } else if (id == leave_group) {
                leaveChatPressed();
            } else if (id == edit_channel) {
                Bundle args = new Bundle();
                args.putLong("chat_id", chatId);
                ChatEditActivity fragment = new ChatEditActivity(args);
                fragment.setInfo(chatInfo);
                presentFragment(fragment);
            } else if (id == invite_to_group) {
                final TLRPC.User user = getMessagesController().getUser(userId);
                if (user == null) {
                    return;
                }
                Bundle args = new Bundle();
                args.putBoolean("onlySelect", true);
                args.putInt("dialogsType", 2);
                args.putString("addToGroupAlertString", LocaleController.formatString("AddToTheGroupAlertText", R.string.AddToTheGroupAlertText, UserObject.getUserName(user), "%1$s"));
                DialogsActivity fragment = new DialogsActivity(args);
                fragment.setDelegate((fragment1, dids, message, param) -> {
                    long did = dids.get(0);
                    Bundle args1 = new Bundle();
                    args1.putBoolean("scrollToTopOnResume", true);
                    args1.putLong("chat_id", -did);
                    if (!getMessagesController().checkCanOpenChat(args1, fragment1)) {
                        return;
                    }
                    getNotificationCenter().removeObserver(ProfileActivity.this, NotificationCenter.closeChats);
                    getNotificationCenter().postNotificationName(NotificationCenter.closeChats);
                    getMessagesController().addUserToChat(-did, user, 0, null, ProfileActivity.this, null);
                    presentFragment(new ChatActivity(args1), true);
                    removeSelfFromStack();
                });
                presentFragment(fragment);
            } else if (id == share) {
                try {
                    String text = null;
                    if (userId != 0) {
                        TLRPC.User user = getMessagesController().getUser(userId);
                        if (user == null) {
                            return;
                        }
                        if (botInfo != null && userInfo != null && !TextUtils.isEmpty(userInfo.about)) {
                            text = String.format("%s https://" + getMessagesController().linkPrefix + "/%s", userInfo.about, user.username);
                        } else {
                            text = String.format("https://" + getMessagesController().linkPrefix + "/%s", user.username);
                        }
                    } else if (chatId != 0) {
                        TLRPC.Chat chat = getMessagesController().getChat(chatId);
                        if (chat == null) {
                            return;
                        }
                        if (chatInfo != null && !TextUtils.isEmpty(chatInfo.about)) {
                            text = String.format("%s\nhttps://" + getMessagesController().linkPrefix + "/%s", chatInfo.about, chat.username);
                        } else {
                            text = String.format("https://" + getMessagesController().linkPrefix + "/%s", chat.username);
                        }
                    }
                    if (TextUtils.isEmpty(text)) {
                        return;
                    }
                    Intent intent = new Intent(Intent.ACTION_SEND);
                    intent.setType("text/plain");
                    intent.putExtra(Intent.EXTRA_TEXT, text);
                    startActivityForResult(Intent.createChooser(intent, LocaleController.getString("BotShare", R.string.BotShare)), 500);
                } catch (Exception e) {
                    FileLog.e(e);
                }
            } else if (id == add_shortcut) {
                try {
                    long did;
                    if (currentEncryptedChat != null) {
                        did = DialogObject.makeEncryptedDialogId(currentEncryptedChat.id);
                    } else if (userId != 0) {
                        did = userId;
                    } else if (chatId != 0) {
                        did = -chatId;
                    } else {
                        return;
                    }
                    getMediaDataController().installShortcut(did);
                } catch (Exception e) {
                    FileLog.e(e);
                }
            } else if (id == call_item || id == video_call_item) {
                if (userId != 0) {
                    TLRPC.User user = getMessagesController().getUser(userId);
                    if (user != null) {
                        VoIPHelper.startCall(user, id == video_call_item, userInfo != null && userInfo.video_calls_available, getParentActivity(), userInfo, getAccountInstance());
                    }
                } else if (chatId != 0) {
                    ChatObject.Call call = getMessagesController().getGroupCall(chatId, false);
                    if (call == null) {
                        VoIPHelper.showGroupCallAlert(ProfileActivity.this, currentChat, null, false, getAccountInstance());
                    } else {
                        VoIPHelper.startCall(currentChat, null, null, false, getParentActivity(), ProfileActivity.this, getAccountInstance());
                    }
                }
            } else if (id == search_members) {
                Bundle args = new Bundle();
                args.putLong("chat_id", chatId);
                args.putInt("type", ChatUsersActivity.TYPE_USERS);
                args.putBoolean("open_search", true);
                ChatUsersActivity fragment = new ChatUsersActivity(args);
                fragment.setInfo(chatInfo);
                presentFragment(fragment);
            } else if (id == add_member) {
                openAddMember();
            } else if (id == statistics) {
                TLRPC.Chat chat = getMessagesController().getChat(chatId);
                Bundle args = new Bundle();
                args.putLong("chat_id", chatId);
                args.putBoolean("is_megagroup", chat.megagroup);
                StatisticActivity fragment = new StatisticActivity(args);
                presentFragment(fragment);
            } else if (id == view_discussion) {
                openDiscussion();
            } else if (id == start_secret_chat) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setTitle(LocaleController.getString("AreYouSureSecretChatTitle", R.string.AreYouSureSecretChatTitle));
                builder.setMessage(LocaleController.getString("AreYouSureSecretChat", R.string.AreYouSureSecretChat));
                builder.setPositiveButton(LocaleController.getString("Start", R.string.Start), (dialogInterface, i) -> {
                    creatingChat = true;
                    getSecretChatHelper().startSecretChat(getParentActivity(), getMessagesController().getUser(userId));
                });
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                showDialog(builder.create());
            } else if (id == gallery_menu_save) {
                if (getParentActivity() == null) {
                    return;
                }
                if (Build.VERSION.SDK_INT >= 23 && (Build.VERSION.SDK_INT <= 28 || BuildVars.NO_SCOPED_STORAGE) && getParentActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    getParentActivity().requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 4);
                    return;
                }
                ImageLocation location = avatarsViewPager.getImageLocation(avatarsViewPager.getRealPosition());
                if (location == null) {
                    return;
                }
                final boolean isVideo = location.imageType == FileLoader.IMAGE_TYPE_ANIMATION;
                File f = FileLoader.getPathToAttach(location.location, isVideo ? "mp4" : null, true);
                if (f.exists()) {
                    MediaController.saveFile(f.toString(), getParentActivity(), 0, null, null, () -> {
                        if (getParentActivity() == null) {
                            return;
                        }
                        BulletinFactory.createSaveToGalleryBulletin(ProfileActivity.this, isVideo, null).show();
                    });
                }
            } else if (id == edit_name) {
                presentFragment(new ChangeNameActivity());
            } else if (id == logout) {
                presentFragment(new LogoutActivity());
            } else if (id == set_as_main) {
                int position = avatarsViewPager.getRealPosition();
                TLRPC.Photo photo = avatarsViewPager.getPhoto(position);
                if (photo == null) {
                    return;
                }
                avatarsViewPager.startMovePhotoToBegin(position);
                TLRPC.TL_photos_updateProfilePhoto req = new TLRPC.TL_photos_updateProfilePhoto();
                req.id = new TLRPC.TL_inputPhoto();
                req.id.id = photo.id;
                req.id.access_hash = photo.access_hash;
                req.id.file_reference = photo.file_reference;
                UserConfig userConfig = getUserConfig();
                getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
                    avatarsViewPager.finishSettingMainPhoto();
                    if (response instanceof TLRPC.TL_photos_photo) {
                        TLRPC.TL_photos_photo photos_photo = (TLRPC.TL_photos_photo) response;
                        getMessagesController().putUsers(photos_photo.users, false);
                        TLRPC.User user = getMessagesController().getUser(userConfig.clientUserId);
                        if (photos_photo.photo instanceof TLRPC.TL_photo) {
                            avatarsViewPager.replaceFirstPhoto(photo, photos_photo.photo);
                            if (user != null) {
                                user.photo.photo_id = photos_photo.photo.id;
                                userConfig.setCurrentUser(user);
                                userConfig.saveConfig(true);
                            }
                        }
                    }
                }));
                undoView.showWithAction(userId, UndoView.ACTION_PROFILE_PHOTO_CHANGED, photo.video_sizes.isEmpty() ? null : 1);
                TLRPC.User user = getMessagesController().getUser(userConfig.clientUserId);
                TLRPC.PhotoSize bigSize = FileLoader.getClosestPhotoSizeWithSize(photo.sizes, 800);
                if (user != null) {
                    TLRPC.PhotoSize smallSize = FileLoader.getClosestPhotoSizeWithSize(photo.sizes, 90);
                    user.photo.photo_id = photo.id;
                    user.photo.photo_small = smallSize.location;
                    user.photo.photo_big = bigSize.location;
                    userConfig.setCurrentUser(user);
                    userConfig.saveConfig(true);
                    NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.mainUserInfoChanged);
                    updateProfileData();
                }
                avatarsViewPager.commitMoveToBegin();
            } else if (id == edit_avatar) {
                int position = avatarsViewPager.getRealPosition();
                ImageLocation location = avatarsViewPager.getImageLocation(position);
                if (location == null) {
                    return;
                }
                File f = FileLoader.getPathToAttach(PhotoViewer.getFileLocation(location), PhotoViewer.getFileLocationExt(location), true);
                boolean isVideo = location.imageType == FileLoader.IMAGE_TYPE_ANIMATION;
                String thumb;
                if (isVideo) {
                    ImageLocation imageLocation = avatarsViewPager.getRealImageLocation(position);
                    thumb = FileLoader.getPathToAttach(PhotoViewer.getFileLocation(imageLocation), PhotoViewer.getFileLocationExt(imageLocation), true).getAbsolutePath();
                } else {
                    thumb = null;
                }
                imageUpdater.openPhotoForEdit(f.getAbsolutePath(), thumb, 0, isVideo);
            } else if (id == delete_avatar) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                ImageLocation location = avatarsViewPager.getImageLocation(avatarsViewPager.getRealPosition());
                if (location == null) {
                    return;
                }
                if (location.imageType == FileLoader.IMAGE_TYPE_ANIMATION) {
                    builder.setTitle(LocaleController.getString("AreYouSureDeleteVideoTitle", R.string.AreYouSureDeleteVideoTitle));
                    builder.setMessage(LocaleController.formatString("AreYouSureDeleteVideo", R.string.AreYouSureDeleteVideo));
                } else {
                    builder.setTitle(LocaleController.getString("AreYouSureDeletePhotoTitle", R.string.AreYouSureDeletePhotoTitle));
                    builder.setMessage(LocaleController.formatString("AreYouSureDeletePhoto", R.string.AreYouSureDeletePhoto));
                }
                builder.setPositiveButton(LocaleController.getString("Delete", R.string.Delete), (dialogInterface, i) -> {
                    int position = avatarsViewPager.getRealPosition();
                    TLRPC.Photo photo = avatarsViewPager.getPhoto(position);
                    if (avatarsViewPager.getRealCount() == 1) {
                        setForegroundImage(true);
                    }
                    if (photo == null || avatarsViewPager.getRealPosition() == 0) {
                        getMessagesController().deleteUserPhoto(null);
                    } else {
                        TLRPC.TL_inputPhoto inputPhoto = new TLRPC.TL_inputPhoto();
                        inputPhoto.id = photo.id;
                        inputPhoto.access_hash = photo.access_hash;
                        inputPhoto.file_reference = photo.file_reference;
                        if (inputPhoto.file_reference == null) {
                            inputPhoto.file_reference = new byte[0];
                        }
                        getMessagesController().deleteUserPhoto(inputPhoto);
                        getMessagesStorage().clearUserPhoto(userId, photo.id);
                    }
                    if (avatarsViewPager.removePhotoAtIndex(position)) {
                        avatarsViewPager.setVisibility(View.GONE);
                        avatarImage.setForegroundAlpha(1f);
                        avatarContainer.setVisibility(View.VISIBLE);
                        doNotSetForeground = true;
                        final View view = layoutManager.findViewByPosition(0);
                        if (view != null) {
                            listView.smoothScrollBy(0, view.getTop() - AndroidUtilities.dp(88), CubicBezierInterpolator.EASE_OUT_QUINT);
                        }
                    }
                });
                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 (id == add_photo) {
                onWriteButtonClick();
            } else if (id == qr_button) {
                Bundle args = new Bundle();
                args.putLong("chat_id", chatId);
                args.putLong("user_id", userId);
                presentFragment(new QrActivity(args));
            }
        }
    });
    if (sharedMediaLayout != null) {
        sharedMediaLayout.onDestroy();
    }
    final long did;
    if (dialogId != 0) {
        did = dialogId;
    } else if (userId != 0) {
        did = userId;
    } else {
        did = -chatId;
    }
    ArrayList<Integer> users = chatInfo != null && chatInfo.participants != null && chatInfo.participants.participants.size() > 5 ? sortedUsers : null;
    sharedMediaLayout = new SharedMediaLayout(context, did, sharedMediaPreloader, userInfo != null ? userInfo.common_chats_count : 0, sortedUsers, chatInfo, users != null, this, this, SharedMediaLayout.VIEW_TYPE_PROFILE_ACTIVITY) {

        @Override
        protected void onSelectedTabChanged() {
            updateSelectedMediaTabText();
        }

        @Override
        protected boolean canShowSearchItem() {
            return mediaHeaderVisible;
        }

        @Override
        protected void onSearchStateChanged(boolean expanded) {
            if (SharedConfig.smoothKeyboard) {
                AndroidUtilities.removeAdjustResize(getParentActivity(), classGuid);
            }
            listView.stopScroll();
            avatarContainer2.setPivotY(avatarContainer.getPivotY() + avatarContainer.getMeasuredHeight() / 2f);
            avatarContainer2.setPivotX(avatarContainer2.getMeasuredWidth() / 2f);
            AndroidUtilities.updateViewVisibilityAnimated(avatarContainer2, !expanded, 0.95f, true);
            callItem.setVisibility(expanded || !callItemVisible ? GONE : INVISIBLE);
            videoCallItem.setVisibility(expanded || !videoCallItemVisible ? GONE : INVISIBLE);
            editItem.setVisibility(expanded || !editItemVisible ? GONE : INVISIBLE);
            otherItem.setVisibility(expanded ? GONE : INVISIBLE);
            if (qrItem != null) {
                qrItem.setVisibility(expanded ? GONE : INVISIBLE);
            }
        }

        @Override
        protected boolean onMemberClick(TLRPC.ChatParticipant participant, boolean isLong) {
            return ProfileActivity.this.onMemberClick(participant, isLong);
        }
    };
    sharedMediaLayout.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.MATCH_PARENT));
    ActionBarMenu menu = actionBar.createMenu();
    if (userId == getUserConfig().clientUserId) {
        qrItem = menu.addItem(qr_button, R.drawable.msg_qr_mini, getResourceProvider());
        qrItem.setVisibility(isQrNeedVisible() ? View.VISIBLE : View.GONE);
        qrItem.setContentDescription(LocaleController.getString("AuthAnotherClientScan", R.string.AuthAnotherClientScan));
    }
    if (imageUpdater != null) {
        searchItem = menu.addItem(search_button, R.drawable.ic_ab_search).setIsSearchField(true).setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() {

            @Override
            public Animator getCustomToggleTransition() {
                searchMode = !searchMode;
                if (!searchMode) {
                    searchItem.clearFocusOnSearchView();
                }
                if (searchMode) {
                    searchItem.getSearchField().setText("");
                }
                return searchExpandTransition(searchMode);
            }

            @Override
            public void onTextChanged(EditText editText) {
                searchAdapter.search(editText.getText().toString().toLowerCase());
            }
        });
        searchItem.setContentDescription(LocaleController.getString("SearchInSettings", R.string.SearchInSettings));
        searchItem.setSearchFieldHint(LocaleController.getString("SearchInSettings", R.string.SearchInSettings));
        sharedMediaLayout.getSearchItem().setVisibility(View.GONE);
        if (expandPhoto) {
            searchItem.setVisibility(View.GONE);
        }
    }
    videoCallItem = menu.addItem(video_call_item, R.drawable.profile_video);
    videoCallItem.setContentDescription(LocaleController.getString("VideoCall", R.string.VideoCall));
    if (chatId != 0) {
        callItem = menu.addItem(call_item, R.drawable.msg_voicechat2);
        if (ChatObject.isChannelOrGiga(currentChat)) {
            callItem.setContentDescription(LocaleController.getString("VoipChannelVoiceChat", R.string.VoipChannelVoiceChat));
        } else {
            callItem.setContentDescription(LocaleController.getString("VoipGroupVoiceChat", R.string.VoipGroupVoiceChat));
        }
    } else {
        callItem = menu.addItem(call_item, R.drawable.ic_call);
        callItem.setContentDescription(LocaleController.getString("Call", R.string.Call));
    }
    editItem = menu.addItem(edit_channel, R.drawable.group_edit_profile);
    editItem.setContentDescription(LocaleController.getString("Edit", R.string.Edit));
    otherItem = menu.addItem(10, R.drawable.ic_ab_other);
    otherItem.setContentDescription(LocaleController.getString("AccDescrMoreOptions", R.string.AccDescrMoreOptions));
    int scrollTo;
    int scrollToPosition = 0;
    Object writeButtonTag = null;
    if (listView != null && imageUpdater != null) {
        scrollTo = layoutManager.findFirstVisibleItemPosition();
        View topView = layoutManager.findViewByPosition(scrollTo);
        if (topView != null) {
            scrollToPosition = topView.getTop() - listView.getPaddingTop();
        } else {
            scrollTo = -1;
        }
        writeButtonTag = writeButton.getTag();
    } else {
        scrollTo = -1;
    }
    createActionBarMenu(false);
    listAdapter = new ListAdapter(context);
    searchAdapter = new SearchAdapter(context);
    avatarDrawable = new AvatarDrawable();
    avatarDrawable.setProfile(true);
    fragmentView = new NestedFrameLayout(context) {

        @Override
        public boolean dispatchTouchEvent(MotionEvent ev) {
            if (pinchToZoomHelper.isInOverlayMode()) {
                return pinchToZoomHelper.onTouchEvent(ev);
            }
            if (sharedMediaLayout != null && sharedMediaLayout.isInFastScroll() && sharedMediaLayout.isPinnedToTop()) {
                return sharedMediaLayout.dispatchFastScrollEvent(ev);
            }
            if (sharedMediaLayout != null && sharedMediaLayout.checkPinchToZoom(ev)) {
                return true;
            }
            return super.dispatchTouchEvent(ev);
        }

        private boolean ignoreLayout;

        private Paint grayPaint = new Paint();

        @Override
        public boolean hasOverlappingRendering() {
            return false;
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            final int actionBarHeight = ActionBar.getCurrentActionBarHeight() + (actionBar.getOccupyStatusBar() ? AndroidUtilities.statusBarHeight : 0);
            if (listView != null) {
                FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams();
                if (layoutParams.topMargin != actionBarHeight) {
                    layoutParams.topMargin = actionBarHeight;
                }
            }
            if (searchListView != null) {
                FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) searchListView.getLayoutParams();
                if (layoutParams.topMargin != actionBarHeight) {
                    layoutParams.topMargin = actionBarHeight;
                }
            }
            int height = MeasureSpec.getSize(heightMeasureSpec);
            super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
            boolean changed = false;
            if (lastMeasuredContentWidth != getMeasuredWidth() || lastMeasuredContentHeight != getMeasuredHeight()) {
                changed = lastMeasuredContentWidth != 0 && lastMeasuredContentWidth != getMeasuredWidth();
                listContentHeight = 0;
                int count = listAdapter.getItemCount();
                lastMeasuredContentWidth = getMeasuredWidth();
                lastMeasuredContentHeight = getMeasuredHeight();
                int ws = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY);
                int hs = MeasureSpec.makeMeasureSpec(listView.getMeasuredHeight(), MeasureSpec.UNSPECIFIED);
                positionToOffset.clear();
                for (int i = 0; i < count; i++) {
                    int type = listAdapter.getItemViewType(i);
                    positionToOffset.put(i, listContentHeight);
                    if (type == 13) {
                        listContentHeight += listView.getMeasuredHeight();
                    } else {
                        RecyclerView.ViewHolder holder = listAdapter.createViewHolder(null, type);
                        listAdapter.onBindViewHolder(holder, i);
                        holder.itemView.measure(ws, hs);
                        listContentHeight += holder.itemView.getMeasuredHeight();
                    }
                }
                if (emptyView != null) {
                    ((LayoutParams) emptyView.getLayoutParams()).topMargin = AndroidUtilities.dp(88) + AndroidUtilities.statusBarHeight;
                }
            }
            if (!fragmentOpened && (expandPhoto || openAnimationInProgress && playProfileAnimation == 2)) {
                ignoreLayout = true;
                if (expandPhoto) {
                    if (searchItem != null) {
                        searchItem.setAlpha(0.0f);
                        searchItem.setEnabled(false);
                        searchItem.setVisibility(GONE);
                    }
                    nameTextView[1].setTextColor(Color.WHITE);
                    onlineTextView[1].setTextColor(Color.argb(179, 255, 255, 255));
                    actionBar.setItemsBackgroundColor(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR, false);
                    actionBar.setItemsColor(Color.WHITE, false);
                    overlaysView.setOverlaysVisible();
                    overlaysView.setAlphaValue(1.0f, false);
                    avatarImage.setForegroundAlpha(1.0f);
                    avatarContainer.setVisibility(View.GONE);
                    avatarsViewPager.resetCurrentItem();
                    avatarsViewPager.setVisibility(View.VISIBLE);
                    expandPhoto = false;
                }
                allowPullingDown = true;
                isPulledDown = true;
                if (otherItem != null) {
                    if (!getMessagesController().isChatNoForwards(currentChat)) {
                        otherItem.showSubItem(gallery_menu_save);
                    } else {
                        otherItem.hideSubItem(gallery_menu_save);
                    }
                    if (imageUpdater != null) {
                        otherItem.showSubItem(edit_avatar);
                        otherItem.showSubItem(delete_avatar);
                        otherItem.hideSubItem(logout);
                    }
                }
                currentExpanAnimatorFracture = 1.0f;
                int paddingTop;
                int paddingBottom;
                if (isInLandscapeMode) {
                    paddingTop = AndroidUtilities.dp(88f);
                    paddingBottom = 0;
                } else {
                    paddingTop = listView.getMeasuredWidth();
                    paddingBottom = Math.max(0, getMeasuredHeight() - (listContentHeight + AndroidUtilities.dp(88) + actionBarHeight));
                }
                if (banFromGroup != 0) {
                    paddingBottom += AndroidUtilities.dp(48);
                    listView.setBottomGlowOffset(AndroidUtilities.dp(48));
                } else {
                    listView.setBottomGlowOffset(0);
                }
                initialAnimationExtraHeight = paddingTop - actionBarHeight;
                layoutManager.scrollToPositionWithOffset(0, -actionBarHeight);
                listView.setPadding(0, paddingTop, 0, paddingBottom);
                measureChildWithMargins(listView, widthMeasureSpec, 0, heightMeasureSpec, 0);
                listView.layout(0, actionBarHeight, listView.getMeasuredWidth(), actionBarHeight + listView.getMeasuredHeight());
                ignoreLayout = false;
            } else if (fragmentOpened && !openAnimationInProgress && !firstLayout) {
                ignoreLayout = true;
                int paddingTop;
                int paddingBottom;
                if (isInLandscapeMode || AndroidUtilities.isTablet()) {
                    paddingTop = AndroidUtilities.dp(88f);
                    paddingBottom = 0;
                } else {
                    paddingTop = listView.getMeasuredWidth();
                    paddingBottom = Math.max(0, getMeasuredHeight() - (listContentHeight + AndroidUtilities.dp(88) + actionBarHeight));
                }
                if (banFromGroup != 0) {
                    paddingBottom += AndroidUtilities.dp(48);
                    listView.setBottomGlowOffset(AndroidUtilities.dp(48));
                } else {
                    listView.setBottomGlowOffset(0);
                }
                int currentPaddingTop = listView.getPaddingTop();
                View view = null;
                int pos = RecyclerView.NO_POSITION;
                for (int i = 0; i < listView.getChildCount(); i++) {
                    int p = listView.getChildAdapterPosition(listView.getChildAt(i));
                    if (p != RecyclerView.NO_POSITION) {
                        view = listView.getChildAt(i);
                        pos = p;
                        break;
                    }
                }
                if (view == null) {
                    view = listView.getChildAt(0);
                    if (view != null) {
                        RecyclerView.ViewHolder holder = listView.findContainingViewHolder(view);
                        pos = holder.getAdapterPosition();
                        if (pos == RecyclerView.NO_POSITION) {
                            pos = holder.getPosition();
                        }
                    }
                }
                int top = paddingTop;
                if (view != null) {
                    top = view.getTop();
                }
                boolean layout = false;
                if (actionBar.isSearchFieldVisible() && sharedMediaRow >= 0) {
                    layoutManager.scrollToPositionWithOffset(sharedMediaRow, -paddingTop);
                    layout = true;
                } else if (invalidateScroll || currentPaddingTop != paddingTop) {
                    if (savedScrollPosition >= 0) {
                        layoutManager.scrollToPositionWithOffset(savedScrollPosition, savedScrollOffset - paddingTop);
                    } else if ((!changed || !allowPullingDown) && view != null) {
                        if (pos == 0 && !allowPullingDown && top > AndroidUtilities.dp(88)) {
                            top = AndroidUtilities.dp(88);
                        }
                        layoutManager.scrollToPositionWithOffset(pos, top - paddingTop);
                        layout = true;
                    } else {
                        layoutManager.scrollToPositionWithOffset(0, AndroidUtilities.dp(88) - paddingTop);
                    }
                }
                if (currentPaddingTop != paddingTop || listView.getPaddingBottom() != paddingBottom) {
                    listView.setPadding(0, paddingTop, 0, paddingBottom);
                    layout = true;
                }
                if (layout) {
                    measureChildWithMargins(listView, widthMeasureSpec, 0, heightMeasureSpec, 0);
                    try {
                        listView.layout(0, actionBarHeight, listView.getMeasuredWidth(), actionBarHeight + listView.getMeasuredHeight());
                    } catch (Exception e) {
                        FileLog.e(e);
                    }
                }
                ignoreLayout = false;
            }
        }

        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            super.onLayout(changed, left, top, right, bottom);
            savedScrollPosition = -1;
            firstLayout = false;
            invalidateScroll = false;
            checkListViewScroll();
        }

        @Override
        public void requestLayout() {
            if (ignoreLayout) {
                return;
            }
            super.requestLayout();
        }

        private final ArrayList<View> sortedChildren = new ArrayList<>();

        private final Comparator<View> viewComparator = (view, view2) -> (int) (view.getY() - view2.getY());

        @Override
        protected void dispatchDraw(Canvas canvas) {
            whitePaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhite));
            if (listView.getVisibility() == VISIBLE) {
                grayPaint.setColor(Theme.getColor(Theme.key_windowBackgroundGray));
                if (transitionAnimationInProress) {
                    whitePaint.setAlpha((int) (255 * listView.getAlpha()));
                }
                if (transitionAnimationInProress) {
                    grayPaint.setAlpha((int) (255 * listView.getAlpha()));
                }
                int count = listView.getChildCount();
                sortedChildren.clear();
                boolean hasRemovingItems = false;
                for (int i = 0; i < count; i++) {
                    View child = listView.getChildAt(i);
                    if (listView.getChildAdapterPosition(child) != RecyclerView.NO_POSITION) {
                        sortedChildren.add(listView.getChildAt(i));
                    } else {
                        hasRemovingItems = true;
                    }
                }
                Collections.sort(sortedChildren, viewComparator);
                boolean hasBackground = false;
                float lastY = listView.getY();
                count = sortedChildren.size();
                if (!openAnimationInProgress && count > 0 && !hasRemovingItems) {
                    lastY += sortedChildren.get(0).getY();
                }
                float alpha = 1f;
                for (int i = 0; i < count; i++) {
                    View child = sortedChildren.get(i);
                    boolean currentHasBackground = child.getBackground() != null;
                    int currentY = (int) (listView.getY() + child.getY());
                    if (hasBackground == currentHasBackground) {
                        if (child.getAlpha() == 1f) {
                            alpha = 1f;
                        }
                        continue;
                    }
                    if (hasBackground) {
                        canvas.drawRect(listView.getX(), lastY, listView.getX() + listView.getMeasuredWidth(), currentY, grayPaint);
                    } else {
                        if (alpha != 1f) {
                            canvas.drawRect(listView.getX(), lastY, listView.getX() + listView.getMeasuredWidth(), currentY, grayPaint);
                            whitePaint.setAlpha((int) (255 * alpha));
                            canvas.drawRect(listView.getX(), lastY, listView.getX() + listView.getMeasuredWidth(), currentY, whitePaint);
                            whitePaint.setAlpha(255);
                        } else {
                            canvas.drawRect(listView.getX(), lastY, listView.getX() + listView.getMeasuredWidth(), currentY, whitePaint);
                        }
                    }
                    hasBackground = currentHasBackground;
                    lastY = currentY;
                    alpha = child.getAlpha();
                }
                if (hasBackground) {
                    canvas.drawRect(listView.getX(), lastY, listView.getX() + listView.getMeasuredWidth(), listView.getBottom(), grayPaint);
                } else {
                    if (alpha != 1f) {
                        canvas.drawRect(listView.getX(), lastY, listView.getX() + listView.getMeasuredWidth(), listView.getBottom(), grayPaint);
                        whitePaint.setAlpha((int) (255 * alpha));
                        canvas.drawRect(listView.getX(), lastY, listView.getX() + listView.getMeasuredWidth(), listView.getBottom(), whitePaint);
                        whitePaint.setAlpha(255);
                    } else {
                        canvas.drawRect(listView.getX(), lastY, listView.getX() + listView.getMeasuredWidth(), listView.getBottom(), whitePaint);
                    }
                }
            } else {
                int top = searchListView.getTop();
                canvas.drawRect(0, top + extraHeight + searchTransitionOffset, getMeasuredWidth(), top + getMeasuredHeight(), whitePaint);
            }
            super.dispatchDraw(canvas);
            if (profileTransitionInProgress && parentLayout.fragmentsStack.size() > 1) {
                BaseFragment fragment = parentLayout.fragmentsStack.get(parentLayout.fragmentsStack.size() - 2);
                if (fragment instanceof ChatActivity) {
                    ChatActivity chatActivity = (ChatActivity) fragment;
                    FragmentContextView fragmentContextView = chatActivity.getFragmentContextView();
                    if (fragmentContextView != null && fragmentContextView.isCallStyle()) {
                        float progress = extraHeight / AndroidUtilities.dpf2(fragmentContextView.getStyleHeight());
                        if (progress > 1f) {
                            progress = 1f;
                        }
                        canvas.save();
                        canvas.translate(fragmentContextView.getX(), fragmentContextView.getY());
                        fragmentContextView.setDrawOverlay(true);
                        fragmentContextView.setCollapseTransition(true, extraHeight, progress);
                        fragmentContextView.draw(canvas);
                        fragmentContextView.setCollapseTransition(false, extraHeight, progress);
                        fragmentContextView.setDrawOverlay(false);
                        canvas.restore();
                    }
                }
            }
            if (scrimPaint.getAlpha() > 0) {
                canvas.drawRect(0, 0, getWidth(), getHeight(), scrimPaint);
            }
            if (scrimView != null) {
                int c = canvas.save();
                canvas.translate(scrimView.getLeft(), scrimView.getTop());
                if (scrimView == actionBar.getBackButton()) {
                    int r = Math.max(scrimView.getMeasuredWidth(), scrimView.getMeasuredHeight()) / 2;
                    int wasAlpha = actionBarBackgroundPaint.getAlpha();
                    actionBarBackgroundPaint.setAlpha((int) (wasAlpha * (scrimPaint.getAlpha() / 255f) / 0.3f));
                    canvas.drawCircle(r, r, r * 0.8f, actionBarBackgroundPaint);
                    actionBarBackgroundPaint.setAlpha(wasAlpha);
                }
                scrimView.draw(canvas);
                canvas.restoreToCount(c);
            }
        }

        @Override
        protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
            if (pinchToZoomHelper.isInOverlayMode() && (child == avatarContainer2 || child == actionBar || child == writeButton)) {
                return true;
            }
            return super.drawChild(canvas, child, drawingTime);
        }
    };
    fragmentView.setWillNotDraw(false);
    FrameLayout frameLayout = (FrameLayout) fragmentView;
    listView = new RecyclerListView(context) {

        private VelocityTracker velocityTracker;

        @Override
        protected boolean canHighlightChildAt(View child, float x, float y) {
            return !(child instanceof AboutLinkCell);
        }

        @Override
        protected boolean allowSelectChildAtPosition(View child) {
            return child != sharedMediaLayout;
        }

        @Override
        public boolean hasOverlappingRendering() {
            return false;
        }

        @Override
        protected void requestChildOnScreen(View child, View focused) {
        }

        @Override
        public void invalidate() {
            super.invalidate();
            if (fragmentView != null) {
                fragmentView.invalidate();
            }
        }

        @Override
        public boolean onTouchEvent(MotionEvent e) {
            final int action = e.getAction();
            if (action == MotionEvent.ACTION_DOWN) {
                if (velocityTracker == null) {
                    velocityTracker = VelocityTracker.obtain();
                } else {
                    velocityTracker.clear();
                }
                velocityTracker.addMovement(e);
            } else if (action == MotionEvent.ACTION_MOVE) {
                if (velocityTracker != null) {
                    velocityTracker.addMovement(e);
                    velocityTracker.computeCurrentVelocity(1000);
                    listViewVelocityY = velocityTracker.getYVelocity(e.getPointerId(e.getActionIndex()));
                }
            } else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
                if (velocityTracker != null) {
                    velocityTracker.recycle();
                    velocityTracker = null;
                }
            }
            final boolean result = super.onTouchEvent(e);
            if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
                if (allowPullingDown) {
                    final View view = layoutManager.findViewByPosition(0);
                    if (view != null) {
                        if (isPulledDown) {
                            final int actionBarHeight = ActionBar.getCurrentActionBarHeight() + (actionBar.getOccupyStatusBar() ? AndroidUtilities.statusBarHeight : 0);
                            listView.smoothScrollBy(0, view.getTop() - listView.getMeasuredWidth() + actionBarHeight, CubicBezierInterpolator.EASE_OUT_QUINT);
                        } else {
                            listView.smoothScrollBy(0, view.getTop() - AndroidUtilities.dp(88), CubicBezierInterpolator.EASE_OUT_QUINT);
                        }
                    }
                }
            }
            return result;
        }

        @Override
        public boolean drawChild(Canvas canvas, View child, long drawingTime) {
            if (getItemAnimator().isRunning() && child.getBackground() == null && child.getTranslationY() != 0) {
                boolean useAlpha = listView.getChildAdapterPosition(child) == sharedMediaRow && child.getAlpha() != 1f;
                if (useAlpha) {
                    whitePaint.setAlpha((int) (255 * listView.getAlpha() * child.getAlpha()));
                }
                canvas.drawRect(listView.getX(), child.getY(), listView.getX() + listView.getMeasuredWidth(), child.getY() + child.getHeight(), whitePaint);
                if (useAlpha) {
                    whitePaint.setAlpha((int) (255 * listView.getAlpha()));
                }
            }
            return super.drawChild(canvas, child, drawingTime);
        }
    };
    listView.setVerticalScrollBarEnabled(false);
    DefaultItemAnimator defaultItemAnimator = new DefaultItemAnimator() {

        int animationIndex = -1;

        @Override
        protected void onAllAnimationsDone() {
            super.onAllAnimationsDone();
            getNotificationCenter().onAnimationFinish(animationIndex);
        }

        @Override
        public void runPendingAnimations() {
            boolean removalsPending = !mPendingRemovals.isEmpty();
            boolean movesPending = !mPendingMoves.isEmpty();
            boolean changesPending = !mPendingChanges.isEmpty();
            boolean additionsPending = !mPendingAdditions.isEmpty();
            if (removalsPending || movesPending || additionsPending || changesPending) {
                ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1f);
                valueAnimator.addUpdateListener(valueAnimator1 -> listView.invalidate());
                valueAnimator.setDuration(getMoveDuration());
                valueAnimator.start();
                animationIndex = getNotificationCenter().setAnimationInProgress(animationIndex, null);
            }
            super.runPendingAnimations();
        }

        @Override
        protected long getAddAnimationDelay(long removeDuration, long moveDuration, long changeDuration) {
            return 0;
        }

        @Override
        protected long getMoveAnimationDelay() {
            return 0;
        }

        @Override
        public long getMoveDuration() {
            return 220;
        }

        @Override
        public long getRemoveDuration() {
            return 220;
        }

        @Override
        public long getAddDuration() {
            return 220;
        }
    };
    listView.setItemAnimator(defaultItemAnimator);
    defaultItemAnimator.setSupportsChangeAnimations(false);
    defaultItemAnimator.setDelayAnimations(false);
    listView.setClipToPadding(false);
    listView.setHideIfEmpty(false);
    layoutManager = new LinearLayoutManager(context) {

        @Override
        public boolean supportsPredictiveItemAnimations() {
            return imageUpdater != null;
        }

        @Override
        public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
            final View view = layoutManager.findViewByPosition(0);
            if (view != null && !openingAvatar) {
                final int canScroll = view.getTop() - AndroidUtilities.dp(88);
                if (!allowPullingDown && canScroll > dy) {
                    dy = canScroll;
                    if (avatarsViewPager.hasImages() && avatarImage.getImageReceiver().hasNotThumb() && !isInLandscapeMode && !AndroidUtilities.isTablet()) {
                        allowPullingDown = avatarBig == null;
                    }
                } else if (allowPullingDown) {
                    if (dy >= canScroll) {
                        dy = canScroll;
                        allowPullingDown = false;
                    } else if (listView.getScrollState() == RecyclerListView.SCROLL_STATE_DRAGGING) {
                        if (!isPulledDown) {
                            dy /= 2;
                        }
                    }
                }
            }
            return super.scrollVerticallyBy(dy, recycler, state);
        }
    };
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    layoutManager.mIgnoreTopPadding = false;
    listView.setLayoutManager(layoutManager);
    listView.setGlowColor(0);
    listView.setAdapter(listAdapter);
    frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));
    listView.setOnItemClickListener((view, position, x, y) -> {
        if (getParentActivity() == null) {
            return;
        }
        if (position == settingsKeyRow) {
            Bundle args = new Bundle();
            args.putInt("chat_id", DialogObject.getEncryptedChatId(dialogId));
            presentFragment(new IdenticonActivity(args));
        } else if (position == settingsTimerRow) {
            showDialog(AlertsCreator.createTTLAlert(getParentActivity(), currentEncryptedChat, null).create());
        } else if (position == notificationsRow) {
            if (LocaleController.isRTL && x <= AndroidUtilities.dp(76) || !LocaleController.isRTL && x >= view.getMeasuredWidth() - AndroidUtilities.dp(76)) {
                NotificationsCheckCell checkCell = (NotificationsCheckCell) view;
                boolean checked = !checkCell.isChecked();
                boolean defaultEnabled = getNotificationsController().isGlobalNotificationsEnabled(did);
                if (checked) {
                    SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount);
                    SharedPreferences.Editor editor = preferences.edit();
                    if (defaultEnabled) {
                        editor.remove("notify2_" + did);
                    } else {
                        editor.putInt("notify2_" + did, 0);
                    }
                    getMessagesStorage().setDialogFlags(did, 0);
                    editor.commit();
                    TLRPC.Dialog dialog = getMessagesController().dialogs_dict.get(did);
                    if (dialog != null) {
                        dialog.notify_settings = new TLRPC.TL_peerNotifySettings();
                    }
                } else {
                    int untilTime = Integer.MAX_VALUE;
                    SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount);
                    SharedPreferences.Editor editor = preferences.edit();
                    long flags;
                    if (!defaultEnabled) {
                        editor.remove("notify2_" + did);
                        flags = 0;
                    } else {
                        editor.putInt("notify2_" + did, 2);
                        flags = 1;
                    }
                    getNotificationsController().removeNotificationsForDialog(did);
                    getMessagesStorage().setDialogFlags(did, flags);
                    editor.commit();
                    TLRPC.Dialog dialog = getMessagesController().dialogs_dict.get(did);
                    if (dialog != null) {
                        dialog.notify_settings = new TLRPC.TL_peerNotifySettings();
                        if (defaultEnabled) {
                            dialog.notify_settings.mute_until = untilTime;
                        }
                    }
                }
                getNotificationsController().updateServerNotificationsSettings(did);
                checkCell.setChecked(checked);
                RecyclerListView.Holder holder = (RecyclerListView.Holder) listView.findViewHolderForPosition(notificationsRow);
                if (holder != null) {
                    listAdapter.onBindViewHolder(holder, notificationsRow);
                }
                return;
            }
            AlertsCreator.showCustomNotificationsDialog(ProfileActivity.this, did, -1, null, currentAccount, param -> listAdapter.notifyItemChanged(notificationsRow));
        } else if (position == unblockRow) {
            getMessagesController().unblockPeer(userId);
            if (BulletinFactory.canShowBulletin(ProfileActivity.this)) {
                BulletinFactory.createBanBulletin(ProfileActivity.this, false).show();
            }
        } else if (position == sendMessageRow) {
            onWriteButtonClick();
        } else if (position == reportRow) {
            AlertsCreator.createReportAlert(getParentActivity(), getDialogId(), 0, ProfileActivity.this, null);
        } else if (position >= membersStartRow && position < membersEndRow) {
            TLRPC.ChatParticipant participant;
            if (!sortedUsers.isEmpty()) {
                participant = chatInfo.participants.participants.get(sortedUsers.get(position - membersStartRow));
            } else {
                participant = chatInfo.participants.participants.get(position - membersStartRow);
            }
            onMemberClick(participant, false);
        } else if (position == addMemberRow) {
            openAddMember();
        } else if (position == usernameRow) {
            if (currentChat != null) {
                try {
                    Intent intent = new Intent(Intent.ACTION_SEND);
                    intent.setType("text/plain");
                    if (!TextUtils.isEmpty(chatInfo.about)) {
                        intent.putExtra(Intent.EXTRA_TEXT, currentChat.title + "\n" + chatInfo.about + "\nhttps://" + getMessagesController().linkPrefix + "/" + currentChat.username);
                    } else {
                        intent.putExtra(Intent.EXTRA_TEXT, currentChat.title + "\nhttps://" + getMessagesController().linkPrefix + "/" + currentChat.username);
                    }
                    getParentActivity().startActivityForResult(Intent.createChooser(intent, LocaleController.getString("BotShare", R.string.BotShare)), 500);
                } catch (Exception e) {
                    FileLog.e(e);
                }
            }
        } else if (position == locationRow) {
            if (chatInfo.location instanceof TLRPC.TL_channelLocation) {
                LocationActivity fragment = new LocationActivity(LocationActivity.LOCATION_TYPE_GROUP_VIEW);
                fragment.setChatLocation(chatId, (TLRPC.TL_channelLocation) chatInfo.location);
                presentFragment(fragment);
            }
        } else if (position == joinRow) {
            getMessagesController().addUserToChat(currentChat.id, getUserConfig().getCurrentUser(), 0, null, ProfileActivity.this, null);
            NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.closeSearchByActiveAction);
        } else if (position == subscribersRow) {
            Bundle args = new Bundle();
            args.putLong("chat_id", chatId);
            args.putInt("type", ChatUsersActivity.TYPE_USERS);
            ChatUsersActivity fragment = new ChatUsersActivity(args);
            fragment.setInfo(chatInfo);
            presentFragment(fragment);
        } else if (position == subscribersRequestsRow) {
            MemberRequestsActivity activity = new MemberRequestsActivity(chatId);
            presentFragment(activity);
        } else if (position == administratorsRow) {
            Bundle args = new Bundle();
            args.putLong("chat_id", chatId);
            args.putInt("type", ChatUsersActivity.TYPE_ADMIN);
            ChatUsersActivity fragment = new ChatUsersActivity(args);
            fragment.setInfo(chatInfo);
            presentFragment(fragment);
        } else if (position == blockedUsersRow) {
            Bundle args = new Bundle();
            args.putLong("chat_id", chatId);
            args.putInt("type", ChatUsersActivity.TYPE_BANNED);
            ChatUsersActivity fragment = new ChatUsersActivity(args);
            fragment.setInfo(chatInfo);
            presentFragment(fragment);
        } else if (position == notificationRow) {
            presentFragment(new NotificationsSettingsActivity());
        } else if (position == privacyRow) {
            presentFragment(new PrivacySettingsActivity());
        } else if (position == dataRow) {
            presentFragment(new DataSettingsActivity());
        } else if (position == chatRow) {
            presentFragment(new ThemeActivity(ThemeActivity.THEME_TYPE_BASIC));
        } else if (position == filtersRow) {
            presentFragment(new FiltersSetupActivity());
        } else if (position == devicesRow) {
            presentFragment(new SessionsActivity(0));
        } else if (position == questionRow) {
            showDialog(AlertsCreator.createSupportAlert(ProfileActivity.this));
        } else if (position == faqRow) {
            Browser.openUrl(getParentActivity(), LocaleController.getString("TelegramFaqUrl", R.string.TelegramFaqUrl));
        } else if (position == policyRow) {
            Browser.openUrl(getParentActivity(), LocaleController.getString("PrivacyPolicyUrl", R.string.PrivacyPolicyUrl));
        } else if (position == sendLogsRow) {
            sendLogs(false);
        } else if (position == sendLastLogsRow) {
            sendLogs(true);
        } else if (position == clearLogsRow) {
            FileLog.cleanupLogs();
        } else if (position == switchBackendRow) {
            if (getParentActivity() == null) {
                return;
            }
            AlertDialog.Builder builder1 = new AlertDialog.Builder(getParentActivity());
            builder1.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure));
            builder1.setTitle(LocaleController.getString("AppName", R.string.AppName));
            builder1.setPositiveButton(LocaleController.getString("OK", R.string.OK), (dialogInterface, i) -> {
                SharedConfig.pushAuthKey = null;
                SharedConfig.pushAuthKeyId = null;
                SharedConfig.saveConfig();
                getConnectionsManager().switchBackend(true);
            });
            builder1.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
            showDialog(builder1.create());
        } else if (position == languageRow) {
            presentFragment(new LanguageSelectActivity());
        } else if (position == setUsernameRow) {
            presentFragment(new ChangeUsernameActivity());
        } else if (position == bioRow) {
            if (userInfo != null) {
                presentFragment(new ChangeBioActivity());
            }
        } else if (position == numberRow) {
            presentFragment(new ActionIntroActivity(ActionIntroActivity.ACTION_TYPE_CHANGE_PHONE_NUMBER));
        } else if (position == setAvatarRow) {
            onWriteButtonClick();
        } else {
            processOnClickOrPress(position, view);
        }
    });
    listView.setOnItemLongClickListener(new RecyclerListView.OnItemLongClickListener() {

        private int pressCount = 0;

        @Override
        public boolean onItemClick(View view, int position) {
            if (position == versionRow) {
                pressCount++;
                if (pressCount >= 2 || BuildVars.DEBUG_PRIVATE_VERSION) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                    builder.setTitle(LocaleController.getString("DebugMenu", R.string.DebugMenu));
                    CharSequence[] items;
                    items = new CharSequence[] { LocaleController.getString("DebugMenuImportContacts", R.string.DebugMenuImportContacts), LocaleController.getString("DebugMenuReloadContacts", R.string.DebugMenuReloadContacts), LocaleController.getString("DebugMenuResetContacts", R.string.DebugMenuResetContacts), LocaleController.getString("DebugMenuResetDialogs", R.string.DebugMenuResetDialogs), BuildVars.DEBUG_VERSION ? null : (BuildVars.LOGS_ENABLED ? LocaleController.getString("DebugMenuDisableLogs", R.string.DebugMenuDisableLogs) : LocaleController.getString("DebugMenuEnableLogs", R.string.DebugMenuEnableLogs)), SharedConfig.inappCamera ? LocaleController.getString("DebugMenuDisableCamera", R.string.DebugMenuDisableCamera) : LocaleController.getString("DebugMenuEnableCamera", R.string.DebugMenuEnableCamera), LocaleController.getString("DebugMenuClearMediaCache", R.string.DebugMenuClearMediaCache), LocaleController.getString("DebugMenuCallSettings", R.string.DebugMenuCallSettings), null, BuildVars.DEBUG_PRIVATE_VERSION || BuildVars.isStandaloneApp() ? LocaleController.getString("DebugMenuCheckAppUpdate", R.string.DebugMenuCheckAppUpdate) : null, LocaleController.getString("DebugMenuReadAllDialogs", R.string.DebugMenuReadAllDialogs), SharedConfig.pauseMusicOnRecord ? LocaleController.getString("DebugMenuDisablePauseMusic", R.string.DebugMenuDisablePauseMusic) : LocaleController.getString("DebugMenuEnablePauseMusic", R.string.DebugMenuEnablePauseMusic), BuildVars.DEBUG_VERSION && !AndroidUtilities.isTablet() && Build.VERSION.SDK_INT >= 23 ? (SharedConfig.smoothKeyboard ? LocaleController.getString("DebugMenuDisableSmoothKeyboard", R.string.DebugMenuDisableSmoothKeyboard) : LocaleController.getString("DebugMenuEnableSmoothKeyboard", R.string.DebugMenuEnableSmoothKeyboard)) : null, BuildVars.DEBUG_PRIVATE_VERSION ? (SharedConfig.disableVoiceAudioEffects ? "Enable voip audio effects" : "Disable voip audio effects") : null, Build.VERSION.SDK_INT >= 21 ? (SharedConfig.noStatusBar ? "Show status bar background" : "Hide status bar background") : null, BuildVars.DEBUG_PRIVATE_VERSION ? "Clean app update" : null, BuildVars.DEBUG_PRIVATE_VERSION ? "Reset suggestions" : null };
                    builder.setItems(items, (dialog, which) -> {
                        if (which == 0) {
                            getUserConfig().syncContacts = true;
                            getUserConfig().saveConfig(false);
                            getContactsController().forceImportContacts();
                        } else if (which == 1) {
                            getContactsController().loadContacts(false, 0);
                        } else if (which == 2) {
                            getContactsController().resetImportedContacts();
                        } else if (which == 3) {
                            getMessagesController().forceResetDialogs();
                        } else if (which == 4) {
                            BuildVars.LOGS_ENABLED = !BuildVars.LOGS_ENABLED;
                            SharedPreferences sharedPreferences = ApplicationLoader.applicationContext.getSharedPreferences("systemConfig", Context.MODE_PRIVATE);
                            sharedPreferences.edit().putBoolean("logsEnabled", BuildVars.LOGS_ENABLED).commit();
                            updateRowsIds();
                            listAdapter.notifyDataSetChanged();
                        } else if (which == 5) {
                            SharedConfig.toggleInappCamera();
                        } else if (which == 6) {
                            getMessagesStorage().clearSentMedia();
                            SharedConfig.setNoSoundHintShowed(false);
                            SharedPreferences.Editor editor = MessagesController.getGlobalMainSettings().edit();
                            editor.remove("archivehint").remove("proximityhint").remove("archivehint_l").remove("gifhint").remove("reminderhint").remove("soundHint").remove("themehint").remove("bganimationhint").remove("filterhint").commit();
                            MessagesController.getEmojiSettings(currentAccount).edit().remove("featured_hidden").commit();
                            SharedConfig.textSelectionHintShows = 0;
                            SharedConfig.lockRecordAudioVideoHint = 0;
                            SharedConfig.stickersReorderingHintUsed = false;
                            SharedConfig.forwardingOptionsHintShown = false;
                            SharedConfig.messageSeenHintCount = 3;
                            SharedConfig.emojiInteractionsHintCount = 3;
                            SharedConfig.dayNightThemeSwitchHintCount = 3;
                            SharedConfig.fastScrollHintCount = 3;
                            ChatThemeController.getInstance(currentAccount).clearCache();
                        } else if (which == 7) {
                            VoIPHelper.showCallDebugSettings(getParentActivity());
                        } else if (which == 8) {
                            SharedConfig.toggleRoundCamera16to9();
                        } else if (which == 9) {
                            ((LaunchActivity) getParentActivity()).checkAppUpdate(true);
                        } else if (which == 10) {
                            getMessagesStorage().readAllDialogs(-1);
                        } else if (which == 11) {
                            SharedConfig.togglePauseMusicOnRecord();
                        } else if (which == 12) {
                            SharedConfig.toggleSmoothKeyboard();
                            if (SharedConfig.smoothKeyboard && getParentActivity() != null) {
                                getParentActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                            }
                        } else if (which == 13) {
                            SharedConfig.toggleDisableVoiceAudioEffects();
                        } else if (which == 14) {
                            SharedConfig.toggleNoStatusBar();
                            if (getParentActivity() != null && Build.VERSION.SDK_INT >= 21) {
                                if (SharedConfig.noStatusBar) {
                                    getParentActivity().getWindow().setStatusBarColor(0);
                                } else {
                                    getParentActivity().getWindow().setStatusBarColor(0x33000000);
                                }
                            }
                        } else if (which == 15) {
                            SharedConfig.pendingAppUpdate = null;
                            SharedConfig.saveConfig();
                            NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.appUpdateAvailable);
                        } else if (which == 16) {
                            Set<String> suggestions = getMessagesController().pendingSuggestions;
                            suggestions.add("VALIDATE_PHONE_NUMBER");
                            suggestions.add("VALIDATE_PASSWORD");
                            getNotificationCenter().postNotificationName(NotificationCenter.newSuggestionsAvailable);
                        }
                    });
                    builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                    showDialog(builder.create());
                } else {
                    try {
                        Toast.makeText(getParentActivity(), "¯\\_(ツ)_/¯", Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        FileLog.e(e);
                    }
                }
                return true;
            } else if (position >= membersStartRow && position < membersEndRow) {
                final TLRPC.ChatParticipant participant;
                if (!sortedUsers.isEmpty()) {
                    participant = visibleChatParticipants.get(sortedUsers.get(position - membersStartRow));
                } else {
                    participant = visibleChatParticipants.get(position - membersStartRow);
                }
                return onMemberClick(participant, true);
            } else {
                return processOnClickOrPress(position, view);
            }
        }
    });
    if (searchItem != null) {
        searchListView = new RecyclerListView(context);
        searchListView.setVerticalScrollBarEnabled(false);
        searchListView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
        searchListView.setGlowColor(Theme.getColor(Theme.key_avatar_backgroundActionBarBlue));
        searchListView.setAdapter(searchAdapter);
        searchListView.setItemAnimator(null);
        searchListView.setVisibility(View.GONE);
        searchListView.setLayoutAnimation(null);
        searchListView.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
        frameLayout.addView(searchListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));
        searchListView.setOnItemClickListener((view, position) -> {
            if (position < 0) {
                return;
            }
            Object object = numberRow;
            boolean add = true;
            if (searchAdapter.searchWas) {
                if (position < searchAdapter.searchResults.size()) {
                    object = searchAdapter.searchResults.get(position);
                } else {
                    position -= searchAdapter.searchResults.size() + 1;
                    if (position >= 0 && position < searchAdapter.faqSearchResults.size()) {
                        object = searchAdapter.faqSearchResults.get(position);
                    }
                }
            } else {
                if (!searchAdapter.recentSearches.isEmpty()) {
                    position--;
                }
                if (position >= 0 && position < searchAdapter.recentSearches.size()) {
                    object = searchAdapter.recentSearches.get(position);
                } else {
                    position -= searchAdapter.recentSearches.size() + 1;
                    if (position >= 0 && position < searchAdapter.faqSearchArray.size()) {
                        object = searchAdapter.faqSearchArray.get(position);
                        add = false;
                    }
                }
            }
            if (object instanceof SearchAdapter.SearchResult) {
                SearchAdapter.SearchResult result = (SearchAdapter.SearchResult) object;
                result.open();
            } else if (object instanceof MessagesController.FaqSearchResult) {
                MessagesController.FaqSearchResult result = (MessagesController.FaqSearchResult) object;
                NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.openArticle, searchAdapter.faqWebPage, result.url);
            }
            if (add && object != null) {
                searchAdapter.addRecent(object);
            }
        });
        searchListView.setOnItemLongClickListener((view, position) -> {
            if (searchAdapter.isSearchWas() || searchAdapter.recentSearches.isEmpty()) {
                return false;
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
            builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
            builder.setMessage(LocaleController.getString("ClearSearch", R.string.ClearSearch));
            builder.setPositiveButton(LocaleController.getString("ClearButton", R.string.ClearButton).toUpperCase(), (dialogInterface, i) -> searchAdapter.clearRecent());
            builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
            showDialog(builder.create());
            return true;
        });
        searchListView.setOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                    AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus());
                }
            }
        });
        searchListView.setAnimateEmptyView(true, 1);
        emptyView = new StickerEmptyView(context, null, 1);
        emptyView.setAnimateLayoutChange(true);
        emptyView.subtitle.setVisibility(View.GONE);
        emptyView.setVisibility(View.GONE);
        frameLayout.addView(emptyView);
        searchAdapter.loadFaqWebPage();
    }
    if (banFromGroup != 0) {
        TLRPC.Chat chat = getMessagesController().getChat(banFromGroup);
        if (currentChannelParticipant == null) {
            TLRPC.TL_channels_getParticipant req = new TLRPC.TL_channels_getParticipant();
            req.channel = MessagesController.getInputChannel(chat);
            req.participant = getMessagesController().getInputPeer(userId);
            getConnectionsManager().sendRequest(req, (response, error) -> {
                if (response != null) {
                    AndroidUtilities.runOnUIThread(() -> currentChannelParticipant = ((TLRPC.TL_channels_channelParticipant) response).participant);
                }
            });
        }
        FrameLayout frameLayout1 = new FrameLayout(context) {

            @Override
            protected void onDraw(Canvas canvas) {
                int bottom = Theme.chat_composeShadowDrawable.getIntrinsicHeight();
                Theme.chat_composeShadowDrawable.setBounds(0, 0, getMeasuredWidth(), bottom);
                Theme.chat_composeShadowDrawable.draw(canvas);
                canvas.drawRect(0, bottom, getMeasuredWidth(), getMeasuredHeight(), Theme.chat_composeBackgroundPaint);
            }
        };
        frameLayout1.setWillNotDraw(false);
        frameLayout.addView(frameLayout1, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.LEFT | Gravity.BOTTOM));
        frameLayout1.setOnClickListener(v -> {
            ChatRightsEditActivity fragment = new ChatRightsEditActivity(userId, banFromGroup, null, chat.default_banned_rights, currentChannelParticipant != null ? currentChannelParticipant.banned_rights : null, "", ChatRightsEditActivity.TYPE_BANNED, true, false);
            fragment.setDelegate(new ChatRightsEditActivity.ChatRightsEditActivityDelegate() {

                @Override
                public void didSetRights(int rights, TLRPC.TL_chatAdminRights rightsAdmin, TLRPC.TL_chatBannedRights rightsBanned, String rank) {
                    removeSelfFromStack();
                }

                @Override
                public void didChangeOwner(TLRPC.User user) {
                    undoView.showWithAction(-chatId, currentChat.megagroup ? UndoView.ACTION_OWNER_TRANSFERED_GROUP : UndoView.ACTION_OWNER_TRANSFERED_CHANNEL, user);
                }
            });
            presentFragment(fragment);
        });
        TextView textView = new TextView(context);
        textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteRedText));
        textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
        textView.setGravity(Gravity.CENTER);
        textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
        textView.setText(LocaleController.getString("BanFromTheGroup", R.string.BanFromTheGroup));
        frameLayout1.addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 1, 0, 0));
        listView.setPadding(0, AndroidUtilities.dp(88), 0, AndroidUtilities.dp(48));
        listView.setBottomGlowOffset(AndroidUtilities.dp(48));
    } else {
        listView.setPadding(0, AndroidUtilities.dp(88), 0, 0);
    }
    topView = new TopView(context);
    topView.setBackgroundColor(Theme.getColor(Theme.key_avatar_backgroundActionBarBlue));
    frameLayout.addView(topView);
    avatarContainer = new FrameLayout(context);
    avatarContainer2 = new FrameLayout(context) {

        @Override
        protected void dispatchDraw(Canvas canvas) {
            super.dispatchDraw(canvas);
            if (transitionOnlineText != null) {
                canvas.save();
                canvas.translate(onlineTextView[0].getX(), onlineTextView[0].getY());
                canvas.saveLayerAlpha(0, 0, transitionOnlineText.getMeasuredWidth(), transitionOnlineText.getMeasuredHeight(), (int) (255 * (1f - animationProgress)), Canvas.ALL_SAVE_FLAG);
                transitionOnlineText.draw(canvas);
                canvas.restore();
                canvas.restore();
                invalidate();
            }
        }
    };
    AndroidUtilities.updateViewVisibilityAnimated(avatarContainer2, true, 1f, false);
    frameLayout.addView(avatarContainer2, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.START, 0, 0, 0, 0));
    avatarContainer.setPivotX(0);
    avatarContainer.setPivotY(0);
    avatarContainer2.addView(avatarContainer, LayoutHelper.createFrame(42, 42, Gravity.TOP | Gravity.LEFT, 64, 0, 0, 0));
    avatarImage = new AvatarImageView(context) {

        @Override
        public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
            super.onInitializeAccessibilityNodeInfo(info);
            if (getImageReceiver().hasNotThumb()) {
                info.setText(LocaleController.getString("AccDescrProfilePicture", R.string.AccDescrProfilePicture));
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    info.addAction(new AccessibilityNodeInfo.AccessibilityAction(AccessibilityNodeInfo.ACTION_CLICK, LocaleController.getString("Open", R.string.Open)));
                    info.addAction(new AccessibilityNodeInfo.AccessibilityAction(AccessibilityNodeInfo.ACTION_LONG_CLICK, LocaleController.getString("AccDescrOpenInPhotoViewer", R.string.AccDescrOpenInPhotoViewer)));
                }
            } else {
                info.setVisibleToUser(false);
            }
        }
    };
    avatarImage.getImageReceiver().setAllowDecodeSingleFrame(true);
    avatarImage.setRoundRadius(AndroidUtilities.dp(21));
    avatarImage.setPivotX(0);
    avatarImage.setPivotY(0);
    avatarContainer.addView(avatarImage, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    avatarImage.setOnClickListener(v -> {
        if (avatarBig != null) {
            return;
        }
        if (!AndroidUtilities.isTablet() && !isInLandscapeMode && avatarImage.getImageReceiver().hasNotThumb()) {
            openingAvatar = true;
            allowPullingDown = true;
            View child = null;
            for (int i = 0; i < listView.getChildCount(); i++) {
                if (listView.getChildAdapterPosition(listView.getChildAt(i)) == 0) {
                    child = listView.getChildAt(i);
                    break;
                }
            }
            if (child != null) {
                RecyclerView.ViewHolder holder = listView.findContainingViewHolder(child);
                if (holder != null) {
                    Integer offset = positionToOffset.get(holder.getAdapterPosition());
                    if (offset != null) {
                        listView.smoothScrollBy(0, -(offset + (listView.getPaddingTop() - child.getTop() - actionBar.getMeasuredHeight())), CubicBezierInterpolator.EASE_OUT_QUINT);
                        return;
                    }
                }
            }
        }
        openAvatar();
    });
    avatarImage.setOnLongClickListener(v -> {
        if (avatarBig != null) {
            return false;
        }
        openAvatar();
        return false;
    });
    avatarProgressView = new RadialProgressView(context) {

        private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

        {
            paint.setColor(0x55000000);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            if (avatarImage != null && avatarImage.getImageReceiver().hasNotThumb()) {
                paint.setAlpha((int) (0x55 * avatarImage.getImageReceiver().getCurrentAlpha()));
                canvas.drawCircle(getMeasuredWidth() / 2.0f, getMeasuredHeight() / 2.0f, getMeasuredWidth() / 2.0f, paint);
            }
            super.onDraw(canvas);
        }
    };
    avatarProgressView.setSize(AndroidUtilities.dp(26));
    avatarProgressView.setProgressColor(0xffffffff);
    avatarProgressView.setNoProgress(false);
    avatarContainer.addView(avatarProgressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    timeItem = new ImageView(context);
    timeItem.setPadding(AndroidUtilities.dp(10), AndroidUtilities.dp(10), AndroidUtilities.dp(5), AndroidUtilities.dp(5));
    timeItem.setScaleType(ImageView.ScaleType.CENTER);
    timeItem.setAlpha(0.0f);
    timeItem.setImageDrawable(timerDrawable = new TimerDrawable(context));
    frameLayout.addView(timeItem, LayoutHelper.createFrame(34, 34, Gravity.TOP | Gravity.LEFT));
    updateTimeItem();
    showAvatarProgress(false, false);
    if (avatarsViewPager != null) {
        avatarsViewPager.onDestroy();
    }
    overlaysView = new OverlaysView(context);
    avatarsViewPager = new ProfileGalleryView(context, userId != 0 ? userId : -chatId, actionBar, listView, avatarImage, getClassGuid(), overlaysView);
    avatarsViewPager.setChatInfo(chatInfo);
    avatarContainer2.addView(avatarsViewPager);
    avatarContainer2.addView(overlaysView);
    avatarImage.setAvatarsViewPager(avatarsViewPager);
    avatarsViewPagerIndicatorView = new PagerIndicatorView(context);
    avatarContainer2.addView(avatarsViewPagerIndicatorView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    frameLayout.addView(actionBar);
    for (int a = 0; a < nameTextView.length; a++) {
        if (playProfileAnimation == 0 && a == 0) {
            continue;
        }
        nameTextView[a] = new SimpleTextView(context);
        if (a == 1) {
            nameTextView[a].setTextColor(Theme.getColor(Theme.key_profile_title));
        } else {
            nameTextView[a].setTextColor(Theme.getColor(Theme.key_actionBarDefaultTitle));
        }
        nameTextView[a].setTextSize(18);
        nameTextView[a].setGravity(Gravity.LEFT);
        nameTextView[a].setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
        nameTextView[a].setLeftDrawableTopPadding(-AndroidUtilities.dp(1.3f));
        nameTextView[a].setPivotX(0);
        nameTextView[a].setPivotY(0);
        nameTextView[a].setAlpha(a == 0 ? 0.0f : 1.0f);
        if (a == 1) {
            nameTextView[a].setScrollNonFitText(true);
            nameTextView[a].setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
        }
        int rightMargin = a == 0 ? (48 + ((callItemVisible && userId != 0) ? 48 : 0)) : 0;
        avatarContainer2.addView(nameTextView[a], LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 118, 0, rightMargin, 0));
    }
    for (int a = 0; a < onlineTextView.length; a++) {
        onlineTextView[a] = new SimpleTextView(context);
        onlineTextView[a].setTextColor(Theme.getColor(Theme.key_avatar_subtitleInProfileBlue));
        onlineTextView[a].setTextSize(14);
        onlineTextView[a].setGravity(Gravity.LEFT);
        onlineTextView[a].setAlpha(a == 0 || a == 2 ? 0.0f : 1.0f);
        if (a > 0) {
            onlineTextView[a].setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
        }
        avatarContainer2.addView(onlineTextView[a], LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 118, 0, a == 0 ? 48 : 8, 0));
    }
    mediaCounterTextView = new AudioPlayerAlert.ClippingTextViewSwitcher(context) {

        @Override
        protected TextView createTextView() {
            TextView textView = new TextView(context);
            textView.setTextColor(Theme.getColor(Theme.key_player_actionBarSubtitle));
            textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
            textView.setSingleLine(true);
            textView.setEllipsize(TextUtils.TruncateAt.END);
            textView.setGravity(Gravity.LEFT);
            return textView;
        }
    };
    mediaCounterTextView.setAlpha(0.0f);
    avatarContainer2.addView(mediaCounterTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 118, 0, 8, 0));
    updateProfileData();
    writeButton = new RLottieImageView(context);
    Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow_profile).mutate();
    shadowDrawable.setColorFilter(new PorterDuffColorFilter(Color.BLACK, PorterDuff.Mode.MULTIPLY));
    CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(56), Theme.getColor(Theme.key_profile_actionBackground), Theme.getColor(Theme.key_profile_actionPressedBackground)), 0, 0);
    combinedDrawable.setIconSize(AndroidUtilities.dp(56), AndroidUtilities.dp(56));
    writeButton.setBackground(combinedDrawable);
    if (userId != 0) {
        if (imageUpdater != null) {
            cameraDrawable = new RLottieDrawable(R.raw.camera_outline, "" + R.raw.camera_outline, AndroidUtilities.dp(56), AndroidUtilities.dp(56), false, null);
            writeButton.setAnimation(cameraDrawable);
            writeButton.setContentDescription(LocaleController.getString("AccDescrChangeProfilePicture", R.string.AccDescrChangeProfilePicture));
            writeButton.setPadding(AndroidUtilities.dp(2), 0, 0, AndroidUtilities.dp(2));
        } else {
            writeButton.setImageResource(R.drawable.profile_newmsg);
            writeButton.setContentDescription(LocaleController.getString("AccDescrOpenChat", R.string.AccDescrOpenChat));
        }
    } else {
        writeButton.setImageResource(R.drawable.profile_discuss);
        writeButton.setContentDescription(LocaleController.getString("ViewDiscussion", R.string.ViewDiscussion));
    }
    writeButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_profile_actionIcon), PorterDuff.Mode.MULTIPLY));
    writeButton.setScaleType(ImageView.ScaleType.CENTER);
    frameLayout.addView(writeButton, LayoutHelper.createFrame(60, 60, Gravity.RIGHT | Gravity.TOP, 0, 0, 16, 0));
    writeButton.setOnClickListener(v -> {
        if (writeButton.getTag() != null) {
            return;
        }
        onWriteButtonClick();
    });
    needLayout(false);
    if (scrollTo != -1) {
        if (writeButtonTag != null) {
            writeButton.setTag(0);
            writeButton.setScaleX(0.2f);
            writeButton.setScaleY(0.2f);
            writeButton.setAlpha(0.0f);
        }
    }
    listView.setOnScrollListener(new RecyclerView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus());
            }
            if (openingAvatar && newState != RecyclerView.SCROLL_STATE_SETTLING) {
                openingAvatar = false;
            }
            if (searchItem != null) {
                scrolling = newState != RecyclerView.SCROLL_STATE_IDLE;
                searchItem.setEnabled(!scrolling && !isPulledDown);
            }
            sharedMediaLayout.scrollingByUser = listView.scrollingByUser;
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            if (fwdRestrictedHint != null) {
                fwdRestrictedHint.hide();
            }
            checkListViewScroll();
            if (participantsMap != null && !usersEndReached && layoutManager.findLastVisibleItemPosition() > membersEndRow - 8) {
                getChannelParticipants(false);
            }
            sharedMediaLayout.setPinnedToTop(sharedMediaLayout.getY() == 0);
        }
    });
    undoView = new UndoView(context);
    frameLayout.addView(undoView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 8, 0, 8, 8));
    expandAnimator = ValueAnimator.ofFloat(0f, 1f);
    expandAnimator.addUpdateListener(anim -> {
        final int newTop = ActionBar.getCurrentActionBarHeight() + (actionBar.getOccupyStatusBar() ? AndroidUtilities.statusBarHeight : 0);
        final float value = AndroidUtilities.lerp(expandAnimatorValues, currentExpanAnimatorFracture = anim.getAnimatedFraction());
        avatarContainer.setScaleX(avatarScale);
        avatarContainer.setScaleY(avatarScale);
        avatarContainer.setTranslationX(AndroidUtilities.lerp(avatarX, 0f, value));
        avatarContainer.setTranslationY(AndroidUtilities.lerp((float) Math.ceil(avatarY), 0f, value));
        avatarImage.setRoundRadius((int) AndroidUtilities.lerp(AndroidUtilities.dpf2(21f), 0f, value));
        if (searchItem != null) {
            searchItem.setAlpha(1.0f - value);
            searchItem.setScaleY(1.0f - value);
            searchItem.setVisibility(View.VISIBLE);
            searchItem.setClickable(searchItem.getAlpha() > .5f);
            if (qrItem != null) {
                float translation = AndroidUtilities.dp(48) * value;
                // if (searchItem.getVisibility() == View.VISIBLE)
                // translation += AndroidUtilities.dp(48);
                qrItem.setTranslationX(translation);
                avatarsViewPagerIndicatorView.setTranslationX(translation - AndroidUtilities.dp(48));
            }
        }
        if (extraHeight > AndroidUtilities.dp(88f) && expandProgress < 0.33f) {
            refreshNameAndOnlineXY();
        }
        if (scamDrawable != null) {
            scamDrawable.setColor(ColorUtils.blendARGB(Theme.getColor(Theme.key_avatar_subtitleInProfileBlue), Color.argb(179, 255, 255, 255), value));
        }
        if (lockIconDrawable != null) {
            lockIconDrawable.setColorFilter(ColorUtils.blendARGB(Theme.getColor(Theme.key_chat_lockIcon), Color.WHITE, value), PorterDuff.Mode.MULTIPLY);
        }
        if (verifiedCrossfadeDrawable != null) {
            verifiedCrossfadeDrawable.setProgress(value);
        }
        final float k = AndroidUtilities.dpf2(8f);
        final float nameTextViewXEnd = AndroidUtilities.dpf2(16f) - nameTextView[1].getLeft();
        final float nameTextViewYEnd = newTop + extraHeight - AndroidUtilities.dpf2(38f) - nameTextView[1].getBottom();
        final float nameTextViewCx = k + nameX + (nameTextViewXEnd - nameX) / 2f;
        final float nameTextViewCy = k + nameY + (nameTextViewYEnd - nameY) / 2f;
        final float nameTextViewX = (1 - value) * (1 - value) * nameX + 2 * (1 - value) * value * nameTextViewCx + value * value * nameTextViewXEnd;
        final float nameTextViewY = (1 - value) * (1 - value) * nameY + 2 * (1 - value) * value * nameTextViewCy + value * value * nameTextViewYEnd;
        final float onlineTextViewXEnd = AndroidUtilities.dpf2(16f) - onlineTextView[1].getLeft();
        final float onlineTextViewYEnd = newTop + extraHeight - AndroidUtilities.dpf2(18f) - onlineTextView[1].getBottom();
        final float onlineTextViewCx = k + onlineX + (onlineTextViewXEnd - onlineX) / 2f;
        final float onlineTextViewCy = k + onlineY + (onlineTextViewYEnd - onlineY) / 2f;
        final float onlineTextViewX = (1 - value) * (1 - value) * onlineX + 2 * (1 - value) * value * onlineTextViewCx + value * value * onlineTextViewXEnd;
        final float onlineTextViewY = (1 - value) * (1 - value) * onlineY + 2 * (1 - value) * value * onlineTextViewCy + value * value * onlineTextViewYEnd;
        nameTextView[1].setTranslationX(nameTextViewX);
        nameTextView[1].setTranslationY(nameTextViewY);
        onlineTextView[1].setTranslationX(onlineTextViewX);
        onlineTextView[1].setTranslationY(onlineTextViewY);
        mediaCounterTextView.setTranslationX(onlineTextViewX);
        mediaCounterTextView.setTranslationY(onlineTextViewY);
        final Object onlineTextViewTag = onlineTextView[1].getTag();
        int statusColor;
        if (onlineTextViewTag instanceof String) {
            statusColor = Theme.getColor((String) onlineTextViewTag);
        } else {
            statusColor = Theme.getColor(Theme.key_avatar_subtitleInProfileBlue);
        }
        onlineTextView[1].setTextColor(ColorUtils.blendARGB(statusColor, Color.argb(179, 255, 255, 255), value));
        if (extraHeight > AndroidUtilities.dp(88f)) {
            nameTextView[1].setPivotY(AndroidUtilities.lerp(0, nameTextView[1].getMeasuredHeight(), value));
            nameTextView[1].setScaleX(AndroidUtilities.lerp(1.12f, 1.67f, value));
            nameTextView[1].setScaleY(AndroidUtilities.lerp(1.12f, 1.67f, value));
        }
        needLayoutText(Math.min(1f, extraHeight / AndroidUtilities.dp(88f)));
        nameTextView[1].setTextColor(ColorUtils.blendARGB(Theme.getColor(Theme.key_profile_title), Color.WHITE, value));
        actionBar.setItemsColor(ColorUtils.blendARGB(Theme.getColor(Theme.key_actionBarDefaultIcon), Color.WHITE, value), false);
        avatarImage.setForegroundAlpha(value);
        final FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) avatarContainer.getLayoutParams();
        params.width = (int) AndroidUtilities.lerp(AndroidUtilities.dpf2(42f), listView.getMeasuredWidth() / avatarScale, value);
        params.height = (int) AndroidUtilities.lerp(AndroidUtilities.dpf2(42f), (extraHeight + newTop) / avatarScale, value);
        params.leftMargin = (int) AndroidUtilities.lerp(AndroidUtilities.dpf2(64f), 0f, value);
        avatarContainer.requestLayout();
    });
    expandAnimator.setInterpolator(CubicBezierInterpolator.EASE_BOTH);
    expandAnimator.addListener(new AnimatorListenerAdapter() {

        @Override
        public void onAnimationStart(Animator animation) {
        }

        @Override
        public void onAnimationEnd(Animator animation) {
            actionBar.setItemsBackgroundColor(isPulledDown ? Theme.ACTION_BAR_WHITE_SELECTOR_COLOR : Theme.getColor(Theme.key_avatar_actionBarSelectorBlue), false);
            avatarImage.clearForeground();
            doNotSetForeground = false;
        }
    });
    updateRowsIds();
    updateSelectedMediaTabText();
    fwdRestrictedHint = new HintView(getParentActivity(), 9);
    fwdRestrictedHint.setAlpha(0);
    frameLayout.addView(fwdRestrictedHint, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 12, 0, 12, 0));
    sharedMediaLayout.setForwardRestrictedHint(fwdRestrictedHint);
    ViewGroup decorView;
    if (Build.VERSION.SDK_INT >= 21) {
        decorView = (ViewGroup) getParentActivity().getWindow().getDecorView();
    } else {
        decorView = frameLayout;
    }
    pinchToZoomHelper = new PinchToZoomHelper(decorView, frameLayout) {

        Paint statusBarPaint;

        @Override
        protected void invalidateViews() {
            super.invalidateViews();
            fragmentView.invalidate();
            for (int i = 0; i < avatarsViewPager.getChildCount(); i++) {
                avatarsViewPager.getChildAt(i).invalidate();
            }
            if (writeButton != null) {
                writeButton.invalidate();
            }
        }

        @Override
        protected void drawOverlays(Canvas canvas, float alpha, float parentOffsetX, float parentOffsetY, float clipTop, float clipBottom) {
            if (alpha > 0) {
                AndroidUtilities.rectTmp.set(0, 0, avatarsViewPager.getMeasuredWidth(), avatarsViewPager.getMeasuredHeight() + AndroidUtilities.dp(30));
                canvas.saveLayerAlpha(AndroidUtilities.rectTmp, (int) (255 * alpha), Canvas.ALL_SAVE_FLAG);
                avatarContainer2.draw(canvas);
                if (actionBar.getOccupyStatusBar()) {
                    if (statusBarPaint == null) {
                        statusBarPaint = new Paint();
                        statusBarPaint.setColor(ColorUtils.setAlphaComponent(Color.BLACK, (int) (255 * 0.2f)));
                    }
                    canvas.drawRect(actionBar.getX(), actionBar.getY(), actionBar.getX() + actionBar.getMeasuredWidth(), actionBar.getY() + AndroidUtilities.statusBarHeight, statusBarPaint);
                }
                canvas.save();
                canvas.translate(actionBar.getX(), actionBar.getY());
                actionBar.draw(canvas);
                canvas.restore();
                if (writeButton != null && writeButton.getVisibility() == View.VISIBLE && writeButton.getAlpha() > 0) {
                    canvas.save();
                    float s = 0.5f + 0.5f * alpha;
                    canvas.scale(s, s, writeButton.getX() + writeButton.getMeasuredWidth() / 2f, writeButton.getY() + writeButton.getMeasuredHeight() / 2f);
                    canvas.translate(writeButton.getX(), writeButton.getY());
                    writeButton.draw(canvas);
                    canvas.restore();
                }
                canvas.restore();
            }
        }

        @Override
        protected boolean zoomEnabled(View child, ImageReceiver receiver) {
            if (!super.zoomEnabled(child, receiver)) {
                return false;
            }
            return listView.getScrollState() != RecyclerView.SCROLL_STATE_DRAGGING;
        }
    };
    pinchToZoomHelper.setCallback(new PinchToZoomHelper.Callback() {

        @Override
        public void onZoomStarted(MessageObject messageObject) {
            listView.cancelClickRunnables(true);
            if (sharedMediaLayout != null && sharedMediaLayout.getCurrentListView() != null) {
                sharedMediaLayout.getCurrentListView().cancelClickRunnables(true);
            }
            Bitmap bitmap = pinchToZoomHelper.getPhotoImage() == null ? null : pinchToZoomHelper.getPhotoImage().getBitmap();
            if (bitmap != null) {
                topView.setBackgroundColor(ColorUtils.blendARGB(AndroidUtilities.calcBitmapColor(bitmap), Theme.getColor(Theme.key_windowBackgroundWhite), 0.1f));
            }
        }
    });
    avatarsViewPager.setPinchToZoomHelper(pinchToZoomHelper);
    scrimPaint.setAlpha(0);
    actionBarBackgroundPaint.setColor(Theme.getColor(Theme.key_listSelector));
    return fragmentView;
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) Arrays(java.util.Arrays) Bundle(android.os.Bundle) BufferedInputStream(java.io.BufferedInputStream) SettingsSuggestionCell(org.telegram.ui.Cells.SettingsSuggestionCell) Uri(android.net.Uri) FrameLayout(android.widget.FrameLayout) ImageView(android.widget.ImageView) AnimatedFileDrawable(org.telegram.ui.Components.AnimatedFileDrawable) ColorDrawable(android.graphics.drawable.ColorDrawable) Drawable(android.graphics.drawable.Drawable) Property(android.util.Property) AvatarDrawable(org.telegram.ui.Components.AvatarDrawable) RadialProgressView(org.telegram.ui.Components.RadialProgressView) Manifest(android.Manifest) Keep(androidx.annotation.Keep) ChatThemeController(org.telegram.messenger.ChatThemeController) ProfileGalleryView(org.telegram.ui.Components.ProfileGalleryView) NotificationsCheckCell(org.telegram.ui.Cells.NotificationsCheckCell) Display(android.view.Display) Canvas(android.graphics.Canvas) ForegroundColorSpan(android.text.style.ForegroundColorSpan) ContextCompat(androidx.core.content.ContextCompat) NotificationsController(org.telegram.messenger.NotificationsController) ViewCompat(androidx.core.view.ViewCompat) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) BackButtonMenu(org.telegram.ui.Components.BackButtonMenu) UndoView(org.telegram.ui.Components.UndoView) AnimationProperties(org.telegram.ui.Components.AnimationProperties) Set(java.util.Set) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) NotificationCenter(org.telegram.messenger.NotificationCenter) HapticFeedbackConstants(android.view.HapticFeedbackConstants) CountDownLatch(java.util.concurrent.CountDownLatch) TextPaint(android.text.TextPaint) HintView(org.telegram.ui.Components.HintView) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) Paint(android.graphics.Paint) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) DividerCell(org.telegram.ui.Cells.DividerCell) StickerEmptyView(org.telegram.ui.Components.StickerEmptyView) FileLoader(org.telegram.messenger.FileLoader) ZipOutputStream(java.util.zip.ZipOutputStream) ViewPager(androidx.viewpager.widget.ViewPager) Dialog(android.app.Dialog) SystemClock(android.os.SystemClock) TimerDrawable(org.telegram.ui.Components.TimerDrawable) SettingsSearchCell(org.telegram.ui.Cells.SettingsSearchCell) AlertsCreator(org.telegram.ui.Components.AlertsCreator) TextInfoPrivacyCell(org.telegram.ui.Cells.TextInfoPrivacyCell) BufferedOutputStream(java.io.BufferedOutputStream) ArrayList(java.util.ArrayList) SpannableStringBuilder(android.text.SpannableStringBuilder) SharedMediaLayout(org.telegram.ui.Components.SharedMediaLayout) FragmentContextView(org.telegram.ui.Components.FragmentContextView) TLRPC(org.telegram.tgnet.TLRPC) GradientDrawable(android.graphics.drawable.GradientDrawable) Toast(android.widget.Toast) PhoneFormat(org.telegram.PhoneFormat.PhoneFormat) IdenticonDrawable(org.telegram.ui.Components.IdenticonDrawable) BuildConfig(org.telegram.messenger.BuildConfig) AccelerateInterpolator(android.view.animation.AccelerateInterpolator) LinkedHashSet(java.util.LinkedHashSet) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) UserCell(org.telegram.ui.Cells.UserCell) R(org.telegram.messenger.R) FileOutputStream(java.io.FileOutputStream) TextUtils(android.text.TextUtils) AboutLinkCell(org.telegram.ui.Cells.AboutLinkCell) File(java.io.File) Gravity(android.view.Gravity) UserObject(org.telegram.messenger.UserObject) SharedPreferences(android.content.SharedPreferences) TypedValue(android.util.TypedValue) ContactsController(org.telegram.messenger.ContactsController) GraySectionCell(org.telegram.ui.Cells.GraySectionCell) Configuration(android.content.res.Configuration) ColorUtils(androidx.core.graphics.ColorUtils) ChatObject(org.telegram.messenger.ChatObject) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) AudioPlayerAlert(org.telegram.ui.Components.AudioPlayerAlert) VoIPHelper(org.telegram.ui.Components.voip.VoIPHelper) EditText(android.widget.EditText) ValueAnimator(android.animation.ValueAnimator) ThemeDescription(org.telegram.ui.ActionBar.ThemeDescription) Rect(android.graphics.Rect) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) ImageUpdater(org.telegram.ui.Components.ImageUpdater) PackageManager(android.content.pm.PackageManager) WindowManager(android.view.WindowManager) AndroidUtilities(org.telegram.messenger.AndroidUtilities) CubicBezierInterpolator(org.telegram.ui.Components.CubicBezierInterpolator) CrossfadeDrawable(org.telegram.ui.Components.CrossfadeDrawable) Animator(android.animation.Animator) ShadowSectionCell(org.telegram.ui.Cells.ShadowSectionCell) ApplicationLoader(org.telegram.messenger.ApplicationLoader) TextCell(org.telegram.ui.Cells.TextCell) Locale(java.util.Locale) MediaController(org.telegram.messenger.MediaController) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) DataSetObserver(android.database.DataSetObserver) ZipEntry(java.util.zip.ZipEntry) RectF(android.graphics.RectF) ImageLoader(org.telegram.messenger.ImageLoader) Utilities(org.telegram.messenger.Utilities) DiffUtil(androidx.recyclerview.widget.DiffUtil) RLottieImageView(org.telegram.ui.Components.RLottieImageView) ObjectAnimator(android.animation.ObjectAnimator) ImageLocation(org.telegram.messenger.ImageLocation) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) PorterDuff(android.graphics.PorterDuff) ConnectionsManager(org.telegram.tgnet.ConnectionsManager) BackDrawable(org.telegram.ui.ActionBar.BackDrawable) ViewGroup(android.view.ViewGroup) DefaultItemAnimator(androidx.recyclerview.widget.DefaultItemAnimator) UserConfig(org.telegram.messenger.UserConfig) TextView(android.widget.TextView) ScamDrawable(org.telegram.ui.Components.ScamDrawable) FileProvider(androidx.core.content.FileProvider) DecelerateInterpolator(android.view.animation.DecelerateInterpolator) ActionBarPopupWindow(org.telegram.ui.ActionBar.ActionBarPopupWindow) Typeface(android.graphics.Typeface) NestedScrollingParentHelper(androidx.core.view.NestedScrollingParentHelper) Context(android.content.Context) AccessibilityNodeInfo(android.view.accessibility.AccessibilityNodeInfo) Spanned(android.text.Spanned) SparseIntArray(android.util.SparseIntArray) Theme(org.telegram.ui.ActionBar.Theme) TextDetailCell(org.telegram.ui.Cells.TextDetailCell) PagerAdapter(androidx.viewpager.widget.PagerAdapter) 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) HeaderCell(org.telegram.ui.Cells.HeaderCell) PackageInfo(android.content.pm.PackageInfo) HashSet(java.util.HashSet) VelocityTracker(android.view.VelocityTracker) MotionEvent(android.view.MotionEvent) NestedScrollingParent3(androidx.core.view.NestedScrollingParent3) ActionBar(org.telegram.ui.ActionBar.ActionBar) TLObject(org.telegram.tgnet.TLObject) AnimatorSet(android.animation.AnimatorSet) MessageObject(org.telegram.messenger.MessageObject) SharedConfig(org.telegram.messenger.SharedConfig) BuildVars(org.telegram.messenger.BuildVars) MediaDataController(org.telegram.messenger.MediaDataController) Build(android.os.Build) SerializedData(org.telegram.tgnet.SerializedData) DialogInterface(android.content.DialogInterface) Browser(org.telegram.messenger.browser.Browser) ChatAvatarContainer(org.telegram.ui.Components.ChatAvatarContainer) 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) FileInputStream(java.io.FileInputStream) FileLog(org.telegram.messenger.FileLog) MessagesController(org.telegram.messenger.MessagesController) Color(android.graphics.Color) Bitmap(android.graphics.Bitmap) ViewTreeObserver(android.view.ViewTreeObserver) Comparator(java.util.Comparator) ImageReceiver(org.telegram.messenger.ImageReceiver) Collections(java.util.Collections) RecyclerListView(org.telegram.ui.Components.RecyclerListView) RLottieDrawable(org.telegram.ui.Components.RLottieDrawable) ArrayList(java.util.ArrayList) AboutLinkCell(org.telegram.ui.Cells.AboutLinkCell) DefaultItemAnimator(androidx.recyclerview.widget.DefaultItemAnimator) EditText(android.widget.EditText) AnimatedFileDrawable(org.telegram.ui.Components.AnimatedFileDrawable) ColorDrawable(android.graphics.drawable.ColorDrawable) Drawable(android.graphics.drawable.Drawable) AvatarDrawable(org.telegram.ui.Components.AvatarDrawable) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) TimerDrawable(org.telegram.ui.Components.TimerDrawable) GradientDrawable(android.graphics.drawable.GradientDrawable) IdenticonDrawable(org.telegram.ui.Components.IdenticonDrawable) CrossfadeDrawable(org.telegram.ui.Components.CrossfadeDrawable) BackDrawable(org.telegram.ui.ActionBar.BackDrawable) ScamDrawable(org.telegram.ui.Components.ScamDrawable) RLottieDrawable(org.telegram.ui.Components.RLottieDrawable) UserConfig(org.telegram.messenger.UserConfig) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) UserObject(org.telegram.messenger.UserObject) ChatObject(org.telegram.messenger.ChatObject) TLObject(org.telegram.tgnet.TLObject) MessageObject(org.telegram.messenger.MessageObject) DialogObject(org.telegram.messenger.DialogObject) Set(java.util.Set) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) AnimatorSet(android.animation.AnimatorSet) ProfileGalleryView(org.telegram.ui.Components.ProfileGalleryView) MessagesController(org.telegram.messenger.MessagesController) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) RecyclerListView(org.telegram.ui.Components.RecyclerListView) ImageLocation(org.telegram.messenger.ImageLocation) UndoView(org.telegram.ui.Components.UndoView) VelocityTracker(android.view.VelocityTracker) SharedPreferences(android.content.SharedPreferences) AccessibilityNodeInfo(android.view.accessibility.AccessibilityNodeInfo) Intent(android.content.Intent) ValueAnimator(android.animation.ValueAnimator) Animator(android.animation.Animator) ObjectAnimator(android.animation.ObjectAnimator) DefaultItemAnimator(androidx.recyclerview.widget.DefaultItemAnimator) RecyclerView(androidx.recyclerview.widget.RecyclerView) SpannableStringBuilder(android.text.SpannableStringBuilder) RLottieDrawable(org.telegram.ui.Components.RLottieDrawable) ValueAnimator(android.animation.ValueAnimator) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) TLRPC(org.telegram.tgnet.TLRPC) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) ImageReceiver(org.telegram.messenger.ImageReceiver) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) TextView(android.widget.TextView) ImageView(android.widget.ImageView) RLottieImageView(org.telegram.ui.Components.RLottieImageView) BackupImageView(org.telegram.ui.Components.BackupImageView) ActionBar(org.telegram.ui.ActionBar.ActionBar) RadialProgressView(org.telegram.ui.Components.RadialProgressView) TimerDrawable(org.telegram.ui.Components.TimerDrawable) Canvas(android.graphics.Canvas) TextPaint(android.text.TextPaint) Paint(android.graphics.Paint) StickerEmptyView(org.telegram.ui.Components.StickerEmptyView) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) File(java.io.File) AvatarDrawable(org.telegram.ui.Components.AvatarDrawable) SharedMediaLayout(org.telegram.ui.Components.SharedMediaLayout) RLottieImageView(org.telegram.ui.Components.RLottieImageView) AudioPlayerAlert(org.telegram.ui.Components.AudioPlayerAlert) Bitmap(android.graphics.Bitmap) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) Bundle(android.os.Bundle) ViewGroup(android.view.ViewGroup) ImageView(android.widget.ImageView) RadialProgressView(org.telegram.ui.Components.RadialProgressView) ProfileGalleryView(org.telegram.ui.Components.ProfileGalleryView) UndoView(org.telegram.ui.Components.UndoView) HintView(org.telegram.ui.Components.HintView) StickerEmptyView(org.telegram.ui.Components.StickerEmptyView) FragmentContextView(org.telegram.ui.Components.FragmentContextView) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) RLottieImageView(org.telegram.ui.Components.RLottieImageView) TextView(android.widget.TextView) BackupImageView(org.telegram.ui.Components.BackupImageView) RecyclerListView(org.telegram.ui.Components.RecyclerListView) TextPaint(android.text.TextPaint) Paint(android.graphics.Paint) Point(android.graphics.Point) MotionEvent(android.view.MotionEvent) HintView(org.telegram.ui.Components.HintView) NotificationsCheckCell(org.telegram.ui.Cells.NotificationsCheckCell) FrameLayout(android.widget.FrameLayout) FragmentContextView(org.telegram.ui.Components.FragmentContextView) MessageObject(org.telegram.messenger.MessageObject)

Example 19 with BaseFragment

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

the class ProfileActivity method onCustomTransitionAnimation.

@Override
protected AnimatorSet onCustomTransitionAnimation(final boolean isOpen, final Runnable callback) {
    if (playProfileAnimation != 0 && allowProfileAnimation && !isPulledDown) {
        if (timeItem != null) {
            timeItem.setAlpha(1.0f);
        }
        final AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.setDuration(playProfileAnimation == 2 ? 250 : 180);
        listView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        ActionBarMenu menu = actionBar.createMenu();
        if (menu.getItem(10) == null) {
            if (animatingItem == null) {
                animatingItem = menu.addItem(10, R.drawable.ic_ab_other);
            }
        }
        if (isOpen) {
            FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) onlineTextView[1].getLayoutParams();
            layoutParams.rightMargin = (int) (-21 * AndroidUtilities.density + AndroidUtilities.dp(8));
            onlineTextView[1].setLayoutParams(layoutParams);
            if (playProfileAnimation != 2) {
                int width = (int) Math.ceil(AndroidUtilities.displaySize.x - AndroidUtilities.dp(118 + 8) + 21 * AndroidUtilities.density);
                float width2 = nameTextView[1].getPaint().measureText(nameTextView[1].getText().toString()) * 1.12f + nameTextView[1].getSideDrawablesSize();
                layoutParams = (FrameLayout.LayoutParams) nameTextView[1].getLayoutParams();
                if (width < width2) {
                    layoutParams.width = (int) Math.ceil(width / 1.12f);
                } else {
                    layoutParams.width = LayoutHelper.WRAP_CONTENT;
                }
                nameTextView[1].setLayoutParams(layoutParams);
                initialAnimationExtraHeight = AndroidUtilities.dp(88f);
            } else {
                layoutParams = (FrameLayout.LayoutParams) nameTextView[1].getLayoutParams();
                layoutParams.width = (int) ((AndroidUtilities.displaySize.x - AndroidUtilities.dp(32)) / 1.67f);
                nameTextView[1].setLayoutParams(layoutParams);
            }
            fragmentView.setBackgroundColor(0);
            setAnimationProgress(0);
            ArrayList<Animator> animators = new ArrayList<>();
            animators.add(ObjectAnimator.ofFloat(this, "animationProgress", 0.0f, 1.0f));
            if (writeButton != null && writeButton.getTag() == null) {
                writeButton.setScaleX(0.2f);
                writeButton.setScaleY(0.2f);
                writeButton.setAlpha(0.0f);
                animators.add(ObjectAnimator.ofFloat(writeButton, View.SCALE_X, 1.0f));
                animators.add(ObjectAnimator.ofFloat(writeButton, View.SCALE_Y, 1.0f));
                animators.add(ObjectAnimator.ofFloat(writeButton, View.ALPHA, 1.0f));
            }
            if (playProfileAnimation == 2) {
                avatarColor = AndroidUtilities.calcBitmapColor(avatarImage.getImageReceiver().getBitmap());
                nameTextView[1].setTextColor(Color.WHITE);
                onlineTextView[1].setTextColor(Color.argb(179, 255, 255, 255));
                actionBar.setItemsBackgroundColor(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR, false);
                overlaysView.setOverlaysVisible();
            }
            for (int a = 0; a < 2; a++) {
                nameTextView[a].setAlpha(a == 0 ? 1.0f : 0.0f);
                animators.add(ObjectAnimator.ofFloat(nameTextView[a], View.ALPHA, a == 0 ? 0.0f : 1.0f));
            }
            if (timeItem.getTag() != null) {
                animators.add(ObjectAnimator.ofFloat(timeItem, View.ALPHA, 1.0f, 0.0f));
                animators.add(ObjectAnimator.ofFloat(timeItem, View.SCALE_X, 1.0f, 0.0f));
                animators.add(ObjectAnimator.ofFloat(timeItem, View.SCALE_Y, 1.0f, 0.0f));
            }
            if (animatingItem != null) {
                animatingItem.setAlpha(1.0f);
                animators.add(ObjectAnimator.ofFloat(animatingItem, View.ALPHA, 0.0f));
            }
            if (callItemVisible && chatId != 0) {
                callItem.setAlpha(0.0f);
                animators.add(ObjectAnimator.ofFloat(callItem, View.ALPHA, 1.0f));
            }
            if (videoCallItemVisible) {
                videoCallItem.setAlpha(0.0f);
                animators.add(ObjectAnimator.ofFloat(videoCallItem, View.ALPHA, 1.0f));
            }
            if (editItemVisible) {
                editItem.setAlpha(0.0f);
                animators.add(ObjectAnimator.ofFloat(editItem, View.ALPHA, 1.0f));
            }
            boolean onlineTextCrosafade = false;
            BaseFragment previousFragment = parentLayout.fragmentsStack.size() > 1 ? parentLayout.fragmentsStack.get(parentLayout.fragmentsStack.size() - 2) : null;
            if (previousFragment instanceof ChatActivity) {
                ChatAvatarContainer avatarContainer = ((ChatActivity) previousFragment).getAvatarContainer();
                if (avatarContainer.getSubtitleTextView().getLeftDrawable() != null) {
                    transitionOnlineText = avatarContainer.getSubtitleTextView();
                    avatarContainer2.invalidate();
                    onlineTextCrosafade = true;
                    onlineTextView[0].setAlpha(0f);
                    onlineTextView[1].setAlpha(0f);
                    animators.add(ObjectAnimator.ofFloat(onlineTextView[1], View.ALPHA, 1.0f));
                }
            }
            if (!onlineTextCrosafade) {
                for (int a = 0; a < 2; a++) {
                    onlineTextView[a].setAlpha(a == 0 ? 1.0f : 0.0f);
                    animators.add(ObjectAnimator.ofFloat(onlineTextView[a], View.ALPHA, a == 0 ? 0.0f : 1.0f));
                }
            }
            animatorSet.playTogether(animators);
        } else {
            initialAnimationExtraHeight = extraHeight;
            ArrayList<Animator> animators = new ArrayList<>();
            animators.add(ObjectAnimator.ofFloat(this, "animationProgress", 1.0f, 0.0f));
            if (writeButton != null) {
                animators.add(ObjectAnimator.ofFloat(writeButton, View.SCALE_X, 0.2f));
                animators.add(ObjectAnimator.ofFloat(writeButton, View.SCALE_Y, 0.2f));
                animators.add(ObjectAnimator.ofFloat(writeButton, View.ALPHA, 0.0f));
            }
            for (int a = 0; a < 2; a++) {
                animators.add(ObjectAnimator.ofFloat(nameTextView[a], View.ALPHA, a == 0 ? 1.0f : 0.0f));
            }
            if (timeItem.getTag() != null) {
                animators.add(ObjectAnimator.ofFloat(timeItem, View.ALPHA, 0.0f, 1.0f));
                animators.add(ObjectAnimator.ofFloat(timeItem, View.SCALE_X, 0.0f, 1.0f));
                animators.add(ObjectAnimator.ofFloat(timeItem, View.SCALE_Y, 0.0f, 1.0f));
            }
            if (animatingItem != null) {
                animatingItem.setAlpha(0.0f);
                animators.add(ObjectAnimator.ofFloat(animatingItem, View.ALPHA, 1.0f));
            }
            if (callItemVisible && chatId != 0) {
                callItem.setAlpha(1.0f);
                animators.add(ObjectAnimator.ofFloat(callItem, View.ALPHA, 0.0f));
            }
            if (videoCallItemVisible) {
                videoCallItem.setAlpha(1.0f);
                animators.add(ObjectAnimator.ofFloat(videoCallItem, View.ALPHA, 0.0f));
            }
            if (editItemVisible) {
                editItem.setAlpha(1.0f);
                animators.add(ObjectAnimator.ofFloat(editItem, View.ALPHA, 0.0f));
            }
            boolean crossfadeOnlineText = false;
            BaseFragment previousFragment = parentLayout.fragmentsStack.size() > 1 ? parentLayout.fragmentsStack.get(parentLayout.fragmentsStack.size() - 2) : null;
            if (previousFragment instanceof ChatActivity) {
                ChatAvatarContainer avatarContainer = ((ChatActivity) previousFragment).getAvatarContainer();
                if (avatarContainer.getSubtitleTextView().getLeftDrawable() != null) {
                    transitionOnlineText = avatarContainer.getSubtitleTextView();
                    avatarContainer2.invalidate();
                    crossfadeOnlineText = true;
                    animators.add(ObjectAnimator.ofFloat(onlineTextView[0], View.ALPHA, 0.0f));
                    animators.add(ObjectAnimator.ofFloat(onlineTextView[1], View.ALPHA, 0.0f));
                }
            }
            if (!crossfadeOnlineText) {
                for (int a = 0; a < 2; a++) {
                    animators.add(ObjectAnimator.ofFloat(onlineTextView[a], View.ALPHA, a == 0 ? 1.0f : 0.0f));
                }
            }
            animatorSet.playTogether(animators);
        }
        profileTransitionInProgress = true;
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1f);
        valueAnimator.addUpdateListener(valueAnimator1 -> fragmentView.invalidate());
        animatorSet.playTogether(valueAnimator);
        animatorSet.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationEnd(Animator animation) {
                listView.setLayerType(View.LAYER_TYPE_NONE, null);
                if (animatingItem != null) {
                    ActionBarMenu menu = actionBar.createMenu();
                    menu.clearItems();
                    animatingItem = null;
                }
                callback.run();
                if (playProfileAnimation == 2) {
                    playProfileAnimation = 1;
                    avatarImage.setForegroundAlpha(1.0f);
                    avatarContainer.setVisibility(View.GONE);
                    avatarsViewPager.resetCurrentItem();
                    avatarsViewPager.setVisibility(View.VISIBLE);
                }
                transitionOnlineText = null;
                avatarContainer2.invalidate();
                profileTransitionInProgress = false;
                fragmentView.invalidate();
            }
        });
        animatorSet.setInterpolator(playProfileAnimation == 2 ? CubicBezierInterpolator.DEFAULT : new DecelerateInterpolator());
        AndroidUtilities.runOnUIThread(animatorSet::start, 50);
        return animatorSet;
    }
    return null;
}
Also used : DecelerateInterpolator(android.view.animation.DecelerateInterpolator) ChatAvatarContainer(org.telegram.ui.Components.ChatAvatarContainer) ArrayList(java.util.ArrayList) AnimatorSet(android.animation.AnimatorSet) ValueAnimator(android.animation.ValueAnimator) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) TextPaint(android.text.TextPaint) Paint(android.graphics.Paint) Point(android.graphics.Point) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) ValueAnimator(android.animation.ValueAnimator) Animator(android.animation.Animator) ObjectAnimator(android.animation.ObjectAnimator) DefaultItemAnimator(androidx.recyclerview.widget.DefaultItemAnimator) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) FrameLayout(android.widget.FrameLayout)

Example 20 with BaseFragment

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

the class ChatUsersActivity method createView.

@Override
public View createView(Context context) {
    searching = false;
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(true);
    if (type == TYPE_KICKED) {
        actionBar.setTitle(LocaleController.getString("ChannelPermissions", R.string.ChannelPermissions));
    } else if (type == TYPE_BANNED) {
        actionBar.setTitle(LocaleController.getString("ChannelBlacklist", R.string.ChannelBlacklist));
    } else if (type == TYPE_ADMIN) {
        actionBar.setTitle(LocaleController.getString("ChannelAdministrators", R.string.ChannelAdministrators));
    } else if (type == TYPE_USERS) {
        if (selectType == SELECT_TYPE_MEMBERS) {
            if (isChannel) {
                actionBar.setTitle(LocaleController.getString("ChannelSubscribers", R.string.ChannelSubscribers));
            } else {
                actionBar.setTitle(LocaleController.getString("ChannelMembers", R.string.ChannelMembers));
            }
        } else {
            if (selectType == SELECT_TYPE_ADMIN) {
                actionBar.setTitle(LocaleController.getString("ChannelAddAdmin", R.string.ChannelAddAdmin));
            } else if (selectType == SELECT_TYPE_BLOCK) {
                actionBar.setTitle(LocaleController.getString("ChannelBlockUser", R.string.ChannelBlockUser));
            } else if (selectType == SELECT_TYPE_EXCEPTION) {
                actionBar.setTitle(LocaleController.getString("ChannelAddException", R.string.ChannelAddException));
            }
        }
    }
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {

        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                if (checkDiscard()) {
                    finishFragment();
                }
            } else if (id == done_button) {
                processDone();
            }
        }
    });
    if (selectType != SELECT_TYPE_MEMBERS || type == TYPE_USERS || type == TYPE_BANNED || type == TYPE_KICKED) {
        searchListViewAdapter = new SearchAdapter(context);
        ActionBarMenu menu = actionBar.createMenu();
        searchItem = menu.addItem(search_button, R.drawable.ic_ab_search).setIsSearchField(true).setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() {

            @Override
            public void onSearchExpand() {
                searching = true;
                if (doneItem != null) {
                    doneItem.setVisibility(View.GONE);
                }
            }

            @Override
            public void onSearchCollapse() {
                searchListViewAdapter.searchUsers(null);
                searching = false;
                listView.setAnimateEmptyView(false, 0);
                listView.setAdapter(listViewAdapter);
                listViewAdapter.notifyDataSetChanged();
                listView.setFastScrollVisible(true);
                listView.setVerticalScrollBarEnabled(false);
                if (doneItem != null) {
                    doneItem.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onTextChanged(EditText editText) {
                if (searchListViewAdapter == null) {
                    return;
                }
                String text = editText.getText().toString();
                int oldItemsCount = listView.getAdapter() == null ? 0 : listView.getAdapter().getItemCount();
                searchListViewAdapter.searchUsers(text);
                if (TextUtils.isEmpty(text) && listView != null && listView.getAdapter() != listViewAdapter) {
                    listView.setAnimateEmptyView(false, 0);
                    listView.setAdapter(listViewAdapter);
                    if (oldItemsCount == 0) {
                        showItemsAnimated(0);
                    }
                }
                progressBar.setVisibility(View.GONE);
                flickerLoadingView.setVisibility(View.VISIBLE);
            }
        });
        if (type == TYPE_KICKED) {
            searchItem.setSearchFieldHint(LocaleController.getString("ChannelSearchException", R.string.ChannelSearchException));
        } else {
            searchItem.setSearchFieldHint(LocaleController.getString("Search", R.string.Search));
        }
        if (!(ChatObject.isChannel(currentChat) || currentChat.creator)) {
            searchItem.setVisibility(View.GONE);
        }
        if (type == TYPE_KICKED) {
            doneItem = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56), LocaleController.getString("Done", R.string.Done));
        }
    }
    fragmentView = new FrameLayout(context) {

        @Override
        protected void dispatchDraw(Canvas canvas) {
            canvas.drawColor(Theme.getColor(listView.getAdapter() == searchListViewAdapter ? Theme.key_windowBackgroundWhite : Theme.key_windowBackgroundGray));
            super.dispatchDraw(canvas);
        }
    };
    FrameLayout frameLayout = (FrameLayout) fragmentView;
    FrameLayout progressLayout = new FrameLayout(context);
    flickerLoadingView = new FlickerLoadingView(context);
    flickerLoadingView.setViewType(FlickerLoadingView.USERS_TYPE);
    flickerLoadingView.showDate(false);
    flickerLoadingView.setUseHeaderOffset(true);
    progressLayout.addView(flickerLoadingView);
    progressBar = new RadialProgressView(context);
    progressLayout.addView(progressBar, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
    flickerLoadingView.setVisibility(View.GONE);
    progressBar.setVisibility(View.GONE);
    emptyView = new StickerEmptyView(context, progressLayout, StickerEmptyView.STICKER_TYPE_SEARCH);
    emptyView.title.setText(LocaleController.getString("NoResult", R.string.NoResult));
    emptyView.subtitle.setText(LocaleController.getString("SearchEmptyViewFilteredSubtitle2", R.string.SearchEmptyViewFilteredSubtitle2));
    emptyView.setVisibility(View.GONE);
    emptyView.setAnimateLayoutChange(true);
    emptyView.showProgress(true, false);
    frameLayout.addView(emptyView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    emptyView.addView(progressLayout, 0);
    listView = new RecyclerListView(context) {

        @Override
        public void invalidate() {
            super.invalidate();
            if (fragmentView != null) {
                fragmentView.invalidate();
            }
        }
    };
    listView.setLayoutManager(layoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) {

        @Override
        public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
            if (!firstLoaded && type == TYPE_BANNED && participants.size() == 0) {
                return 0;
            }
            return super.scrollVerticallyBy(dy, recycler, state);
        }
    });
    DefaultItemAnimator itemAnimator = new DefaultItemAnimator() {

        @Override
        protected long getAddAnimationDelay(long removeDuration, long moveDuration, long changeDuration) {
            return 0;
        }

        @Override
        protected long getMoveAnimationDelay() {
            return 0;
        }

        @Override
        public long getMoveDuration() {
            return 220;
        }

        @Override
        public long getRemoveDuration() {
            return 220;
        }

        @Override
        public long getAddDuration() {
            return 220;
        }

        int animationIndex = -1;

        @Override
        protected void onAllAnimationsDone() {
            super.onAllAnimationsDone();
            getNotificationCenter().onAnimationFinish(animationIndex);
        }

        @Override
        public void runPendingAnimations() {
            boolean removalsPending = !mPendingRemovals.isEmpty();
            boolean movesPending = !mPendingMoves.isEmpty();
            boolean changesPending = !mPendingChanges.isEmpty();
            boolean additionsPending = !mPendingAdditions.isEmpty();
            if (removalsPending || movesPending || additionsPending || changesPending) {
                animationIndex = getNotificationCenter().setAnimationInProgress(animationIndex, null);
            }
            super.runPendingAnimations();
        }
    };
    listView.setItemAnimator(itemAnimator);
    itemAnimator.setSupportsChangeAnimations(false);
    listView.setAnimateEmptyView(true, 0);
    listView.setAdapter(listViewAdapter = new ListAdapter(context));
    listView.setVerticalScrollbarPosition(LocaleController.isRTL ? RecyclerListView.SCROLLBAR_POSITION_LEFT : RecyclerListView.SCROLLBAR_POSITION_RIGHT);
    frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    listView.setOnItemClickListener((view, position) -> {
        boolean listAdapter = listView.getAdapter() == listViewAdapter;
        if (listAdapter) {
            if (position == addNewRow) {
                if (type == TYPE_BANNED || type == TYPE_KICKED) {
                    Bundle bundle = new Bundle();
                    bundle.putLong("chat_id", chatId);
                    bundle.putInt("type", ChatUsersActivity.TYPE_USERS);
                    bundle.putInt("selectType", type == TYPE_BANNED ? ChatUsersActivity.SELECT_TYPE_BLOCK : ChatUsersActivity.SELECT_TYPE_EXCEPTION);
                    ChatUsersActivity fragment = new ChatUsersActivity(bundle);
                    fragment.setInfo(info);
                    fragment.setDelegate(new ChatUsersActivityDelegate() {

                        @Override
                        public void didAddParticipantToList(long uid, TLObject participant) {
                            if (participantsMap.get(uid) == null) {
                                DiffCallback diffCallback = saveState();
                                participants.add(participant);
                                participantsMap.put(uid, participant);
                                sortUsers(participants);
                                updateListAnimated(diffCallback);
                            }
                        }

                        @Override
                        public void didKickParticipant(long uid) {
                            if (participantsMap.get(uid) == null) {
                                DiffCallback diffCallback = saveState();
                                TLRPC.TL_channelParticipantBanned chatParticipant = new TLRPC.TL_channelParticipantBanned();
                                if (uid > 0) {
                                    chatParticipant.peer = new TLRPC.TL_peerUser();
                                    chatParticipant.peer.user_id = uid;
                                } else {
                                    chatParticipant.peer = new TLRPC.TL_peerChannel();
                                    chatParticipant.peer.channel_id = -uid;
                                }
                                chatParticipant.date = getConnectionsManager().getCurrentTime();
                                chatParticipant.kicked_by = getAccountInstance().getUserConfig().clientUserId;
                                info.kicked_count++;
                                participants.add(chatParticipant);
                                participantsMap.put(uid, chatParticipant);
                                sortUsers(participants);
                                updateListAnimated(diffCallback);
                            }
                        }
                    });
                    presentFragment(fragment);
                } else if (type == TYPE_ADMIN) {
                    Bundle bundle = new Bundle();
                    bundle.putLong("chat_id", chatId);
                    bundle.putInt("type", ChatUsersActivity.TYPE_USERS);
                    bundle.putInt("selectType", ChatUsersActivity.SELECT_TYPE_ADMIN);
                    ChatUsersActivity fragment = new ChatUsersActivity(bundle);
                    fragment.setDelegate(new ChatUsersActivityDelegate() {

                        @Override
                        public void didAddParticipantToList(long uid, TLObject participant) {
                            if (participant != null && participantsMap.get(uid) == null) {
                                DiffCallback diffCallback = saveState();
                                participants.add(participant);
                                participantsMap.put(uid, participant);
                                sortAdmins(participants);
                                updateListAnimated(diffCallback);
                            }
                        }

                        @Override
                        public void didChangeOwner(TLRPC.User user) {
                            onOwnerChaged(user);
                        }

                        @Override
                        public void didSelectUser(long uid) {
                            final TLRPC.User user = getMessagesController().getUser(uid);
                            if (user != null) {
                                AndroidUtilities.runOnUIThread(() -> {
                                    if (BulletinFactory.canShowBulletin(ChatUsersActivity.this)) {
                                        BulletinFactory.createPromoteToAdminBulletin(ChatUsersActivity.this, user.first_name).show();
                                    }
                                }, 200);
                            }
                            if (participantsMap.get(uid) == null) {
                                DiffCallback diffCallback = saveState();
                                TLRPC.TL_channelParticipantAdmin chatParticipant = new TLRPC.TL_channelParticipantAdmin();
                                chatParticipant.peer = new TLRPC.TL_peerUser();
                                chatParticipant.peer.user_id = user.id;
                                chatParticipant.date = getConnectionsManager().getCurrentTime();
                                chatParticipant.promoted_by = getAccountInstance().getUserConfig().clientUserId;
                                participants.add(chatParticipant);
                                participantsMap.put(user.id, chatParticipant);
                                sortAdmins(participants);
                                updateListAnimated(diffCallback);
                            }
                        }
                    });
                    fragment.setInfo(info);
                    presentFragment(fragment);
                } else if (type == TYPE_USERS) {
                    Bundle args = new Bundle();
                    args.putBoolean("addToGroup", true);
                    args.putLong(isChannel ? "channelId" : "chatId", currentChat.id);
                    GroupCreateActivity fragment = new GroupCreateActivity(args);
                    fragment.setInfo(info);
                    fragment.setIgnoreUsers(contactsMap != null && contactsMap.size() != 0 ? contactsMap : participantsMap);
                    fragment.setDelegate(new GroupCreateActivity.ContactsAddActivityDelegate() {

                        @Override
                        public void didSelectUsers(ArrayList<TLRPC.User> users, int fwdCount) {
                            DiffCallback savedState = saveState();
                            ArrayList<TLObject> array = contactsMap != null && contactsMap.size() != 0 ? contacts : participants;
                            LongSparseArray<TLObject> map = contactsMap != null && contactsMap.size() != 0 ? contactsMap : participantsMap;
                            int k = 0;
                            for (int a = 0, N = users.size(); a < N; a++) {
                                TLRPC.User user = users.get(a);
                                getMessagesController().addUserToChat(chatId, user, fwdCount, null, ChatUsersActivity.this, null);
                                getMessagesController().putUser(user, false);
                                if (map.get(user.id) == null) {
                                    if (ChatObject.isChannel(currentChat)) {
                                        TLRPC.TL_channelParticipant channelParticipant1 = new TLRPC.TL_channelParticipant();
                                        channelParticipant1.inviter_id = getUserConfig().getClientUserId();
                                        channelParticipant1.peer = new TLRPC.TL_peerUser();
                                        channelParticipant1.peer.user_id = user.id;
                                        channelParticipant1.date = getConnectionsManager().getCurrentTime();
                                        array.add(k, channelParticipant1);
                                        k++;
                                        map.put(user.id, channelParticipant1);
                                    } else {
                                        TLRPC.ChatParticipant participant = new TLRPC.TL_chatParticipant();
                                        participant.user_id = user.id;
                                        participant.inviter_id = getUserConfig().getClientUserId();
                                        array.add(k, participant);
                                        k++;
                                        map.put(user.id, participant);
                                    }
                                }
                            }
                            if (array == participants) {
                                sortAdmins(participants);
                            }
                            updateListAnimated(savedState);
                        }

                        @Override
                        public void needAddBot(TLRPC.User user) {
                            openRightsEdit(user.id, null, null, null, "", true, ChatRightsEditActivity.TYPE_ADMIN, false);
                        }
                    });
                    presentFragment(fragment);
                }
                return;
            } else if (position == recentActionsRow) {
                presentFragment(new ChannelAdminLogActivity(currentChat));
                return;
            } else if (position == removedUsersRow) {
                Bundle args = new Bundle();
                args.putLong("chat_id", chatId);
                args.putInt("type", ChatUsersActivity.TYPE_BANNED);
                ChatUsersActivity fragment = new ChatUsersActivity(args);
                fragment.setInfo(info);
                presentFragment(fragment);
                return;
            } else if (position == gigaConvertRow) {
                showDialog(new GigagroupConvertAlert(getParentActivity(), ChatUsersActivity.this) {

                    @Override
                    protected void onCovert() {
                        getMessagesController().convertToGigaGroup(getParentActivity(), currentChat, ChatUsersActivity.this, (result) -> {
                            if (result && parentLayout != null) {
                                BaseFragment editActivity = parentLayout.fragmentsStack.get(parentLayout.fragmentsStack.size() - 2);
                                if (editActivity instanceof ChatEditActivity) {
                                    editActivity.removeSelfFromStack();
                                    Bundle args = new Bundle();
                                    args.putLong("chat_id", chatId);
                                    ChatEditActivity fragment = new ChatEditActivity(args);
                                    fragment.setInfo(info);
                                    parentLayout.addFragmentToStack(fragment, parentLayout.fragmentsStack.size() - 1);
                                    finishFragment();
                                    fragment.showConvertTooltip();
                                } else {
                                    finishFragment();
                                }
                            }
                        });
                    }

                    @Override
                    protected void onCancel() {
                    }
                });
            } else if (position == addNew2Row) {
                ManageLinksActivity fragment = new ManageLinksActivity(chatId, 0, 0);
                fragment.setInfo(info, info.exported_invite);
                presentFragment(fragment);
                return;
            } else if (position > permissionsSectionRow && position <= changeInfoRow) {
                TextCheckCell2 checkCell = (TextCheckCell2) view;
                if (!checkCell.isEnabled()) {
                    return;
                }
                if (checkCell.hasIcon()) {
                    if (!TextUtils.isEmpty(currentChat.username) && (position == pinMessagesRow || position == changeInfoRow)) {
                        BulletinFactory.of(this).createErrorBulletin(LocaleController.getString("EditCantEditPermissionsPublic", R.string.EditCantEditPermissionsPublic)).show();
                    } else {
                        BulletinFactory.of(this).createErrorBulletin(LocaleController.getString("EditCantEditPermissions", R.string.EditCantEditPermissions)).show();
                    }
                    return;
                }
                checkCell.setChecked(!checkCell.isChecked());
                if (position == changeInfoRow) {
                    defaultBannedRights.change_info = !defaultBannedRights.change_info;
                } else if (position == addUsersRow) {
                    defaultBannedRights.invite_users = !defaultBannedRights.invite_users;
                } else if (position == pinMessagesRow) {
                    defaultBannedRights.pin_messages = !defaultBannedRights.pin_messages;
                } else {
                    boolean disabled = !checkCell.isChecked();
                    if (position == sendMessagesRow) {
                        defaultBannedRights.send_messages = !defaultBannedRights.send_messages;
                    } else if (position == sendMediaRow) {
                        defaultBannedRights.send_media = !defaultBannedRights.send_media;
                    } else if (position == sendStickersRow) {
                        defaultBannedRights.send_stickers = defaultBannedRights.send_games = defaultBannedRights.send_gifs = defaultBannedRights.send_inline = !defaultBannedRights.send_stickers;
                    } else if (position == embedLinksRow) {
                        defaultBannedRights.embed_links = !defaultBannedRights.embed_links;
                    } else if (position == sendPollsRow) {
                        defaultBannedRights.send_polls = !defaultBannedRights.send_polls;
                    }
                    if (disabled) {
                        if (defaultBannedRights.view_messages && !defaultBannedRights.send_messages) {
                            defaultBannedRights.send_messages = true;
                            RecyclerListView.ViewHolder holder = listView.findViewHolderForAdapterPosition(sendMessagesRow);
                            if (holder != null) {
                                ((TextCheckCell2) holder.itemView).setChecked(false);
                            }
                        }
                        if ((defaultBannedRights.view_messages || defaultBannedRights.send_messages) && !defaultBannedRights.send_media) {
                            defaultBannedRights.send_media = true;
                            RecyclerListView.ViewHolder holder = listView.findViewHolderForAdapterPosition(sendMediaRow);
                            if (holder != null) {
                                ((TextCheckCell2) holder.itemView).setChecked(false);
                            }
                        }
                        if ((defaultBannedRights.view_messages || defaultBannedRights.send_messages) && !defaultBannedRights.send_polls) {
                            defaultBannedRights.send_polls = true;
                            RecyclerListView.ViewHolder holder = listView.findViewHolderForAdapterPosition(sendPollsRow);
                            if (holder != null) {
                                ((TextCheckCell2) holder.itemView).setChecked(false);
                            }
                        }
                        if ((defaultBannedRights.view_messages || defaultBannedRights.send_messages) && !defaultBannedRights.send_stickers) {
                            defaultBannedRights.send_stickers = defaultBannedRights.send_games = defaultBannedRights.send_gifs = defaultBannedRights.send_inline = true;
                            RecyclerListView.ViewHolder holder = listView.findViewHolderForAdapterPosition(sendStickersRow);
                            if (holder != null) {
                                ((TextCheckCell2) holder.itemView).setChecked(false);
                            }
                        }
                        if ((defaultBannedRights.view_messages || defaultBannedRights.send_messages) && !defaultBannedRights.embed_links) {
                            defaultBannedRights.embed_links = true;
                            RecyclerListView.ViewHolder holder = listView.findViewHolderForAdapterPosition(embedLinksRow);
                            if (holder != null) {
                                ((TextCheckCell2) holder.itemView).setChecked(false);
                            }
                        }
                    } else {
                        if ((!defaultBannedRights.embed_links || !defaultBannedRights.send_inline || !defaultBannedRights.send_media || !defaultBannedRights.send_polls) && defaultBannedRights.send_messages) {
                            defaultBannedRights.send_messages = false;
                            RecyclerListView.ViewHolder holder = listView.findViewHolderForAdapterPosition(sendMessagesRow);
                            if (holder != null) {
                                ((TextCheckCell2) holder.itemView).setChecked(true);
                            }
                        }
                    }
                }
                return;
            }
        }
        TLRPC.TL_chatBannedRights bannedRights = null;
        TLRPC.TL_chatAdminRights adminRights = null;
        String rank = "";
        final TLObject participant;
        long peerId = 0;
        long promoted_by = 0;
        boolean canEditAdmin = false;
        if (listAdapter) {
            participant = listViewAdapter.getItem(position);
            if (participant instanceof TLRPC.ChannelParticipant) {
                TLRPC.ChannelParticipant channelParticipant = (TLRPC.ChannelParticipant) participant;
                peerId = MessageObject.getPeerId(channelParticipant.peer);
                bannedRights = channelParticipant.banned_rights;
                adminRights = channelParticipant.admin_rights;
                rank = channelParticipant.rank;
                canEditAdmin = !(channelParticipant instanceof TLRPC.TL_channelParticipantAdmin || channelParticipant instanceof TLRPC.TL_channelParticipantCreator) || channelParticipant.can_edit;
                if (participant instanceof TLRPC.TL_channelParticipantCreator) {
                    adminRights = ((TLRPC.TL_channelParticipantCreator) participant).admin_rights;
                    if (adminRights == null) {
                        adminRights = new TLRPC.TL_chatAdminRights();
                        adminRights.change_info = adminRights.post_messages = adminRights.edit_messages = adminRights.delete_messages = adminRights.ban_users = adminRights.invite_users = adminRights.pin_messages = adminRights.add_admins = true;
                        if (!isChannel) {
                            adminRights.manage_call = true;
                        }
                    }
                }
            } else if (participant instanceof TLRPC.ChatParticipant) {
                TLRPC.ChatParticipant chatParticipant = (TLRPC.ChatParticipant) participant;
                peerId = chatParticipant.user_id;
                canEditAdmin = currentChat.creator;
                if (participant instanceof TLRPC.TL_chatParticipantCreator) {
                    adminRights = new TLRPC.TL_chatAdminRights();
                    adminRights.change_info = adminRights.post_messages = adminRights.edit_messages = adminRights.delete_messages = adminRights.ban_users = adminRights.invite_users = adminRights.pin_messages = adminRights.add_admins = true;
                    if (!isChannel) {
                        adminRights.manage_call = true;
                    }
                }
            }
        } else {
            TLObject object = searchListViewAdapter.getItem(position);
            if (object instanceof TLRPC.User) {
                TLRPC.User user = (TLRPC.User) object;
                getMessagesController().putUser(user, false);
                participant = getAnyParticipant(peerId = user.id);
            } else if (object instanceof TLRPC.ChannelParticipant || object instanceof TLRPC.ChatParticipant) {
                participant = object;
            } else {
                participant = null;
            }
            if (participant instanceof TLRPC.ChannelParticipant) {
                TLRPC.ChannelParticipant channelParticipant = (TLRPC.ChannelParticipant) participant;
                peerId = MessageObject.getPeerId(channelParticipant.peer);
                canEditAdmin = !(channelParticipant instanceof TLRPC.TL_channelParticipantAdmin || channelParticipant instanceof TLRPC.TL_channelParticipantCreator) || channelParticipant.can_edit;
                bannedRights = channelParticipant.banned_rights;
                adminRights = channelParticipant.admin_rights;
                rank = channelParticipant.rank;
            } else if (participant instanceof TLRPC.ChatParticipant) {
                TLRPC.ChatParticipant chatParticipant = (TLRPC.ChatParticipant) participant;
                peerId = chatParticipant.user_id;
                canEditAdmin = currentChat.creator;
                bannedRights = null;
                adminRights = null;
            } else if (participant == null) {
                canEditAdmin = true;
            }
        }
        if (peerId != 0) {
            if (selectType != SELECT_TYPE_MEMBERS) {
                if (selectType == SELECT_TYPE_EXCEPTION || selectType == SELECT_TYPE_ADMIN) {
                    if (selectType != SELECT_TYPE_ADMIN && canEditAdmin && (participant instanceof TLRPC.TL_channelParticipantAdmin || participant instanceof TLRPC.TL_chatParticipantAdmin)) {
                        final TLRPC.User user = getMessagesController().getUser(peerId);
                        final TLRPC.TL_chatBannedRights br = bannedRights;
                        final TLRPC.TL_chatAdminRights ar = adminRights;
                        final boolean canEdit = canEditAdmin;
                        final String rankFinal = rank;
                        AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                        builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                        builder.setMessage(LocaleController.formatString("AdminWillBeRemoved", R.string.AdminWillBeRemoved, UserObject.getUserName(user)));
                        builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), (dialog, which) -> openRightsEdit(user.id, participant, ar, br, rankFinal, canEdit, selectType == SELECT_TYPE_ADMIN ? 0 : 1, false));
                        builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                        showDialog(builder.create());
                    } else {
                        openRightsEdit(peerId, participant, adminRights, bannedRights, rank, canEditAdmin, selectType == SELECT_TYPE_ADMIN ? 0 : 1, selectType == SELECT_TYPE_ADMIN || selectType == SELECT_TYPE_EXCEPTION);
                    }
                } else {
                    removeParticipant(peerId);
                }
            } else {
                boolean canEdit = false;
                if (type == TYPE_ADMIN) {
                    canEdit = peerId != getUserConfig().getClientUserId() && (currentChat.creator || canEditAdmin);
                } else if (type == TYPE_BANNED || type == TYPE_KICKED) {
                    canEdit = ChatObject.canBlockUsers(currentChat);
                }
                if (type == TYPE_BANNED || type != TYPE_ADMIN && isChannel || type == TYPE_USERS && selectType == SELECT_TYPE_MEMBERS) {
                    if (peerId == getUserConfig().getClientUserId()) {
                        return;
                    }
                    Bundle args = new Bundle();
                    if (peerId > 0) {
                        args.putLong("user_id", peerId);
                    } else {
                        args.putLong("chat_id", -peerId);
                    }
                    presentFragment(new ProfileActivity(args));
                } else {
                    if (bannedRights == null) {
                        bannedRights = new TLRPC.TL_chatBannedRights();
                        bannedRights.view_messages = true;
                        bannedRights.send_stickers = true;
                        bannedRights.send_media = true;
                        bannedRights.embed_links = true;
                        bannedRights.send_messages = true;
                        bannedRights.send_games = true;
                        bannedRights.send_inline = true;
                        bannedRights.send_gifs = true;
                        bannedRights.pin_messages = true;
                        bannedRights.send_polls = true;
                        bannedRights.invite_users = true;
                        bannedRights.change_info = true;
                    }
                    ChatRightsEditActivity fragment = new ChatRightsEditActivity(peerId, chatId, adminRights, defaultBannedRights, bannedRights, rank, type == TYPE_ADMIN ? ChatRightsEditActivity.TYPE_ADMIN : ChatRightsEditActivity.TYPE_BANNED, canEdit, participant == null);
                    fragment.setDelegate(new ChatRightsEditActivity.ChatRightsEditActivityDelegate() {

                        @Override
                        public void didSetRights(int rights, TLRPC.TL_chatAdminRights rightsAdmin, TLRPC.TL_chatBannedRights rightsBanned, String rank) {
                            if (participant instanceof TLRPC.ChannelParticipant) {
                                TLRPC.ChannelParticipant channelParticipant = (TLRPC.ChannelParticipant) participant;
                                channelParticipant.admin_rights = rightsAdmin;
                                channelParticipant.banned_rights = rightsBanned;
                                channelParticipant.rank = rank;
                                updateParticipantWithRights(channelParticipant, rightsAdmin, rightsBanned, 0, false);
                            }
                        }

                        @Override
                        public void didChangeOwner(TLRPC.User user) {
                            onOwnerChaged(user);
                        }
                    });
                    presentFragment(fragment);
                }
            }
        }
    });
    listView.setOnItemLongClickListener((view, position) -> !(getParentActivity() == null || listView.getAdapter() != listViewAdapter) && createMenuForParticipant(listViewAdapter.getItem(position), false));
    if (searchItem != null) {
        listView.setOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                    AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus());
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            }
        });
    }
    undoView = new UndoView(context);
    frameLayout.addView(undoView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 8, 0, 8, 8));
    updateRows();
    listView.setEmptyView(emptyView);
    listView.setAnimateEmptyView(false, 0);
    if (needOpenSearch) {
        searchItem.openSearch(false);
    }
    return fragmentView;
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) SpannableStringBuilder(android.text.SpannableStringBuilder) ArrayList(java.util.ArrayList) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) DefaultItemAnimator(androidx.recyclerview.widget.DefaultItemAnimator) TLRPC(org.telegram.tgnet.TLRPC) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) ActionBar(org.telegram.ui.ActionBar.ActionBar) EditText(android.widget.EditText) RadialProgressView(org.telegram.ui.Components.RadialProgressView) Canvas(android.graphics.Canvas) StickerEmptyView(org.telegram.ui.Components.StickerEmptyView) TextCheckCell2(org.telegram.ui.Cells.TextCheckCell2) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) GigagroupConvertAlert(org.telegram.ui.Components.GigagroupConvertAlert) LongSparseArray(androidx.collection.LongSparseArray) RecyclerListView(org.telegram.ui.Components.RecyclerListView) UndoView(org.telegram.ui.Components.UndoView) FlickerLoadingView(org.telegram.ui.Components.FlickerLoadingView) Bundle(android.os.Bundle) TextPaint(android.text.TextPaint) Paint(android.graphics.Paint) TLObject(org.telegram.tgnet.TLObject) FrameLayout(android.widget.FrameLayout) RecyclerView(androidx.recyclerview.widget.RecyclerView)

Aggregations

BaseFragment (org.telegram.ui.ActionBar.BaseFragment)46 Paint (android.graphics.Paint)25 Bundle (android.os.Bundle)18 TLRPC (org.telegram.tgnet.TLRPC)18 FrameLayout (android.widget.FrameLayout)17 ArrayList (java.util.ArrayList)17 SuppressLint (android.annotation.SuppressLint)16 View (android.view.View)15 TextView (android.widget.TextView)15 Animator (android.animation.Animator)14 AnimatorListenerAdapter (android.animation.AnimatorListenerAdapter)14 ObjectAnimator (android.animation.ObjectAnimator)14 SharedPreferences (android.content.SharedPreferences)14 Canvas (android.graphics.Canvas)14 RecyclerView (androidx.recyclerview.widget.RecyclerView)14 Context (android.content.Context)13 Intent (android.content.Intent)13 LinearLayoutManager (androidx.recyclerview.widget.LinearLayoutManager)13 TLObject (org.telegram.tgnet.TLObject)13 AlertDialog (org.telegram.ui.ActionBar.AlertDialog)13