Example usage for android.view Gravity CENTER_HORIZONTAL

List of usage examples for android.view Gravity CENTER_HORIZONTAL

Introduction

In this page you can find the example usage for android.view Gravity CENTER_HORIZONTAL.

Prototype

int CENTER_HORIZONTAL

To view the source code for android.view Gravity CENTER_HORIZONTAL.

Click Source Link

Document

Place object in the horizontal center of its container, not changing its size.

Usage

From source file:net.bluehack.ui.ChatActivity.java

@Override
public View createView(Context context) {

    if (chatMessageCellsCache.isEmpty()) {
        for (int a = 0; a < 8; a++) {
            chatMessageCellsCache.add(new ChatMessageCell(context));
        }/*  w w w . ja v  a 2  s .c o  m*/
    }
    for (int a = 1; a >= 0; a--) {
        selectedMessagesIds[a].clear();
        selectedMessagesCanCopyIds[a].clear();
    }
    cantDeleteMessagesCount = 0;

    hasOwnBackground = true;
    if (chatAttachAlert != null) {
        chatAttachAlert.onDestroy();
        chatAttachAlert = null;
    }

    Theme.loadRecources(context);
    Theme.loadChatResources(context);

    actionBar.setAddToContainer(false);
    actionBar.setBackButtonDrawable(new BackDrawable(false));
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override
        public void onItemClick(final int id) {
            if (id == -1) {
                if (actionBar.isActionModeShowed()) {
                    for (int a = 1; a >= 0; a--) {
                        selectedMessagesIds[a].clear();
                        selectedMessagesCanCopyIds[a].clear();
                    }
                    cantDeleteMessagesCount = 0;
                    if (chatActivityEnterView.isEditingMessage()) {
                        chatActivityEnterView.setEditingMessageObject(null, false);
                    } else {
                        actionBar.hideActionMode();
                        updatePinnedMessageView(true);
                    }
                    updateVisibleRows();
                } else {
                    finishFragment();
                }
            } else if (id == copy) {
                String str = "";
                int previousUid = 0;
                for (int a = 1; a >= 0; a--) {
                    ArrayList<Integer> ids = new ArrayList<>(selectedMessagesCanCopyIds[a].keySet());
                    if (currentEncryptedChat == null) {
                        Collections.sort(ids);
                    } else {
                        Collections.sort(ids, Collections.reverseOrder());
                    }
                    for (int b = 0; b < ids.size(); b++) {
                        Integer messageId = ids.get(b);
                        MessageObject messageObject = selectedMessagesCanCopyIds[a].get(messageId);
                        if (str.length() != 0) {
                            str += "\n\n";
                        }
                        str += getMessageContent(messageObject, previousUid, true);
                        previousUid = messageObject.messageOwner.from_id;
                    }
                }
                if (str.length() != 0) {
                    AndroidUtilities.addToClipboard(str);
                }
                for (int a = 1; a >= 0; a--) {
                    selectedMessagesIds[a].clear();
                    selectedMessagesCanCopyIds[a].clear();
                }
                cantDeleteMessagesCount = 0;
                actionBar.hideActionMode();
                updatePinnedMessageView(true);
                updateVisibleRows();
            } else if (id == edit_done) {
                if (chatActivityEnterView != null
                        && (chatActivityEnterView.isEditingCaption() || chatActivityEnterView.hasText())) {
                    chatActivityEnterView.doneEditingMessage();
                }
            } else if (id == delete) {
                if (getParentActivity() == null) {
                    return;
                }
                createDeleteMessagesAlert(null);
            } else if (id == forward) {
                Bundle args = new Bundle();
                args.putBoolean("onlySelect", true);
                args.putInt("dialogsType", 1);
                DialogsActivity fragment = new DialogsActivity(args);
                fragment.setDelegate(ChatActivity.this);
                presentFragment(fragment);
            } else if (id == chat_enc_timer) {
                if (getParentActivity() == null) {
                    return;
                }
                showDialog(AndroidUtilities.buildTTLAlert(getParentActivity(), currentEncryptedChat).create());
            } else if (id == clear_history || id == delete_chat) {
                if (getParentActivity() == null) {
                    return;
                }
                final boolean isChat = (int) dialog_id < 0 && (int) (dialog_id >> 32) != 1;
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                if (id == clear_history) {
                    builder.setMessage(LocaleController.getString("AreYouSureClearHistory",
                            R.string.AreYouSureClearHistory));
                } else {
                    if (isChat) {
                        builder.setMessage(LocaleController.getString("AreYouSureDeleteAndExit",
                                R.string.AreYouSureDeleteAndExit));
                    } else {
                        builder.setMessage(LocaleController.getString("AreYouSureDeleteThisChat",
                                R.string.AreYouSureDeleteThisChat));
                    }
                }
                builder.setPositiveButton(LocaleController.getString("OK", R.string.OK),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                if (id != clear_history) {
                                    if (isChat) {
                                        if (ChatObject.isNotInChat(currentChat)) {
                                            MessagesController.getInstance().deleteDialog(dialog_id, 0);
                                        } else {
                                            MessagesController.getInstance()
                                                    .deleteUserFromChat(
                                                            (int) -dialog_id, MessagesController.getInstance()
                                                                    .getUser(UserConfig.getClientUserId()),
                                                            null);
                                        }
                                    } else {
                                        MessagesController.getInstance().deleteDialog(dialog_id, 0);
                                    }
                                    finishFragment();
                                } else {
                                    MessagesController.getInstance().deleteDialog(dialog_id, 1);
                                }
                            }
                        });
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                showDialog(builder.create());
            } else if (id == share_contact) {
                if (currentUser == null || getParentActivity() == null) {
                    return;
                }
                if (currentUser.phone != null && currentUser.phone.length() != 0) {
                    Bundle args = new Bundle();
                    args.putInt("user_id", currentUser.id);
                    args.putBoolean("addContact", true);
                    presentFragment(new ContactAddActivity(args));
                } else {
                    shareMyContact(replyingMessageObject);
                }
            } else if (id == mute) {
                toggleMute(false);
            } else if (id == report) {
                showDialog(AlertsCreator.createReportAlert(getParentActivity(), dialog_id, ChatActivity.this));
            } else if (id == reply) {
                MessageObject messageObject = null;
                for (int a = 1; a >= 0; a--) {
                    if (messageObject == null && selectedMessagesIds[a].size() == 1) {
                        ArrayList<Integer> ids = new ArrayList<>(selectedMessagesIds[a].keySet());
                        messageObject = messagesDict[a].get(ids.get(0));
                    }
                    selectedMessagesIds[a].clear();
                    selectedMessagesCanCopyIds[a].clear();
                }
                if (messageObject != null && (messageObject.messageOwner.id > 0
                        || messageObject.messageOwner.id < 0 && currentEncryptedChat != null)) {
                    showReplyPanel(true, messageObject, null, null, false, true);
                }
                cantDeleteMessagesCount = 0;
                actionBar.hideActionMode();
                updatePinnedMessageView(true);
                updateVisibleRows();
            } else if (id == chat_menu_attach) {
                if (getParentActivity() == null) {
                    return;
                }

                createChatAttachView();
                chatAttachAlert.loadGalleryPhotos();
                if (Build.VERSION.SDK_INT == 21 || Build.VERSION.SDK_INT == 22) {
                    chatActivityEnterView.closeKeyboard();
                }
                chatAttachAlert.init();
                showDialog(chatAttachAlert);
            } else if (id == bot_help) {
                SendMessagesHelper.getInstance().sendMessage("/help", dialog_id, null, null, false, null, null,
                        null);
            } else if (id == bot_settings) {
                SendMessagesHelper.getInstance().sendMessage("/settings", dialog_id, null, null, false, null,
                        null, null);
            } else if (id == search) {
                openSearchWithText(null);
            }
        }
    });

    avatarContainer = new ChatAvatarContainer(context, this, currentEncryptedChat != null);
    actionBar.addView(avatarContainer, 0, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, 56, 0, 40, 0));

    if (currentChat != null) {
        if (!ChatObject.isChannel(currentChat)) {
            int count = currentChat.participants_count;
            if (info != null) {
                count = info.participants.participants.size();
            }
            if (count == 0 || currentChat.deactivated || currentChat.left
                    || currentChat instanceof TLRPC.TL_chatForbidden
                    || info != null && info.participants instanceof TLRPC.TL_chatParticipantsForbidden) {
                avatarContainer.setEnabled(false);
            }
        }
    }

    ActionBarMenu menu = actionBar.createMenu();

    if (currentEncryptedChat == null && !isBroadcast) {
        searchItem = menu.addItem(0, R.drawable.ic_ab_search).setIsSearchField(true)
                .setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() {

                    @Override
                    public void onSearchCollapse() {
                        avatarContainer.setVisibility(View.VISIBLE);
                        if (chatActivityEnterView.hasText()) {
                            if (headerItem != null) {
                                headerItem.setVisibility(View.GONE);
                            }
                            if (attachItem != null) {
                                attachItem.setVisibility(View.VISIBLE);
                            }
                        } else {
                            if (headerItem != null) {
                                headerItem.setVisibility(View.VISIBLE);
                            }
                            if (attachItem != null) {
                                attachItem.setVisibility(View.GONE);
                            }
                        }
                        searchItem.setVisibility(View.GONE);
                        highlightMessageId = Integer.MAX_VALUE;
                        updateVisibleRows();
                        scrollToLastMessage(false);
                        updateBottomOverlay();
                    }

                    @Override
                    public void onSearchExpand() {
                        if (!openSearchKeyboard) {
                            return;
                        }
                        AndroidUtilities.runOnUIThread(new Runnable() {
                            @Override
                            public void run() {
                                searchItem.getSearchField().requestFocus();
                                AndroidUtilities.showKeyboard(searchItem.getSearchField());
                            }
                        }, 300);
                    }

                    @Override
                    public void onSearchPressed(EditText editText) {
                        updateSearchButtons(0, 0, 0);
                        MessagesSearchQuery.searchMessagesInChat(editText.getText().toString(), dialog_id,
                                mergeDialogId, classGuid, 0);
                    }
                });
        searchItem.getSearchField().setHint(LocaleController.getString("Search", R.string.Search));
        searchItem.setVisibility(View.GONE);
    }

    headerItem = menu.addItem(0, R.drawable.ic_ab_other);
    if (searchItem != null) {
        headerItem.addSubItem(search, LocaleController.getString("Search", R.string.Search), 0);
    }
    if (ChatObject.isChannel(currentChat) && !currentChat.creator
            && (!currentChat.megagroup || currentChat.username != null && currentChat.username.length() > 0)) {
        headerItem.addSubItem(report, LocaleController.getString("ReportChat", R.string.ReportChat), 0);
    }
    if (currentUser != null) {
        addContactItem = headerItem.addSubItem(share_contact, "", 0);
    }
    if (currentEncryptedChat != null) {
        timeItem2 = headerItem.addSubItem(chat_enc_timer,
                LocaleController.getString("SetTimer", R.string.SetTimer), 0);
    }
    if (!ChatObject.isChannel(currentChat)) {
        headerItem.addSubItem(clear_history, LocaleController.getString("ClearHistory", R.string.ClearHistory),
                0);
        if (currentChat != null && !isBroadcast) {
            headerItem.addSubItem(delete_chat,
                    LocaleController.getString("DeleteAndExit", R.string.DeleteAndExit), 0);
        } else {
            headerItem.addSubItem(delete_chat,
                    LocaleController.getString("DeleteChatUser", R.string.DeleteChatUser), 0);
        }
    }
    if (currentUser == null || !currentUser.self) {
        muteItem = headerItem.addSubItem(mute, null, 0);
    }
    if (currentUser != null && currentEncryptedChat == null && currentUser.bot) {
        headerItem.addSubItem(bot_settings, LocaleController.getString("BotSettings", R.string.BotSettings), 0);
        headerItem.addSubItem(bot_help, LocaleController.getString("BotHelp", R.string.BotHelp), 0);
        updateBotButtons();
    }

    updateTitle();
    avatarContainer.updateOnlineCount();
    avatarContainer.updateSubtitle();
    updateTitleIcons();

    attachItem = menu.addItem(chat_menu_attach, R.drawable.ic_ab_other).setOverrideMenuClick(true)
            .setAllowCloseAnimation(false);
    attachItem.setVisibility(View.GONE);
    menuItem = menu.addItem(chat_menu_attach, R.drawable.ic_ab_attach).setAllowCloseAnimation(false);
    menuItem.setBackgroundDrawable(null);

    actionModeViews.clear();

    final ActionBarMenu actionMode = actionBar.createActionMode();

    selectedMessagesCountTextView = new NumberTextView(actionMode.getContext());
    selectedMessagesCountTextView.setTextSize(18);
    selectedMessagesCountTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    selectedMessagesCountTextView.setTextColor(Theme.ACTION_BAR_ACTION_MODE_TEXT_COLOR);
    actionMode.addView(selectedMessagesCountTextView,
            LayoutHelper.createLinear(0, LayoutHelper.MATCH_PARENT, 1.0f, 65, 0, 0, 0));
    selectedMessagesCountTextView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });

    actionModeTitleContainer = new FrameLayout(context) {

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int width = MeasureSpec.getSize(widthMeasureSpec);
            int height = MeasureSpec.getSize(heightMeasureSpec);

            setMeasuredDimension(width, height);

            actionModeTextView.setTextSize(!AndroidUtilities.isTablet()
                    && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE ? 18
                            : 20);
            actionModeTextView.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST),
                    MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(24), MeasureSpec.AT_MOST));

            if (actionModeSubTextView.getVisibility() != GONE) {
                actionModeSubTextView.setTextSize(!AndroidUtilities.isTablet()
                        && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE
                                ? 14
                                : 16);
                actionModeSubTextView.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST),
                        MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(20), MeasureSpec.AT_MOST));
            }
        }

        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            int height = bottom - top;

            int textTop;
            if (actionModeSubTextView.getVisibility() != GONE) {
                textTop = (height / 2 - actionModeTextView.getTextHeight()) / 2
                        + AndroidUtilities.dp(!AndroidUtilities.isTablet() && getResources()
                                .getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE ? 2 : 3);
            } else {
                textTop = (height - actionModeTextView.getTextHeight()) / 2;
            }
            actionModeTextView.layout(0, textTop, actionModeTextView.getMeasuredWidth(),
                    textTop + actionModeTextView.getTextHeight());

            if (actionModeSubTextView.getVisibility() != GONE) {
                textTop = height / 2 + (height / 2 - actionModeSubTextView.getTextHeight()) / 2
                        - AndroidUtilities.dp(!AndroidUtilities.isTablet() && getResources()
                                .getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE ? 1 : 1);
                actionModeSubTextView.layout(0, textTop, actionModeSubTextView.getMeasuredWidth(),
                        textTop + actionModeSubTextView.getTextHeight());
            }
        }
    };
    actionMode.addView(actionModeTitleContainer,
            LayoutHelper.createLinear(0, LayoutHelper.MATCH_PARENT, 1.0f, 65, 0, 0, 0));
    actionModeTitleContainer.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });
    actionModeTitleContainer.setVisibility(View.GONE);

    actionModeTextView = new SimpleTextView(context);
    actionModeTextView.setTextSize(18);
    actionModeTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    actionModeTextView.setTextColor(Theme.ACTION_BAR_ACTION_MODE_TEXT_COLOR);
    actionModeTextView.setText(LocaleController.getString("Edit", R.string.Edit));
    actionModeTitleContainer.addView(actionModeTextView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));

    actionModeSubTextView = new SimpleTextView(context);
    actionModeSubTextView.setGravity(Gravity.LEFT);
    actionModeSubTextView.setTextColor(Theme.ACTION_BAR_ACTION_MODE_TEXT_COLOR);
    actionModeTitleContainer.addView(actionModeSubTextView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));

    if (currentEncryptedChat == null) {
        if (!isBroadcast) {
            actionModeViews.add(actionMode.addItem(reply, R.drawable.ic_ab_reply,
                    Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
        }
        actionModeViews.add(actionMode.addItem(copy, R.drawable.ic_ab_fwd_copy,
                Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
        actionModeViews.add(actionMode.addItem(forward, R.drawable.ic_ab_fwd_forward,
                Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
        actionModeViews.add(actionMode.addItem(delete, R.drawable.ic_ab_fwd_delete,
                Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
        actionModeViews.add(editDoneItem = actionMode.addItem(edit_done, R.drawable.check_blue,
                Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
        editDoneItem.setVisibility(View.GONE);
        editDoneItemProgress = new ContextProgressView(context, 0);
        editDoneItem.addView(editDoneItemProgress,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
        editDoneItemProgress.setVisibility(View.INVISIBLE);
    } else {
        actionModeViews.add(actionMode.addItem(reply, R.drawable.ic_ab_reply,
                Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
        actionModeViews.add(actionMode.addItem(copy, R.drawable.ic_ab_fwd_copy,
                Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
        actionModeViews.add(actionMode.addItem(delete, R.drawable.ic_ab_fwd_delete,
                Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
    }
    actionMode.getItem(copy)
            .setVisibility(selectedMessagesCanCopyIds[0].size() + selectedMessagesCanCopyIds[1].size() != 0
                    ? View.VISIBLE
                    : View.GONE);
    actionMode.getItem(delete).setVisibility(cantDeleteMessagesCount == 0 ? View.VISIBLE : View.GONE);
    checkActionBarMenu();

    fragmentView = new SizeNotifierFrameLayout(context) {

        int inputFieldHeight = 0;

        @Override
        protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
            boolean result = super.drawChild(canvas, child, drawingTime);
            if (child == actionBar) {
                parentLayout.drawHeaderShadow(canvas, actionBar.getMeasuredHeight());
            }
            return result;
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int widthSize = MeasureSpec.getSize(widthMeasureSpec);
            int heightSize = MeasureSpec.getSize(heightMeasureSpec);

            setMeasuredDimension(widthSize, heightSize);
            heightSize -= getPaddingTop();

            measureChildWithMargins(actionBar, widthMeasureSpec, 0, heightMeasureSpec, 0);
            int actionBarHeight = actionBar.getMeasuredHeight();
            heightSize -= actionBarHeight;

            int keyboardSize = getKeyboardHeight();

            if (keyboardSize <= AndroidUtilities.dp(20) && !AndroidUtilities.isInMultiwindow) {
                heightSize -= chatActivityEnterView.getEmojiPadding();
            }

            int childCount = getChildCount();

            measureChildWithMargins(chatActivityEnterView, widthMeasureSpec, 0, heightMeasureSpec, 0);
            inputFieldHeight = chatActivityEnterView.getMeasuredHeight();

            for (int i = 0; i < childCount; i++) {
                View child = getChildAt(i);
                if (child == null || child.getVisibility() == GONE || child == chatActivityEnterView
                        || child == actionBar) {
                    continue;
                }
                if (child == chatListView || child == progressView) {
                    int contentWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
                    int contentHeightSpec = MeasureSpec
                            .makeMeasureSpec(
                                    Math.max(AndroidUtilities.dp(10),
                                            heightSize - inputFieldHeight + AndroidUtilities.dp(
                                                    2 + (chatActivityEnterView.isTopViewVisible() ? 48 : 0))),
                                    MeasureSpec.EXACTLY);
                    child.measure(contentWidthSpec, contentHeightSpec);
                } else if (child == emptyViewContainer) {
                    int contentWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
                    int contentHeightSpec = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY);
                    child.measure(contentWidthSpec, contentHeightSpec);
                } else if (chatActivityEnterView.isPopupView(child)) {
                    if (AndroidUtilities.isInMultiwindow) {
                        if (AndroidUtilities.isTablet()) {
                            child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY),
                                    MeasureSpec.makeMeasureSpec(Math.min(AndroidUtilities.dp(320),
                                            heightSize - inputFieldHeight + actionBarHeight
                                                    - AndroidUtilities.statusBarHeight + getPaddingTop()),
                                            MeasureSpec.EXACTLY));
                        } else {
                            child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY),
                                    MeasureSpec.makeMeasureSpec(
                                            heightSize - inputFieldHeight + actionBarHeight
                                                    - AndroidUtilities.statusBarHeight + getPaddingTop(),
                                            MeasureSpec.EXACTLY));
                        }
                    } else {
                        child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec
                                .makeMeasureSpec(child.getLayoutParams().height, MeasureSpec.EXACTLY));
                    }
                } else if (child == mentionContainer) {
                    FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mentionContainer
                            .getLayoutParams();
                    int height;
                    mentionListViewIgnoreLayout = true;

                    if (mentionsAdapter.isBotContext() && mentionsAdapter.isMediaLayout()) {
                        int size = mentionGridLayoutManager.getRowsCount(widthSize);
                        int maxHeight = size * 102;
                        if (mentionsAdapter.isBotContext()) {
                            if (mentionsAdapter.getBotContextSwitch() != null) {
                                maxHeight += 34;
                            }
                        }
                        height = heightSize - chatActivityEnterView.getMeasuredHeight()
                                + (maxHeight != 0 ? AndroidUtilities.dp(2) : 0);
                        mentionListView.setPadding(0,
                                Math.max(0, height - AndroidUtilities.dp(Math.min(maxHeight, 68 * 1.8f))), 0,
                                0);
                    } else {
                        int size = mentionsAdapter.getItemCount();
                        int maxHeight = 0;
                        if (mentionsAdapter.isBotContext()) {
                            if (mentionsAdapter.getBotContextSwitch() != null) {
                                maxHeight += 36;
                                size -= 1;
                            }
                            maxHeight += size * 68;
                        } else {
                            maxHeight += size * 36;
                        }
                        height = heightSize - chatActivityEnterView.getMeasuredHeight()
                                + (maxHeight != 0 ? AndroidUtilities.dp(2) : 0);
                        mentionListView.setPadding(0,
                                Math.max(0, height - AndroidUtilities.dp(Math.min(maxHeight, 68 * 1.8f))), 0,
                                0);
                    }

                    layoutParams.height = height;
                    layoutParams.topMargin = 0;

                    mentionListViewIgnoreLayout = false;
                    child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY),
                            MeasureSpec.makeMeasureSpec(layoutParams.height, MeasureSpec.EXACTLY));
                } else {
                    measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
                }
            }
        }

        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
            final int count = getChildCount();

            int paddingBottom = getKeyboardHeight() <= AndroidUtilities.dp(20)
                    && !AndroidUtilities.isInMultiwindow ? chatActivityEnterView.getEmojiPadding() : 0;
            setBottomClip(paddingBottom);

            for (int i = 0; i < count; i++) {
                final View child = getChildAt(i);
                if (child.getVisibility() == GONE) {
                    continue;
                }
                final LayoutParams lp = (LayoutParams) child.getLayoutParams();

                final int width = child.getMeasuredWidth();
                final int height = child.getMeasuredHeight();

                int childLeft;
                int childTop;

                int gravity = lp.gravity;
                if (gravity == -1) {
                    gravity = Gravity.TOP | Gravity.LEFT;
                }

                final int absoluteGravity = gravity & Gravity.HORIZONTAL_GRAVITY_MASK;
                final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;

                switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
                case Gravity.CENTER_HORIZONTAL:
                    childLeft = (r - l - width) / 2 + lp.leftMargin - lp.rightMargin;
                    break;
                case Gravity.RIGHT:
                    childLeft = r - width - lp.rightMargin;
                    break;
                case Gravity.LEFT:
                default:
                    childLeft = lp.leftMargin;
                }

                switch (verticalGravity) {
                case Gravity.TOP:
                    childTop = lp.topMargin + getPaddingTop();
                    if (child != actionBar) {
                        childTop += actionBar.getMeasuredHeight();
                    }
                    break;
                case Gravity.CENTER_VERTICAL:
                    childTop = ((b - paddingBottom) - t - height) / 2 + lp.topMargin - lp.bottomMargin;
                    break;
                case Gravity.BOTTOM:
                    childTop = ((b - paddingBottom) - t) - height - lp.bottomMargin;
                    break;
                default:
                    childTop = lp.topMargin;
                }

                if (child == mentionContainer) {
                    childTop -= chatActivityEnterView.getMeasuredHeight() - AndroidUtilities.dp(2);
                } else if (child == pagedownButton) {
                    childTop -= chatActivityEnterView.getMeasuredHeight();
                } else if (child == emptyViewContainer) {
                    childTop -= inputFieldHeight / 2 - actionBar.getMeasuredHeight() / 2;
                } else if (chatActivityEnterView.isPopupView(child)) {
                    if (AndroidUtilities.isInMultiwindow) {
                        childTop = chatActivityEnterView.getTop() - child.getMeasuredHeight()
                                + AndroidUtilities.dp(1);
                    } else {
                        childTop = chatActivityEnterView.getBottom();
                    }
                } else if (child == gifHintTextView) {
                    childTop -= inputFieldHeight;
                } else if (child == chatListView || child == progressView) {
                    if (chatActivityEnterView.isTopViewVisible()) {
                        childTop -= AndroidUtilities.dp(48);
                    }
                } else if (child == actionBar) {
                    childTop -= getPaddingTop();
                }
                child.layout(childLeft, childTop, childLeft + width, childTop + height);
            }

            updateMessagesVisisblePart();
            notifyHeightChanged();
        }
    };

    SizeNotifierFrameLayout contentView = (SizeNotifierFrameLayout) fragmentView;

    contentView.setBackgroundImage(ApplicationLoader.getCachedWallpaper());

    emptyViewContainer = new FrameLayout(context);
    emptyViewContainer.setVisibility(View.INVISIBLE);
    contentView.addView(emptyViewContainer,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
    emptyViewContainer.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });

    if (currentEncryptedChat == null) {
        if (currentUser != null && currentUser.self) {
            bigEmptyView = new ChatBigEmptyView(context, false);
            emptyViewContainer.addView(bigEmptyView, new FrameLayout.LayoutParams(LayoutHelper.WRAP_CONTENT,
                    LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
        } else {
            TextView emptyView = new TextView(context);
            if (currentUser != null && currentUser.id != 777000 && currentUser.id != 429000
                    && (currentUser.id / 1000 == 333 || currentUser.id % 1000 == 0)) {
                emptyView.setText(LocaleController.getString("GotAQuestion", R.string.GotAQuestion));
            } else {
                emptyView.setText(LocaleController.getString("NoMessages", R.string.NoMessages));
            }
            emptyView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
            emptyView.setGravity(Gravity.CENTER);
            emptyView.setTextColor(Theme.CHAT_EMPTY_VIEW_TEXT_COLOR);
            emptyView.setBackgroundResource(R.drawable.system);
            emptyView.getBackground().setColorFilter(Theme.colorFilter);
            emptyView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
            emptyView.setPadding(AndroidUtilities.dp(10), AndroidUtilities.dp(2), AndroidUtilities.dp(10),
                    AndroidUtilities.dp(3));
            emptyViewContainer.addView(emptyView, new FrameLayout.LayoutParams(LayoutHelper.WRAP_CONTENT,
                    LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
        }
    } else {
        bigEmptyView = new ChatBigEmptyView(context, true);
        if (currentEncryptedChat.admin_id == UserConfig.getClientUserId()) {
            bigEmptyView.setSecretText(LocaleController.formatString("EncryptedPlaceholderTitleOutgoing",
                    R.string.EncryptedPlaceholderTitleOutgoing, UserObject.getFirstName(currentUser)));
        } else {
            bigEmptyView.setSecretText(LocaleController.formatString("EncryptedPlaceholderTitleIncoming",
                    R.string.EncryptedPlaceholderTitleIncoming, UserObject.getFirstName(currentUser)));
        }
        emptyViewContainer.addView(bigEmptyView, new FrameLayout.LayoutParams(LayoutHelper.WRAP_CONTENT,
                LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
    }

    if (chatActivityEnterView != null) {
        chatActivityEnterView.onDestroy();
    }
    if (mentionsAdapter != null) {
        mentionsAdapter.onDestroy();
    }

    chatListView = new RecyclerListView(context) {
        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
            super.onLayout(changed, l, t, r, b);
            forceScrollToTop = false;
            if (chatAdapter.isBot) {
                int childCount = getChildCount();
                for (int a = 0; a < childCount; a++) {
                    View child = getChildAt(a);
                    if (child instanceof BotHelpCell) {
                        int height = b - t;
                        int top = height / 2 - child.getMeasuredHeight() / 2;
                        if (child.getTop() > top) {
                            child.layout(0, top, r - l, top + child.getMeasuredHeight());
                        }
                        break;
                    }
                }
            }
        }
    };
    chatListView.setTag(1);
    chatListView.setVerticalScrollBarEnabled(true);
    chatListView.setAdapter(chatAdapter = new ChatActivityAdapter(context));
    chatListView.setClipToPadding(false);
    chatListView.setPadding(0, AndroidUtilities.dp(4), 0, AndroidUtilities.dp(3));
    chatListView.setItemAnimator(null);
    chatListView.setLayoutAnimation(null);
    chatLayoutManager = new LinearLayoutManager(context) {
        @Override
        public boolean supportsPredictiveItemAnimations() {
            return false;
        }
    };
    chatLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    chatLayoutManager.setStackFromEnd(true);
    chatListView.setLayoutManager(chatLayoutManager);
    contentView.addView(chatListView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    chatListView.setOnItemLongClickListener(onItemLongClickListener);
    chatListView.setOnItemClickListener(onItemClickListener);
    chatListView.setOnScrollListener(new RecyclerView.OnScrollListener() {

        private float totalDy = 0;
        private final int scrollValue = AndroidUtilities.dp(100);

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            if (newState == RecyclerView.SCROLL_STATE_DRAGGING && highlightMessageId != Integer.MAX_VALUE) {
                highlightMessageId = Integer.MAX_VALUE;
                updateVisibleRows();
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            checkScrollForLoad(true);
            int firstVisibleItem = chatLayoutManager.findFirstVisibleItemPosition();
            int visibleItemCount = firstVisibleItem == RecyclerView.NO_POSITION ? 0
                    : Math.abs(chatLayoutManager.findLastVisibleItemPosition() - firstVisibleItem) + 1;
            if (visibleItemCount > 0) {
                int totalItemCount = chatAdapter.getItemCount();
                if (firstVisibleItem + visibleItemCount == totalItemCount && forwardEndReached[0]) {
                    showPagedownButton(false, true);
                } else {
                    if (dy > 0) {
                        if (pagedownButton.getTag() == null) {
                            totalDy += dy;
                            if (totalDy > scrollValue) {
                                totalDy = 0;
                                showPagedownButton(true, true);
                                pagedownButtonShowedByScroll = true;
                            }
                        }
                    } else {
                        if (pagedownButtonShowedByScroll && pagedownButton.getTag() != null) {
                            totalDy += dy;
                            if (totalDy < -scrollValue) {
                                showPagedownButton(false, true);
                                totalDy = 0;
                            }
                        }
                    }
                }
            }
            updateMessagesVisisblePart();
        }
    });
    chatListView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (openSecretPhotoRunnable != null || SecretPhotoViewer.getInstance().isVisible()) {
                if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL
                        || event.getAction() == MotionEvent.ACTION_POINTER_UP) {
                    AndroidUtilities.runOnUIThread(new Runnable() {
                        @Override
                        public void run() {
                            chatListView.setOnItemClickListener(onItemClickListener);
                        }
                    }, 150);
                    if (openSecretPhotoRunnable != null) {
                        AndroidUtilities.cancelRunOnUIThread(openSecretPhotoRunnable);
                        openSecretPhotoRunnable = null;
                        try {
                            Toast.makeText(v.getContext(),
                                    LocaleController.getString("PhotoTip", R.string.PhotoTip),
                                    Toast.LENGTH_SHORT).show();
                        } catch (Exception e) {
                            FileLog.e("tmessages", e);
                        }
                    } else if (SecretPhotoViewer.getInstance().isVisible()) {
                        AndroidUtilities.runOnUIThread(new Runnable() {
                            @Override
                            public void run() {
                                chatListView.setOnItemLongClickListener(onItemLongClickListener);
                                chatListView.setLongClickable(true);
                            }
                        });
                        SecretPhotoViewer.getInstance().closePhoto();
                    }
                } else if (event.getAction() != MotionEvent.ACTION_DOWN) {
                    if (SecretPhotoViewer.getInstance().isVisible()) {
                        return true;
                    } else if (openSecretPhotoRunnable != null) {
                        if (event.getAction() == MotionEvent.ACTION_MOVE) {
                            if (Math.hypot(startX - event.getX(), startY - event.getY()) > AndroidUtilities
                                    .dp(5)) {
                                AndroidUtilities.cancelRunOnUIThread(openSecretPhotoRunnable);
                                openSecretPhotoRunnable = null;
                            }
                        } else {
                            AndroidUtilities.cancelRunOnUIThread(openSecretPhotoRunnable);
                            openSecretPhotoRunnable = null;
                        }
                        chatListView.setOnItemClickListener(onItemClickListener);
                        chatListView.setOnItemLongClickListener(onItemLongClickListener);
                        chatListView.setLongClickable(true);
                    }
                }
            }
            return false;
        }
    });
    chatListView.setOnInterceptTouchListener(new RecyclerListView.OnInterceptTouchListener() {
        @Override
        public boolean onInterceptTouchEvent(MotionEvent event) {
            if (chatActivityEnterView != null && chatActivityEnterView.isEditingMessage()) {
                return true;
            }
            if (actionBar.isActionModeShowed()) {
                return false;
            }
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                int x = (int) event.getX();
                int y = (int) event.getY();
                int count = chatListView.getChildCount();
                for (int a = 0; a < count; a++) {
                    View view = chatListView.getChildAt(a);
                    int top = view.getTop();
                    int bottom = view.getBottom();
                    if (top > y || bottom < y) {
                        continue;
                    }
                    if (!(view instanceof ChatMessageCell)) {
                        break;
                    }
                    final ChatMessageCell cell = (ChatMessageCell) view;
                    final MessageObject messageObject = cell.getMessageObject();
                    if (messageObject == null || messageObject.isSending() || !messageObject.isSecretPhoto()
                            || !cell.getPhotoImage().isInsideImage(x, y - top)) {
                        break;
                    }
                    File file = FileLoader.getPathToMessage(messageObject.messageOwner);
                    if (!file.exists()) {
                        break;
                    }
                    startX = x;
                    startY = y;
                    chatListView.setOnItemClickListener(null);
                    openSecretPhotoRunnable = new Runnable() {
                        @Override
                        public void run() {
                            if (openSecretPhotoRunnable == null) {
                                return;
                            }
                            chatListView.requestDisallowInterceptTouchEvent(true);
                            chatListView.setOnItemLongClickListener(null);
                            chatListView.setLongClickable(false);
                            openSecretPhotoRunnable = null;
                            if (sendSecretMessageRead(messageObject)) {
                                cell.invalidate();
                            }
                            SecretPhotoViewer.getInstance().setParentActivity(getParentActivity());
                            SecretPhotoViewer.getInstance().openPhoto(messageObject);
                        }
                    };
                    AndroidUtilities.runOnUIThread(openSecretPhotoRunnable, 100);
                    return true;
                }
            }
            return false;
        }
    });

    progressView = new FrameLayout(context);
    progressView.setVisibility(View.INVISIBLE);
    contentView.addView(progressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));

    View view = new View(context);
    view.setBackgroundResource(R.drawable.system_loader);
    view.getBackground().setColorFilter(Theme.colorFilter);
    progressView.addView(view, LayoutHelper.createFrame(36, 36, Gravity.CENTER));

    ProgressBar progressBar = new ProgressBar(context);
    try {
        progressBar.setIndeterminateDrawable(context.getResources().getDrawable(R.drawable.loading_animation));
    } catch (Exception e) {
        //don't promt
    }
    progressBar.setIndeterminate(true);
    AndroidUtilities.setProgressBarAnimationDuration(progressBar, 1500);
    progressView.addView(progressBar, LayoutHelper.createFrame(32, 32, Gravity.CENTER));

    if (ChatObject.isChannel(currentChat)) {
        pinnedMessageView = new FrameLayout(context);
        pinnedMessageView.setTag(1);
        pinnedMessageView.setTranslationY(-AndroidUtilities.dp(50));
        pinnedMessageView.setVisibility(View.GONE);
        pinnedMessageView.setBackgroundResource(R.drawable.blockpanel);
        contentView.addView(pinnedMessageView,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 50, Gravity.TOP | Gravity.LEFT));
        pinnedMessageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scrollToMessageId(info.pinned_msg_id, 0, true, 0);
            }
        });

        View lineView = new View(context);
        lineView.setBackgroundColor(0xff6c9fd2);
        pinnedMessageView.addView(lineView,
                LayoutHelper.createFrame(2, 32, Gravity.LEFT | Gravity.TOP, 8, 8, 0, 0));

        pinnedMessageImageView = new BackupImageView(context);
        pinnedMessageView.addView(pinnedMessageImageView,
                LayoutHelper.createFrame(32, 32, Gravity.TOP | Gravity.LEFT, 17, 8, 0, 0));

        pinnedMessageNameTextView = new SimpleTextView(context);
        pinnedMessageNameTextView.setTextSize(14);
        pinnedMessageNameTextView.setTextColor(Theme.PINNED_PANEL_NAME_TEXT_COLOR);
        pinnedMessageNameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
        pinnedMessageView.addView(pinnedMessageNameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
                AndroidUtilities.dp(18), Gravity.TOP | Gravity.LEFT, 18, 7.3f, 52, 0));

        pinnedMessageTextView = new SimpleTextView(context);
        pinnedMessageTextView.setTextSize(14);
        pinnedMessageTextView.setTextColor(Theme.PINNED_PANEL_MESSAGE_TEXT_COLOR);
        pinnedMessageView.addView(pinnedMessageTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
                AndroidUtilities.dp(18), Gravity.TOP | Gravity.LEFT, 18, 25.3f, 52, 0));

        ImageView closePinned = new ImageView(context);
        closePinned.setImageResource(R.drawable.miniplayer_close);
        closePinned.setScaleType(ImageView.ScaleType.CENTER);
        pinnedMessageView.addView(closePinned, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.TOP));
        closePinned.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getParentActivity() == null) {
                    return;
                }
                if (currentChat.creator || currentChat.editor) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                    builder.setMessage(
                            LocaleController.getString("UnpinMessageAlert", R.string.UnpinMessageAlert));
                    builder.setPositiveButton(LocaleController.getString("OK", R.string.OK),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    MessagesController.getInstance().pinChannelMessage(currentChat, 0, false);
                                }
                            });
                    builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                    builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                    showDialog(builder.create());
                } else {
                    SharedPreferences preferences = ApplicationLoader.applicationContext
                            .getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
                    preferences.edit().putInt("pin_" + dialog_id, info.pinned_msg_id).commit();
                    updatePinnedMessageView(true);
                }
            }
        });
    }

    reportSpamView = new LinearLayout(context);
    reportSpamView.setTag(1);
    reportSpamView.setTranslationY(-AndroidUtilities.dp(50));
    reportSpamView.setVisibility(View.GONE);
    reportSpamView.setBackgroundResource(R.drawable.blockpanel);
    contentView.addView(reportSpamView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 50, Gravity.TOP | Gravity.LEFT));

    addToContactsButton = new TextView(context);
    addToContactsButton.setTextColor(Theme.CHAT_ADD_CONTACT_TEXT_COLOR);
    addToContactsButton.setVisibility(View.GONE);
    addToContactsButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    addToContactsButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    addToContactsButton.setSingleLine(true);
    addToContactsButton.setMaxLines(1);
    addToContactsButton.setPadding(AndroidUtilities.dp(4), 0, AndroidUtilities.dp(4), 0);
    addToContactsButton.setGravity(Gravity.CENTER);
    addToContactsButton.setText(LocaleController.getString("AddContactChat", R.string.AddContactChat));
    reportSpamView.addView(addToContactsButton, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT,
            LayoutHelper.MATCH_PARENT, 0.5f, Gravity.LEFT | Gravity.TOP, 0, 0, 0, AndroidUtilities.dp(1)));
    addToContactsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Bundle args = new Bundle();
            args.putInt("user_id", currentUser.id);
            args.putBoolean("addContact", true);
            presentFragment(new ContactAddActivity(args));
        }
    });

    reportSpamContainer = new FrameLayout(context);
    reportSpamView.addView(reportSpamContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT,
            LayoutHelper.MATCH_PARENT, 1.0f, Gravity.LEFT | Gravity.TOP, 0, 0, 0, AndroidUtilities.dp(1)));

    reportSpamButton = new TextView(context);
    reportSpamButton.setTextColor(Theme.CHAT_REPORT_SPAM_TEXT_COLOR);
    reportSpamButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    reportSpamButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    reportSpamButton.setSingleLine(true);
    reportSpamButton.setMaxLines(1);
    if (currentChat != null) {
        reportSpamButton.setText(LocaleController.getString("ReportSpamAndLeave", R.string.ReportSpamAndLeave));
    } else {
        reportSpamButton.setText(LocaleController.getString("ReportSpam", R.string.ReportSpam));
    }
    reportSpamButton.setGravity(Gravity.CENTER);
    reportSpamButton.setPadding(AndroidUtilities.dp(50), 0, AndroidUtilities.dp(50), 0);
    reportSpamContainer.addView(reportSpamButton, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
    reportSpamButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (getParentActivity() == null) {
                return;
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
            if (ChatObject.isChannel(currentChat) && !currentChat.megagroup) {
                builder.setMessage(
                        LocaleController.getString("ReportSpamAlertChannel", R.string.ReportSpamAlertChannel));
            } else if (currentChat != null) {
                builder.setMessage(
                        LocaleController.getString("ReportSpamAlertGroup", R.string.ReportSpamAlertGroup));
            } else {
                builder.setMessage(LocaleController.getString("ReportSpamAlert", R.string.ReportSpamAlert));
            }
            builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
            builder.setPositiveButton(LocaleController.getString("OK", R.string.OK),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            if (currentUser != null) {
                                MessagesController.getInstance().blockUser(currentUser.id);
                            }
                            MessagesController.getInstance().reportSpam(dialog_id, currentUser, currentChat);
                            updateSpamView();
                            if (currentChat != null) {
                                if (ChatObject.isNotInChat(currentChat)) {
                                    MessagesController.getInstance().deleteDialog(dialog_id, 0);
                                } else {
                                    MessagesController.getInstance().deleteUserFromChat((int) -dialog_id,
                                            MessagesController.getInstance()
                                                    .getUser(UserConfig.getClientUserId()),
                                            null);
                                }
                            } else {
                                MessagesController.getInstance().deleteDialog(dialog_id, 0);
                            }
                            finishFragment();
                        }
                    });
            builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
            showDialog(builder.create());
        }
    });

    ImageView closeReportSpam = new ImageView(context);
    closeReportSpam.setImageResource(R.drawable.miniplayer_close);
    closeReportSpam.setScaleType(ImageView.ScaleType.CENTER);
    reportSpamContainer.addView(closeReportSpam, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.TOP));
    closeReportSpam.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MessagesController.getInstance().hideReportSpam(dialog_id, currentUser, currentChat);
            updateSpamView();
        }
    });

    alertView = new FrameLayout(context);
    alertView.setTag(1);
    alertView.setTranslationY(-AndroidUtilities.dp(50));
    alertView.setVisibility(View.GONE);
    alertView.setBackgroundResource(R.drawable.blockpanel);
    contentView.addView(alertView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 50, Gravity.TOP | Gravity.LEFT));

    alertNameTextView = new TextView(context);
    alertNameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    alertNameTextView.setTextColor(Theme.ALERT_PANEL_NAME_TEXT_COLOR);
    alertNameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    alertNameTextView.setSingleLine(true);
    alertNameTextView.setEllipsize(TextUtils.TruncateAt.END);
    alertNameTextView.setMaxLines(1);
    alertView.addView(alertNameTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 8, 5, 8, 0));

    alertTextView = new TextView(context);
    alertTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    alertTextView.setTextColor(Theme.ALERT_PANEL_MESSAGE_TEXT_COLOR);
    alertTextView.setSingleLine(true);
    alertTextView.setEllipsize(TextUtils.TruncateAt.END);
    alertTextView.setMaxLines(1);
    alertView.addView(alertTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 8, 23, 8, 0));

    if (!isBroadcast) {
        mentionContainer = new FrameLayout(context) {

            private Drawable background;

            @Override
            public void onDraw(Canvas canvas) {
                if (mentionListView.getChildCount() <= 0) {
                    return;
                }
                if (mentionsAdapter.isBotContext() && mentionsAdapter.isMediaLayout()
                        && mentionsAdapter.getBotContextSwitch() == null) {
                    background.setBounds(0, mentionListViewScrollOffsetY - AndroidUtilities.dp(4),
                            getMeasuredWidth(), getMeasuredHeight());
                } else {
                    background.setBounds(0, mentionListViewScrollOffsetY - AndroidUtilities.dp(2),
                            getMeasuredWidth(), getMeasuredHeight());
                }
                background.draw(canvas);
            }

            @Override
            public void setBackgroundResource(int resid) {
                background = getContext().getResources().getDrawable(resid);
            }

            @Override
            public void requestLayout() {
                if (mentionListViewIgnoreLayout) {
                    return;
                }
                super.requestLayout();
            }
        };
        mentionContainer.setBackgroundResource(R.drawable.compose_panel);
        mentionContainer.setVisibility(View.GONE);
        mentionContainer.setWillNotDraw(false);
        contentView.addView(mentionContainer,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 110, Gravity.LEFT | Gravity.BOTTOM));

        mentionListView = new RecyclerListView(context) {

            private int lastWidth;
            private int lastHeight;

            @Override
            public boolean onInterceptTouchEvent(MotionEvent event) {
                if (!mentionListViewIsScrolling && mentionListViewScrollOffsetY != 0
                        && event.getY() < mentionListViewScrollOffsetY) {
                    return false;
                }
                boolean result = StickerPreviewViewer.getInstance().onInterceptTouchEvent(event,
                        mentionListView, 0);
                return super.onInterceptTouchEvent(event) || result;
            }

            @Override
            public boolean onTouchEvent(MotionEvent event) {
                if (!mentionListViewIsScrolling && mentionListViewScrollOffsetY != 0
                        && event.getY() < mentionListViewScrollOffsetY) {
                    return false;
                }
                //supress warning
                return super.onTouchEvent(event);
            }

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

            @Override
            protected void onLayout(boolean changed, int l, int t, int r, int b) {
                int width = r - l;
                int height = b - t;

                int newPosition = -1;
                int newTop = 0;
                if (mentionListView != null && mentionListViewLastViewPosition >= 0 && width == lastWidth
                        && height - lastHeight != 0) {
                    newPosition = mentionListViewLastViewPosition;
                    newTop = mentionListViewLastViewTop + height - lastHeight - getPaddingTop();
                }

                super.onLayout(changed, l, t, r, b);

                if (newPosition != -1) {
                    mentionListViewIgnoreLayout = true;
                    if (mentionsAdapter.isBotContext() && mentionsAdapter.isMediaLayout()) {
                        mentionGridLayoutManager.scrollToPositionWithOffset(newPosition, newTop);
                    } else {
                        mentionLayoutManager.scrollToPositionWithOffset(newPosition, newTop);
                    }
                    super.onLayout(false, l, t, r, b);
                    mentionListViewIgnoreLayout = false;
                }

                lastHeight = height;
                lastWidth = width;
                mentionListViewUpdateLayout();
            }
        };
        mentionListView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return StickerPreviewViewer.getInstance().onTouch(event, mentionListView, 0,
                        mentionsOnItemClickListener);
            }
        });
        mentionListView.setTag(2);
        mentionLayoutManager = new LinearLayoutManager(context) {
            @Override
            public boolean supportsPredictiveItemAnimations() {
                return false;
            }
        };
        mentionLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mentionGridLayoutManager = new ExtendedGridLayoutManager(context, 100) {

            private Size size = new Size();

            @Override
            protected Size getSizeForItem(int i) {
                if (mentionsAdapter.getBotContextSwitch() != null) {
                    i++;
                }
                Object object = mentionsAdapter.getItem(i);
                if (object instanceof TLRPC.BotInlineResult) {
                    TLRPC.BotInlineResult inlineResult = (TLRPC.BotInlineResult) object;
                    if (inlineResult.document != null) {
                        size.width = inlineResult.document.thumb != null ? inlineResult.document.thumb.w : 100;
                        size.height = inlineResult.document.thumb != null ? inlineResult.document.thumb.h : 100;
                        for (int b = 0; b < inlineResult.document.attributes.size(); b++) {
                            TLRPC.DocumentAttribute attribute = inlineResult.document.attributes.get(b);
                            if (attribute instanceof TLRPC.TL_documentAttributeImageSize
                                    || attribute instanceof TLRPC.TL_documentAttributeVideo) {
                                size.width = attribute.w;
                                size.height = attribute.h;
                                break;
                            }
                        }
                    } else {
                        size.width = inlineResult.w;
                        size.height = inlineResult.h;
                    }
                }
                return size;
            }

            @Override
            protected int getFlowItemCount() {
                if (mentionsAdapter.getBotContextSwitch() != null) {
                    return getItemCount() - 1;
                }
                return super.getFlowItemCount();
            }
        };
        mentionGridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                Object object = mentionsAdapter.getItem(position);
                if (object instanceof TLRPC.TL_inlineBotSwitchPM) {
                    return 100;
                } else {
                    if (mentionsAdapter.getBotContextSwitch() != null) {
                        position--;
                    }
                    return mentionGridLayoutManager.getSpanSizeForItem(position);
                }
            }
        });
        mentionListView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.left = 0;
                outRect.right = 0;
                outRect.top = 0;
                outRect.bottom = 0;
                if (parent.getLayoutManager() == mentionGridLayoutManager) {
                    int position = parent.getChildAdapterPosition(view);
                    if (mentionsAdapter.getBotContextSwitch() != null) {
                        if (position == 0) {
                            return;
                        }
                        position--;
                        if (!mentionGridLayoutManager.isFirstRow(position)) {
                            outRect.top = AndroidUtilities.dp(2);
                        }
                    } else {
                        outRect.top = AndroidUtilities.dp(2);
                    }
                    outRect.right = mentionGridLayoutManager.isLastInRow(position) ? 0 : AndroidUtilities.dp(2);
                }
            }
        });
        mentionListView.setItemAnimator(null);
        mentionListView.setLayoutAnimation(null);
        mentionListView.setClipToPadding(false);
        mentionListView.setLayoutManager(mentionLayoutManager);
        mentionListView.setOverScrollMode(ListView.OVER_SCROLL_NEVER);
        mentionContainer.addView(mentionListView,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));

        mentionListView.setAdapter(mentionsAdapter = new MentionsAdapter(context, false, dialog_id,
                new MentionsAdapter.MentionsAdapterDelegate() {
                    @Override
                    public void needChangePanelVisibility(boolean show) {
                        if (mentionsAdapter.isBotContext() && mentionsAdapter.isMediaLayout()) {
                            mentionListView.setLayoutManager(mentionGridLayoutManager);
                        } else {
                            mentionListView.setLayoutManager(mentionLayoutManager);
                        }
                        if (show) {
                            if (mentionListAnimation != null) {
                                mentionListAnimation.cancel();
                                mentionListAnimation = null;
                            }

                            if (mentionContainer.getVisibility() == View.VISIBLE) {
                                mentionContainer.setAlpha(1.0f);
                                return;
                            }
                            if (mentionsAdapter.isBotContext() && mentionsAdapter.isMediaLayout()) {
                                mentionGridLayoutManager.scrollToPositionWithOffset(0, 10000);
                            } else {
                                mentionLayoutManager.scrollToPositionWithOffset(0, 10000);
                            }
                            if (allowStickersPanel && (!mentionsAdapter.isBotContext()
                                    || (allowContextBotPanel || allowContextBotPanelSecond))) {
                                if (currentEncryptedChat != null && mentionsAdapter.isBotContext()) {
                                    SharedPreferences preferences = ApplicationLoader.applicationContext
                                            .getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
                                    if (!preferences.getBoolean("secretbot", false)) {
                                        AlertDialog.Builder builder = new AlertDialog.Builder(
                                                getParentActivity());
                                        builder.setTitle(
                                                LocaleController.getString("AppName", R.string.AppName));
                                        builder.setMessage(
                                                LocaleController.getString("SecretChatContextBotAlert",
                                                        R.string.SecretChatContextBotAlert));
                                        builder.setPositiveButton(LocaleController.getString("OK", R.string.OK),
                                                null);
                                        showDialog(builder.create());
                                        preferences.edit().putBoolean("secretbot", true).commit();
                                    }
                                }
                                mentionContainer.setVisibility(View.VISIBLE);
                                mentionContainer.setTag(null);
                                mentionListAnimation = new AnimatorSet();
                                mentionListAnimation.playTogether(
                                        ObjectAnimator.ofFloat(mentionContainer, "alpha", 0.0f, 1.0f));
                                mentionListAnimation.addListener(new AnimatorListenerAdapterProxy() {
                                    @Override
                                    public void onAnimationEnd(Animator animation) {
                                        if (mentionListAnimation != null
                                                && mentionListAnimation.equals(animation)) {
                                            mentionListAnimation = null;
                                        }
                                    }

                                    @Override
                                    public void onAnimationCancel(Animator animation) {
                                        if (mentionListAnimation != null
                                                && mentionListAnimation.equals(animation)) {
                                            mentionListAnimation = null;
                                        }
                                    }
                                });
                                mentionListAnimation.setDuration(200);
                                mentionListAnimation.start();
                            } else {
                                mentionContainer.setAlpha(1.0f);
                                mentionContainer.setVisibility(View.INVISIBLE);
                            }
                        } else {
                            if (mentionListAnimation != null) {
                                mentionListAnimation.cancel();
                                mentionListAnimation = null;
                            }

                            if (mentionContainer.getVisibility() == View.GONE) {
                                return;
                            }
                            if (allowStickersPanel) {
                                mentionListAnimation = new AnimatorSet();
                                mentionListAnimation
                                        .playTogether(ObjectAnimator.ofFloat(mentionContainer, "alpha", 0.0f));
                                mentionListAnimation.addListener(new AnimatorListenerAdapterProxy() {
                                    @Override
                                    public void onAnimationEnd(Animator animation) {
                                        if (mentionListAnimation != null
                                                && mentionListAnimation.equals(animation)) {
                                            mentionContainer.setVisibility(View.GONE);
                                            mentionContainer.setTag(null);
                                            mentionListAnimation = null;
                                        }
                                    }

                                    @Override
                                    public void onAnimationCancel(Animator animation) {
                                        if (mentionListAnimation != null
                                                && mentionListAnimation.equals(animation)) {
                                            mentionListAnimation = null;
                                        }
                                    }
                                });
                                mentionListAnimation.setDuration(200);
                                mentionListAnimation.start();
                            } else {
                                mentionContainer.setTag(null);
                                mentionContainer.setVisibility(View.GONE);
                            }
                        }
                    }

                    @Override
                    public void onContextSearch(boolean searching) {
                        if (chatActivityEnterView != null) {
                            chatActivityEnterView.setCaption(mentionsAdapter.getBotCaption());
                            chatActivityEnterView.showContextProgress(searching);
                        }
                    }

                    @Override
                    public void onContextClick(TLRPC.BotInlineResult result) {
                        if (getParentActivity() == null || result.content_url == null) {
                            return;
                        }
                        if (result.type.equals("video") || result.type.equals("web_player_video")) {
                            BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity());
                            builder.setCustomView(new WebFrameLayout(getParentActivity(), builder.create(),
                                    result.title != null ? result.title : "", result.description,
                                    result.content_url, result.content_url, result.w, result.h));
                            builder.setUseFullWidth(true);
                            showDialog(builder.create());
                        } else {
                            Browser.openUrl(getParentActivity(), result.content_url);
                        }
                    }
                }));
        if (!ChatObject.isChannel(currentChat) || currentChat != null && currentChat.megagroup) {
            mentionsAdapter.setBotInfo(botInfo);
        }
        mentionsAdapter.setParentFragment(this);
        mentionsAdapter.setChatInfo(info);
        mentionsAdapter.setNeedUsernames(currentChat != null);
        mentionsAdapter.setNeedBotContext(currentEncryptedChat == null
                || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 46);
        mentionsAdapter.setBotsCount(currentChat != null ? botsCount : 1);
        mentionListView.setOnItemClickListener(
                mentionsOnItemClickListener = new RecyclerListView.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        Object object = mentionsAdapter.getItem(position);
                        int start = mentionsAdapter.getResultStartPosition();
                        int len = mentionsAdapter.getResultLength();
                        if (object instanceof TLRPC.User) {
                            TLRPC.User user = (TLRPC.User) object;
                            if (user != null) {
                                if (user.username != null) {
                                    chatActivityEnterView.replaceWithText(start, len,
                                            "@" + user.username + " ");
                                } else {
                                    String name = user.first_name;
                                    if (name == null || name.length() == 0) {
                                        name = user.last_name;
                                    }
                                    Spannable spannable = new SpannableString(name + " ");
                                    spannable.setSpan(new URLSpanUserMention("" + user.id), 0,
                                            spannable.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    chatActivityEnterView.replaceWithText(start, len, spannable);
                                }
                            }
                        } else if (object instanceof String) {
                            if (mentionsAdapter.isBotCommands()) {
                                SendMessagesHelper.getInstance().sendMessage((String) object, dialog_id, null,
                                        null, false, null, null, null);
                                chatActivityEnterView.setFieldText("");
                            } else {
                                chatActivityEnterView.replaceWithText(start, len, object + " ");
                            }
                        } else if (object instanceof TLRPC.BotInlineResult) {
                            if (chatActivityEnterView.getFieldText() == null) {
                                return;
                            }
                            TLRPC.BotInlineResult result = (TLRPC.BotInlineResult) object;
                            if (Build.VERSION.SDK_INT >= 16 && (result.type.equals("photo")
                                    && (result.photo != null || result.content_url != null)
                                    || result.type.equals("gif")
                                            && (result.document != null || result.content_url != null)
                                    || result.type.equals("video")
                                            && (result.document != null/* || result.content_url != null*/))) {
                                ArrayList<Object> arrayList = botContextResults = new ArrayList<Object>(
                                        mentionsAdapter.getSearchResultBotContext());
                                PhotoViewer.getInstance().setParentActivity(getParentActivity());
                                PhotoViewer.getInstance().openPhotoForSelect(arrayList,
                                        mentionsAdapter.getItemPosition(position), 3, botContextProvider, null);
                            } else {
                                sendBotInlineResult(result);
                            }
                        } else if (object instanceof TLRPC.TL_inlineBotSwitchPM) {
                            processInlineBotContextPM((TLRPC.TL_inlineBotSwitchPM) object);
                        }
                    }
                });

        mentionListView.setOnItemLongClickListener(new RecyclerListView.OnItemLongClickListener() {
            @Override
            public boolean onItemClick(View view, int position) {
                if (getParentActivity() == null || !mentionsAdapter.isLongClickEnabled()) {
                    return false;
                }
                Object object = mentionsAdapter.getItem(position);
                if (object instanceof String) {
                    if (mentionsAdapter.isBotCommands()) {
                        if (URLSpanBotCommand.enabled) {
                            chatActivityEnterView.setFieldText("");
                            chatActivityEnterView.setCommand(null, (String) object, true,
                                    currentChat != null && currentChat.megagroup);
                            return true;
                        }
                        return false;
                    } else {
                        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(),
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        mentionsAdapter.clearRecentHashtags();
                                    }
                                });
                        builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                        showDialog(builder.create());
                        return true;
                    }
                }
                return false;
            }
        });

        mentionListView.setOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                mentionListViewIsScrolling = newState == RecyclerView.SCROLL_STATE_DRAGGING;
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                int lastVisibleItem;
                if (mentionsAdapter.isBotContext() && mentionsAdapter.isMediaLayout()) {
                    lastVisibleItem = mentionGridLayoutManager.findLastVisibleItemPosition();
                } else {
                    lastVisibleItem = mentionLayoutManager.findLastVisibleItemPosition();
                }
                int visibleItemCount = lastVisibleItem == RecyclerView.NO_POSITION ? 0 : lastVisibleItem;
                if (visibleItemCount > 0 && lastVisibleItem > mentionsAdapter.getItemCount() - 5) {
                    mentionsAdapter.searchForContextBotForNextOffset();
                }
                mentionListViewUpdateLayout();
            }
        });
    }

    pagedownButton = new FrameLayout(context);
    pagedownButton.setVisibility(View.INVISIBLE);
    contentView.addView(pagedownButton,
            LayoutHelper.createFrame(46, 59, Gravity.RIGHT | Gravity.BOTTOM, 0, 0, 7, 5));
    pagedownButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (returnToMessageId > 0) {
                scrollToMessageId(returnToMessageId, 0, true, returnToLoadIndex);
            } else {
                scrollToLastMessage(true);
            }
        }
    });

    ImageView pagedownButtonImage = new ImageView(context);
    pagedownButtonImage.setImageResource(R.drawable.pagedown);
    pagedownButton.addView(pagedownButtonImage,
            LayoutHelper.createFrame(46, 46, Gravity.LEFT | Gravity.BOTTOM));

    pagedownButtonCounter = new TextView(context);
    pagedownButtonCounter.setVisibility(View.INVISIBLE);
    pagedownButtonCounter.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    pagedownButtonCounter.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
    pagedownButtonCounter.setTextColor(0xffffffff);
    pagedownButtonCounter.setGravity(Gravity.CENTER);
    pagedownButtonCounter.setBackgroundResource(R.drawable.chat_badge);
    pagedownButtonCounter.setMinWidth(AndroidUtilities.dp(23));
    pagedownButtonCounter.setPadding(AndroidUtilities.dp(8), 0, AndroidUtilities.dp(8), AndroidUtilities.dp(1));
    pagedownButton.addView(pagedownButtonCounter,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 23, Gravity.TOP | Gravity.CENTER_HORIZONTAL));

    chatActivityEnterView = new ChatActivityEnterView(getParentActivity(), contentView, this, true);
    chatActivityEnterView.setDialogId(dialog_id);
    chatActivityEnterView.addToAttachLayout(menuItem);
    chatActivityEnterView.setId(id_chat_compose_panel);
    chatActivityEnterView.setBotsCount(botsCount, hasBotsCommands);
    chatActivityEnterView.setAllowStickersAndGifs(
            currentEncryptedChat == null
                    || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 23,
            currentEncryptedChat == null
                    || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 46);
    contentView.addView(chatActivityEnterView, contentView.getChildCount() - 1, LayoutHelper
            .createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.BOTTOM));
    chatActivityEnterView.setDelegate(new ChatActivityEnterView.ChatActivityEnterViewDelegate() {
        @Override
        public void onMessageSend(CharSequence message) {
            moveScrollToLastMessage();
            showReplyPanel(false, null, null, null, false, true);
            if (mentionsAdapter != null) {
                mentionsAdapter.addHashtagsFromMessage(message);
            }
        }

        @Override
        public void onTextChanged(final CharSequence text, boolean bigChange) {
            MediaController.getInstance().setInputFieldHasText(
                    text != null && text.length() != 0 || chatActivityEnterView.isEditingMessage());
            if (stickersAdapter != null && !chatActivityEnterView.isEditingMessage()) {
                stickersAdapter.loadStikersForEmoji(text);
            }
            if (mentionsAdapter != null) {
                mentionsAdapter.searchUsernameOrHashtag(text.toString(),
                        chatActivityEnterView.getCursorPosition(), messages);
            }
            if (waitingForCharaterEnterRunnable != null) {
                AndroidUtilities.cancelRunOnUIThread(waitingForCharaterEnterRunnable);
                waitingForCharaterEnterRunnable = null;
            }
            if (chatActivityEnterView.isMessageWebPageSearchEnabled()
                    && (!chatActivityEnterView.isEditingMessage()
                            || !chatActivityEnterView.isEditingCaption())) {
                if (bigChange) {
                    searchLinks(text, true);
                } else {
                    waitingForCharaterEnterRunnable = new Runnable() {
                        @Override
                        public void run() {
                            if (this == waitingForCharaterEnterRunnable) {
                                searchLinks(text, false);
                                waitingForCharaterEnterRunnable = null;
                            }
                        }
                    };
                    AndroidUtilities.runOnUIThread(waitingForCharaterEnterRunnable,
                            AndroidUtilities.WEB_URL == null ? 3000 : 1000);
                }
            }
        }

        @Override
        public void needSendTyping() {
            MessagesController.getInstance().sendTyping(dialog_id, 0, classGuid);
        }

        @Override
        public void onAttachButtonHidden() {
            if (actionBar.isSearchFieldVisible()) {
                return;
            }
            if (attachItem != null) {
                attachItem.setVisibility(View.VISIBLE);
            }
            if (headerItem != null) {
                headerItem.setVisibility(View.GONE);
            }
        }

        @Override
        public void onAttachButtonShow() {
            if (actionBar.isSearchFieldVisible()) {
                return;
            }
            if (attachItem != null) {
                attachItem.setVisibility(View.GONE);
            }
            if (headerItem != null) {
                headerItem.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onMessageEditEnd(boolean loading) {
            if (loading) {
                showEditDoneProgress(true, true);
            } else {
                mentionsAdapter.setNeedBotContext(currentEncryptedChat == null
                        || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 46);
                chatListView.setOnItemLongClickListener(onItemLongClickListener);
                chatListView.setOnItemClickListener(onItemClickListener);
                chatListView.setClickable(true);
                chatListView.setLongClickable(true);
                mentionsAdapter.setAllowNewMentions(true);
                actionModeTitleContainer.setVisibility(View.GONE);
                selectedMessagesCountTextView.setVisibility(View.VISIBLE);
                chatActivityEnterView.setAllowStickersAndGifs(
                        currentEncryptedChat == null
                                || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 23,
                        currentEncryptedChat == null
                                || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 46);
                if (editingMessageObjectReqId != 0) {
                    ConnectionsManager.getInstance().cancelRequest(editingMessageObjectReqId, true);
                    editingMessageObjectReqId = 0;
                }
                actionBar.hideActionMode();
                updatePinnedMessageView(true);
                updateVisibleRows();
            }
        }

        @Override
        public void onWindowSizeChanged(int size) {
            if (size < AndroidUtilities.dp(72) + ActionBar.getCurrentActionBarHeight()) {
                allowStickersPanel = false;
                if (stickersPanel.getVisibility() == View.VISIBLE) {
                    stickersPanel.setVisibility(View.INVISIBLE);
                }
                if (mentionContainer != null && mentionContainer.getVisibility() == View.VISIBLE) {
                    mentionContainer.setVisibility(View.INVISIBLE);
                }
            } else {
                allowStickersPanel = true;
                if (stickersPanel.getVisibility() == View.INVISIBLE) {
                    stickersPanel.setVisibility(View.VISIBLE);
                }
                if (mentionContainer != null && mentionContainer.getVisibility() == View.INVISIBLE
                        && (!mentionsAdapter.isBotContext()
                                || (allowContextBotPanel || allowContextBotPanelSecond))) {
                    mentionContainer.setVisibility(View.VISIBLE);
                    mentionContainer.setTag(null);
                }
            }

            allowContextBotPanel = !chatActivityEnterView.isPopupShowing();
            checkContextBotPanel();
        }

        @Override
        public void onStickersTab(boolean opened) {
            if (emojiButtonRed != null) {
                emojiButtonRed.setVisibility(View.GONE);
            }
            allowContextBotPanelSecond = !opened;
            checkContextBotPanel();
        }
    });

    FrameLayout replyLayout = new FrameLayout(context) {
        @Override
        public void setTranslationY(float translationY) {
            super.setTranslationY(translationY);
            if (chatActivityEnterView != null) {
                chatActivityEnterView.invalidate();
            }
            if (getVisibility() != GONE) {
                int height = getLayoutParams().height;
                if (chatListView != null) {
                    chatListView.setTranslationY(translationY);
                }
                if (progressView != null) {
                    progressView.setTranslationY(translationY);
                }
                if (mentionContainer != null) {
                    mentionContainer.setTranslationY(translationY);
                }
                if (pagedownButton != null) {
                    pagedownButton.setTranslationY(translationY);
                }
            }
        }

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

        @Override
        public void setVisibility(int visibility) {
            super.setVisibility(visibility);
            if (visibility == GONE) {
                if (chatListView != null) {
                    chatListView.setTranslationY(0);
                }
                if (progressView != null) {
                    progressView.setTranslationY(0);
                }
                if (mentionContainer != null) {
                    mentionContainer.setTranslationY(0);
                }
                if (pagedownButton != null) {
                    pagedownButton
                            .setTranslationY(pagedownButton.getTag() == null ? AndroidUtilities.dp(100) : 0);
                }
            }
        }
    };
    replyLayout.setClickable(true);
    chatActivityEnterView.addTopView(replyLayout, 48);

    View lineView = new View(context);
    lineView.setBackgroundColor(0xffe8e8e8);
    replyLayout.addView(lineView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 1, Gravity.BOTTOM | Gravity.LEFT));

    replyIconImageView = new ImageView(context);
    replyIconImageView.setScaleType(ImageView.ScaleType.CENTER);
    replyLayout.addView(replyIconImageView, LayoutHelper.createFrame(52, 46, Gravity.TOP | Gravity.LEFT));

    ImageView imageView = new ImageView(context);
    imageView.setImageResource(R.drawable.delete_reply);
    imageView.setScaleType(ImageView.ScaleType.CENTER);
    replyLayout.addView(imageView,
            LayoutHelper.createFrame(52, 46, Gravity.RIGHT | Gravity.TOP, 0, 0.5f, 0, 0));
    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (forwardingMessages != null) {
                forwardingMessages.clear();
            }
            showReplyPanel(false, null, null, foundWebPage, true, true);
        }
    });

    replyNameTextView = new SimpleTextView(context);
    replyNameTextView.setTextSize(14);
    replyNameTextView.setTextColor(Theme.REPLY_PANEL_NAME_TEXT_COLOR);
    replyNameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    replyLayout.addView(replyNameTextView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.TOP | Gravity.LEFT, 52, 6, 52, 0));

    replyObjectTextView = new SimpleTextView(context);
    replyObjectTextView.setTextSize(14);
    replyObjectTextView.setTextColor(Theme.REPLY_PANEL_MESSAGE_TEXT_COLOR);
    replyLayout.addView(replyObjectTextView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.TOP | Gravity.LEFT, 52, 24, 52, 0));

    replyImageView = new BackupImageView(context);
    replyLayout.addView(replyImageView,
            LayoutHelper.createFrame(34, 34, Gravity.TOP | Gravity.LEFT, 52, 6, 0, 0));

    stickersPanel = new FrameLayout(context);
    stickersPanel.setVisibility(View.GONE);
    contentView.addView(stickersPanel, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 81.5f,
            Gravity.LEFT | Gravity.BOTTOM, 0, 0, 0, 38));

    stickersListView = new RecyclerListView(context) {
        @Override
        public boolean onInterceptTouchEvent(MotionEvent event) {
            boolean result = StickerPreviewViewer.getInstance().onInterceptTouchEvent(event, stickersListView,
                    0);
            return super.onInterceptTouchEvent(event) || result;
        }
    };
    stickersListView.setTag(3);
    stickersListView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return StickerPreviewViewer.getInstance().onTouch(event, stickersListView, 0,
                    stickersOnItemClickListener);
        }
    });
    stickersListView.setDisallowInterceptTouchEvents(true);
    LinearLayoutManager layoutManager = new LinearLayoutManager(context);
    layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
    stickersListView.setLayoutManager(layoutManager);
    stickersListView.setClipToPadding(false);
    stickersListView.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER);
    stickersPanel.addView(stickersListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 78));
    initStickers();

    imageView = new ImageView(context);
    imageView.setImageResource(R.drawable.stickers_back_arrow);
    stickersPanel.addView(imageView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 53, 0, 0, 0));

    searchContainer = new FrameLayout(context);
    searchContainer.setBackgroundResource(R.drawable.compose_panel);
    searchContainer.setVisibility(View.INVISIBLE);
    searchContainer.setFocusable(true);
    searchContainer.setFocusableInTouchMode(true);
    searchContainer.setClickable(true);
    searchContainer.setBackgroundResource(R.drawable.compose_panel);
    searchContainer.setPadding(0, AndroidUtilities.dp(3), 0, 0);
    contentView.addView(searchContainer,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM));

    searchUpButton = new ImageView(context);
    searchUpButton.setScaleType(ImageView.ScaleType.CENTER);
    searchUpButton.setImageResource(R.drawable.search_up);
    searchContainer.addView(searchUpButton, LayoutHelper.createFrame(48, 48));
    searchUpButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            MessagesSearchQuery.searchMessagesInChat(null, dialog_id, mergeDialogId, classGuid, 1);
        }
    });

    searchDownButton = new ImageView(context);
    searchDownButton.setScaleType(ImageView.ScaleType.CENTER);
    searchDownButton.setImageResource(R.drawable.search_down);
    searchContainer.addView(searchDownButton,
            LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.TOP, 48, 0, 0, 0));
    searchDownButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            MessagesSearchQuery.searchMessagesInChat(null, dialog_id, mergeDialogId, classGuid, 2);
        }
    });

    searchCountText = new SimpleTextView(context);
    searchCountText.setTextColor(Theme.CHAT_SEARCH_COUNT_TEXT_COLOR);
    searchCountText.setTextSize(15);
    searchCountText.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    searchContainer.addView(searchCountText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL, 108, 0, 0, 0));

    bottomOverlay = new FrameLayout(context);
    bottomOverlay.setVisibility(View.INVISIBLE);
    bottomOverlay.setFocusable(true);
    bottomOverlay.setFocusableInTouchMode(true);
    bottomOverlay.setClickable(true);
    bottomOverlay.setBackgroundResource(R.drawable.compose_panel);
    bottomOverlay.setPadding(0, AndroidUtilities.dp(3), 0, 0);
    contentView.addView(bottomOverlay, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM));

    bottomOverlayText = new TextView(context);
    bottomOverlayText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
    bottomOverlayText.setTextColor(Theme.CHAT_BOTTOM_OVERLAY_TEXT_COLOR);
    bottomOverlay.addView(bottomOverlayText,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));

    bottomOverlayChat = new FrameLayout(context);
    bottomOverlayChat.setBackgroundResource(R.drawable.compose_panel);
    bottomOverlayChat.setPadding(0, AndroidUtilities.dp(3), 0, 0);
    bottomOverlayChat.setVisibility(View.INVISIBLE);
    contentView.addView(bottomOverlayChat,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM));
    bottomOverlayChat.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (getParentActivity() == null) {
                return;
            }
            AlertDialog.Builder builder = null;
            if (currentUser != null && userBlocked) {
                if (currentUser.bot) {
                    String botUserLast = botUser;
                    botUser = null;
                    MessagesController.getInstance().unblockUser(currentUser.id);
                    if (botUserLast != null && botUserLast.length() != 0) {
                        MessagesController.getInstance().sendBotStart(currentUser, botUserLast);
                    } else {
                        SendMessagesHelper.getInstance().sendMessage("/start", dialog_id, null, null, false,
                                null, null, null);
                    }
                } else {
                    builder = new AlertDialog.Builder(getParentActivity());
                    builder.setMessage(LocaleController.getString("AreYouSureUnblockContact",
                            R.string.AreYouSureUnblockContact));
                    builder.setPositiveButton(LocaleController.getString("OK", R.string.OK),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    MessagesController.getInstance().unblockUser(currentUser.id);
                                }
                            });
                }
            } else if (currentUser != null && currentUser.bot && botUser != null) {
                if (botUser.length() != 0) {
                    MessagesController.getInstance().sendBotStart(currentUser, botUser);
                } else {
                    SendMessagesHelper.getInstance().sendMessage("/start", dialog_id, null, null, false, null,
                            null, null);
                }
                botUser = null;
                updateBottomOverlay();
            } else {
                if (ChatObject.isChannel(currentChat) && !(currentChat instanceof TLRPC.TL_channelForbidden)) {
                    if (ChatObject.isNotInChat(currentChat)) {
                        MessagesController.getInstance().addUserToChat(currentChat.id,
                                UserConfig.getCurrentUser(), null, 0, null, null);
                    } else {
                        toggleMute(true);
                    }
                } else {
                    builder = new AlertDialog.Builder(getParentActivity());
                    builder.setMessage(LocaleController.getString("AreYouSureDeleteThisChat",
                            R.string.AreYouSureDeleteThisChat));
                    builder.setPositiveButton(LocaleController.getString("OK", R.string.OK),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    MessagesController.getInstance().deleteDialog(dialog_id, 0);
                                    finishFragment();
                                }
                            });
                }
            }
            if (builder != null) {
                builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                showDialog(builder.create());
            }
        }
    });

    bottomOverlayChatText = new TextView(context);
    bottomOverlayChatText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
    bottomOverlayChatText.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    bottomOverlayChatText.setTextColor(Theme.CHAT_BOTTOM_CHAT_OVERLAY_TEXT_COLOR);
    bottomOverlayChat.addView(bottomOverlayChatText,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));

    chatAdapter.updateRows();
    if (loading && messages.isEmpty()) {
        progressView.setVisibility(chatAdapter.botInfoRow == -1 ? View.VISIBLE : View.INVISIBLE);
        chatListView.setEmptyView(null);
    } else {
        progressView.setVisibility(View.INVISIBLE);
        chatListView.setEmptyView(emptyViewContainer);
    }

    chatActivityEnterView.setButtons(userBlocked ? null : botButtons);

    if (!AndroidUtilities.isTablet() || AndroidUtilities.isSmallTablet()) {
        contentView.addView(playerView = new PlayerView(context, this), LayoutHelper
                .createFrame(LayoutHelper.MATCH_PARENT, 39, Gravity.TOP | Gravity.LEFT, 0, -36, 0, 0));
    }

    updateContactStatus();
    updateBottomOverlay();
    updateSecretStatus();
    updateSpamView();
    updatePinnedMessageView(true);

    try {
        if (currentEncryptedChat != null && Build.VERSION.SDK_INT >= 23) {
            getParentActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE,
                    WindowManager.LayoutParams.FLAG_SECURE);
        }
    } catch (Throwable e) {
        FileLog.e("tmessages", e);
    }
    fixLayoutInternal();

    contentView.addView(actionBar);

    return fragmentView;
}

From source file:kr.wdream.ui.ChatActivity.java

@Override
public View createView(Context context) {

    Log.d(LOG_TAG, "createView");

    if (chatMessageCellsCache.isEmpty()) {
        for (int a = 0; a < 8; a++) {
            chatMessageCellsCache.add(new ChatMessageCell(context));
        }// www . j av a 2s  .  c o m
    }
    for (int a = 1; a >= 0; a--) {
        selectedMessagesIds[a].clear();
        selectedMessagesCanCopyIds[a].clear();
    }
    cantDeleteMessagesCount = 0;

    hasOwnBackground = true;
    if (chatAttachAlert != null) {
        chatAttachAlert.onDestroy();
        chatAttachAlert = null;
    }

    Theme.loadRecources(context);
    Theme.loadChatResources(context);

    actionBar.setAddToContainer(false);
    actionBar.setBackButtonDrawable(new BackDrawable(false));
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override
        public void onItemClick(final int id) {
            if (id == -1) {
                if (actionBar.isActionModeShowed()) {
                    for (int a = 1; a >= 0; a--) {
                        selectedMessagesIds[a].clear();
                        selectedMessagesCanCopyIds[a].clear();
                    }
                    cantDeleteMessagesCount = 0;
                    if (chatActivityEnterView.isEditingMessage()) {
                        chatActivityEnterView.setEditingMessageObject(null, false);
                    } else {
                        actionBar.hideActionMode();
                        updatePinnedMessageView(true);
                    }
                    updateVisibleRows();
                } else {
                    finishFragment();
                }
            } else if (id == copy) {
                String str = "";
                int previousUid = 0;
                for (int a = 1; a >= 0; a--) {
                    ArrayList<Integer> ids = new ArrayList<>(selectedMessagesCanCopyIds[a].keySet());
                    if (currentEncryptedChat == null) {
                        Collections.sort(ids);
                    } else {
                        Collections.sort(ids, Collections.reverseOrder());
                    }
                    for (int b = 0; b < ids.size(); b++) {
                        Integer messageId = ids.get(b);
                        MessageObject messageObject = selectedMessagesCanCopyIds[a].get(messageId);
                        if (str.length() != 0) {
                            str += "\n\n";
                        }
                        str += getMessageContent(messageObject, previousUid, true);
                        previousUid = messageObject.messageOwner.from_id;
                    }
                }
                if (str.length() != 0) {
                    AndroidUtilities.addToClipboard(str);
                }
                for (int a = 1; a >= 0; a--) {
                    selectedMessagesIds[a].clear();
                    selectedMessagesCanCopyIds[a].clear();
                }
                cantDeleteMessagesCount = 0;
                actionBar.hideActionMode();
                updatePinnedMessageView(true);
                updateVisibleRows();
            } else if (id == edit_done) {
                if (chatActivityEnterView != null
                        && (chatActivityEnterView.isEditingCaption() || chatActivityEnterView.hasText())) {
                    chatActivityEnterView.doneEditingMessage();
                }
            } else if (id == delete) {
                if (getParentActivity() == null) {
                    return;
                }
                createDeleteMessagesAlert(null);
            } else if (id == forward) {
                Bundle args = new Bundle();
                args.putBoolean("onlySelect", true);
                args.putInt("dialogsType", 1);
                DialogsActivity fragment = new DialogsActivity(args);
                fragment.setDelegate(ChatActivity.this);
                presentFragment(fragment);
            } else if (id == chat_enc_timer) {
                if (getParentActivity() == null) {
                    return;
                }
                showDialog(AndroidUtilities.buildTTLAlert(getParentActivity(), currentEncryptedChat).create());
            } else if (id == clear_history || id == delete_chat) {
                if (getParentActivity() == null) {
                    return;
                }
                final boolean isChat = (int) dialog_id < 0 && (int) (dialog_id >> 32) != 1;
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setTitle(LocaleController.getString("AppName", kr.wdream.storyshop.R.string.AppName));
                if (id == clear_history) {
                    builder.setMessage(LocaleController.getString("AreYouSureClearHistory",
                            kr.wdream.storyshop.R.string.AreYouSureClearHistory));
                } else {
                    if (isChat) {
                        builder.setMessage(LocaleController.getString("AreYouSureDeleteAndExit",
                                kr.wdream.storyshop.R.string.AreYouSureDeleteAndExit));
                    } else {
                        builder.setMessage(LocaleController.getString("AreYouSureDeleteThisChat",
                                kr.wdream.storyshop.R.string.AreYouSureDeleteThisChat));
                    }
                }
                builder.setPositiveButton(LocaleController.getString("OK", kr.wdream.storyshop.R.string.OK),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                if (id != clear_history) {
                                    if (isChat) {
                                        if (ChatObject.isNotInChat(currentChat)) {
                                            MessagesController.getInstance().deleteDialog(dialog_id, 0);
                                        } else {
                                            MessagesController.getInstance()
                                                    .deleteUserFromChat(
                                                            (int) -dialog_id, MessagesController.getInstance()
                                                                    .getUser(UserConfig.getClientUserId()),
                                                            null);
                                        }
                                    } else {
                                        MessagesController.getInstance().deleteDialog(dialog_id, 0);
                                    }
                                    finishFragment();
                                } else {
                                    MessagesController.getInstance().deleteDialog(dialog_id, 1);
                                }
                            }
                        });
                builder.setNegativeButton(
                        LocaleController.getString("Cancel", kr.wdream.storyshop.R.string.Cancel), null);
                showDialog(builder.create());
            } else if (id == share_contact) {
                if (currentUser == null || getParentActivity() == null) {
                    return;
                }
                if (currentUser.phone != null && currentUser.phone.length() != 0) {
                    Bundle args = new Bundle();
                    args.putInt("user_id", currentUser.id);
                    args.putBoolean("addContact", true);
                    presentFragment(new ContactAddActivity(args));
                } else {
                    shareMyContact(replyingMessageObject);
                }
            } else if (id == mute) {
                toggleMute(false);
            } else if (id == report) {
                showDialog(AlertsCreator.createReportAlert(getParentActivity(), dialog_id, ChatActivity.this));
            } else if (id == reply) {
                MessageObject messageObject = null;
                for (int a = 1; a >= 0; a--) {
                    if (messageObject == null && selectedMessagesIds[a].size() == 1) {
                        ArrayList<Integer> ids = new ArrayList<>(selectedMessagesIds[a].keySet());
                        messageObject = messagesDict[a].get(ids.get(0));
                    }
                    selectedMessagesIds[a].clear();
                    selectedMessagesCanCopyIds[a].clear();
                }
                if (messageObject != null && (messageObject.messageOwner.id > 0
                        || messageObject.messageOwner.id < 0 && currentEncryptedChat != null)) {
                    showReplyPanel(true, messageObject, null, null, false, true);
                }
                cantDeleteMessagesCount = 0;
                actionBar.hideActionMode();
                updatePinnedMessageView(true);
                updateVisibleRows();
            } else if (id == chat_menu_attach) {
                if (getParentActivity() == null) {
                    return;
                }

                createChatAttachView();
                chatAttachAlert.loadGalleryPhotos();
                if (Build.VERSION.SDK_INT == 21 || Build.VERSION.SDK_INT == 22) {
                    chatActivityEnterView.closeKeyboard();
                }
                chatAttachAlert.init();
                showDialog(chatAttachAlert);
            } else if (id == bot_help) {
                SendMessagesHelper.getInstance().sendMessage("/help", dialog_id, null, null, false, null, null,
                        null);
            } else if (id == bot_settings) {
                SendMessagesHelper.getInstance().sendMessage("/settings", dialog_id, null, null, false, null,
                        null, null);
            } else if (id == search) {
                openSearchWithText(null);
            }
        }
    });

    avatarContainer = new ChatAvatarContainer(context, this, currentEncryptedChat != null);
    actionBar.addView(avatarContainer, 0, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, 56, 0, 40, 0));

    if (currentChat != null) {
        if (!ChatObject.isChannel(currentChat)) {
            int count = currentChat.participants_count;
            if (info != null) {
                count = info.participants.participants.size();
            }
            if (count == 0 || currentChat.deactivated || currentChat.left
                    || currentChat instanceof TLRPC.TL_chatForbidden
                    || info != null && info.participants instanceof TLRPC.TL_chatParticipantsForbidden) {
                avatarContainer.setEnabled(false);
            }
        }
    }

    ActionBarMenu menu = actionBar.createMenu();

    if (currentEncryptedChat == null && !isBroadcast) {
        searchItem = menu.addItem(0, kr.wdream.storyshop.R.drawable.ic_ab_search).setIsSearchField(true)
                .setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() {

                    @Override
                    public void onSearchCollapse() {
                        avatarContainer.setVisibility(View.VISIBLE);
                        if (chatActivityEnterView.hasText()) {
                            if (headerItem != null) {
                                headerItem.setVisibility(View.GONE);
                            }
                            if (attachItem != null) {
                                attachItem.setVisibility(View.VISIBLE);
                            }
                        } else {
                            if (headerItem != null) {
                                headerItem.setVisibility(View.VISIBLE);
                            }
                            if (attachItem != null) {
                                attachItem.setVisibility(View.GONE);
                            }
                        }
                        searchItem.setVisibility(View.GONE);
                        highlightMessageId = Integer.MAX_VALUE;
                        updateVisibleRows();
                        scrollToLastMessage(false);
                        updateBottomOverlay();
                    }

                    @Override
                    public void onSearchExpand() {
                        if (!openSearchKeyboard) {
                            return;
                        }
                        AndroidUtilities.runOnUIThread(new Runnable() {
                            @Override
                            public void run() {
                                searchItem.getSearchField().requestFocus();
                                AndroidUtilities.showKeyboard(searchItem.getSearchField());
                            }
                        }, 300);
                    }

                    @Override
                    public void onSearchPressed(EditText editText) {
                        updateSearchButtons(0, 0, 0);
                        MessagesSearchQuery.searchMessagesInChat(editText.getText().toString(), dialog_id,
                                mergeDialogId, classGuid, 0);
                    }
                });
        searchItem.getSearchField()
                .setHint(LocaleController.getString("Search", kr.wdream.storyshop.R.string.Search));
        searchItem.setVisibility(View.GONE);
    }

    headerItem = menu.addItem(0, kr.wdream.storyshop.R.drawable.ic_ab_other);
    if (searchItem != null) {
        headerItem.addSubItem(search, LocaleController.getString("Search", kr.wdream.storyshop.R.string.Search),
                0);
    }
    if (ChatObject.isChannel(currentChat) && !currentChat.creator
            && (!currentChat.megagroup || currentChat.username != null && currentChat.username.length() > 0)) {
        headerItem.addSubItem(report,
                LocaleController.getString("ReportChat", kr.wdream.storyshop.R.string.ReportChat), 0);
    }
    if (currentUser != null) {
        addContactItem = headerItem.addSubItem(share_contact, "", 0);
    }
    if (currentEncryptedChat != null) {
        timeItem2 = headerItem.addSubItem(chat_enc_timer,
                LocaleController.getString("SetTimer", kr.wdream.storyshop.R.string.SetTimer), 0);
    }
    if (!ChatObject.isChannel(currentChat)) {
        headerItem.addSubItem(clear_history,
                LocaleController.getString("ClearHistory", kr.wdream.storyshop.R.string.ClearHistory), 0);
        if (currentChat != null && !isBroadcast) {
            headerItem.addSubItem(delete_chat,
                    LocaleController.getString("DeleteAndExit", kr.wdream.storyshop.R.string.DeleteAndExit), 0);
        } else {
            headerItem.addSubItem(delete_chat,
                    LocaleController.getString("DeleteChatUser", kr.wdream.storyshop.R.string.DeleteChatUser),
                    0);
        }
    }
    if (currentUser == null || !currentUser.self) {
        muteItem = headerItem.addSubItem(mute, null, 0);
    }
    if (currentUser != null && currentEncryptedChat == null && currentUser.bot) {
        headerItem.addSubItem(bot_settings,
                LocaleController.getString("BotSettings", kr.wdream.storyshop.R.string.BotSettings), 0);
        headerItem.addSubItem(bot_help,
                LocaleController.getString("BotHelp", kr.wdream.storyshop.R.string.BotHelp), 0);
        updateBotButtons();
    }

    updateTitle();
    avatarContainer.updateOnlineCount();
    avatarContainer.updateSubtitle();
    updateTitleIcons();

    attachItem = menu.addItem(chat_menu_attach, kr.wdream.storyshop.R.drawable.ic_ab_other)
            .setOverrideMenuClick(true).setAllowCloseAnimation(false);
    attachItem.setVisibility(View.GONE);
    menuItem = menu.addItem(chat_menu_attach, kr.wdream.storyshop.R.drawable.ic_ab_attach)
            .setAllowCloseAnimation(false);
    menuItem.setBackgroundDrawable(null);

    actionModeViews.clear();

    final ActionBarMenu actionMode = actionBar.createActionMode();

    selectedMessagesCountTextView = new NumberTextView(actionMode.getContext());
    selectedMessagesCountTextView.setTextSize(18);
    selectedMessagesCountTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    selectedMessagesCountTextView.setTextColor(Theme.ACTION_BAR_ACTION_MODE_TEXT_COLOR);
    actionMode.addView(selectedMessagesCountTextView,
            LayoutHelper.createLinear(0, LayoutHelper.MATCH_PARENT, 1.0f, 65, 0, 0, 0));
    selectedMessagesCountTextView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });

    actionModeTitleContainer = new FrameLayout(context) {

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int width = MeasureSpec.getSize(widthMeasureSpec);
            int height = MeasureSpec.getSize(heightMeasureSpec);

            setMeasuredDimension(width, height);

            actionModeTextView.setTextSize(!AndroidUtilities.isTablet()
                    && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE ? 18
                            : 20);
            actionModeTextView.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST),
                    MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(24), MeasureSpec.AT_MOST));

            if (actionModeSubTextView.getVisibility() != GONE) {
                actionModeSubTextView.setTextSize(!AndroidUtilities.isTablet()
                        && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE
                                ? 14
                                : 16);
                actionModeSubTextView.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST),
                        MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(20), MeasureSpec.AT_MOST));
            }
        }

        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            int height = bottom - top;

            int textTop;
            if (actionModeSubTextView.getVisibility() != GONE) {
                textTop = (height / 2 - actionModeTextView.getTextHeight()) / 2
                        + AndroidUtilities.dp(!AndroidUtilities.isTablet() && getResources()
                                .getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE ? 2 : 3);
            } else {
                textTop = (height - actionModeTextView.getTextHeight()) / 2;
            }
            actionModeTextView.layout(0, textTop, actionModeTextView.getMeasuredWidth(),
                    textTop + actionModeTextView.getTextHeight());

            if (actionModeSubTextView.getVisibility() != GONE) {
                textTop = height / 2 + (height / 2 - actionModeSubTextView.getTextHeight()) / 2
                        - AndroidUtilities.dp(!AndroidUtilities.isTablet() && getResources()
                                .getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE ? 1 : 1);
                actionModeSubTextView.layout(0, textTop, actionModeSubTextView.getMeasuredWidth(),
                        textTop + actionModeSubTextView.getTextHeight());
            }
        }
    };
    actionMode.addView(actionModeTitleContainer,
            LayoutHelper.createLinear(0, LayoutHelper.MATCH_PARENT, 1.0f, 65, 0, 0, 0));
    actionModeTitleContainer.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });
    actionModeTitleContainer.setVisibility(View.GONE);

    actionModeTextView = new SimpleTextView(context);
    actionModeTextView.setTextSize(18);
    actionModeTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    actionModeTextView.setTextColor(Theme.ACTION_BAR_ACTION_MODE_TEXT_COLOR);
    actionModeTextView.setText(LocaleController.getString("Edit", kr.wdream.storyshop.R.string.Edit));
    actionModeTitleContainer.addView(actionModeTextView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));

    actionModeSubTextView = new SimpleTextView(context);
    actionModeSubTextView.setGravity(Gravity.LEFT);
    actionModeSubTextView.setTextColor(Theme.ACTION_BAR_ACTION_MODE_TEXT_COLOR);
    actionModeTitleContainer.addView(actionModeSubTextView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));

    if (currentEncryptedChat == null) {
        if (!isBroadcast) {
            actionModeViews.add(actionMode.addItem(reply, kr.wdream.storyshop.R.drawable.ic_ab_reply,
                    Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
        }
        actionModeViews.add(actionMode.addItem(copy, kr.wdream.storyshop.R.drawable.ic_ab_fwd_copy,
                Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
        actionModeViews.add(actionMode.addItem(forward, kr.wdream.storyshop.R.drawable.ic_ab_fwd_forward,
                Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
        actionModeViews.add(actionMode.addItem(delete, kr.wdream.storyshop.R.drawable.ic_ab_fwd_delete,
                Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
        actionModeViews
                .add(editDoneItem = actionMode.addItem(edit_done, kr.wdream.storyshop.R.drawable.check_blue,
                        Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
        editDoneItem.setVisibility(View.GONE);
        editDoneItemProgress = new ContextProgressView(context, 0);
        editDoneItem.addView(editDoneItemProgress,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
        editDoneItemProgress.setVisibility(View.INVISIBLE);
    } else {
        actionModeViews.add(actionMode.addItem(reply, kr.wdream.storyshop.R.drawable.ic_ab_reply,
                Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
        actionModeViews.add(actionMode.addItem(copy, kr.wdream.storyshop.R.drawable.ic_ab_fwd_copy,
                Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
        actionModeViews.add(actionMode.addItem(delete, kr.wdream.storyshop.R.drawable.ic_ab_fwd_delete,
                Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
    }
    actionMode.getItem(copy)
            .setVisibility(selectedMessagesCanCopyIds[0].size() + selectedMessagesCanCopyIds[1].size() != 0
                    ? View.VISIBLE
                    : View.GONE);
    actionMode.getItem(delete).setVisibility(cantDeleteMessagesCount == 0 ? View.VISIBLE : View.GONE);
    checkActionBarMenu();

    fragmentView = new SizeNotifierFrameLayout(context) {

        int inputFieldHeight = 0;

        @Override
        protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
            boolean result = super.drawChild(canvas, child, drawingTime);
            if (child == actionBar) {
                parentLayout.drawHeaderShadow(canvas, actionBar.getMeasuredHeight());
            }
            return result;
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int widthSize = MeasureSpec.getSize(widthMeasureSpec);
            int heightSize = MeasureSpec.getSize(heightMeasureSpec);

            setMeasuredDimension(widthSize, heightSize);
            heightSize -= getPaddingTop();

            measureChildWithMargins(actionBar, widthMeasureSpec, 0, heightMeasureSpec, 0);
            int actionBarHeight = actionBar.getMeasuredHeight();
            heightSize -= actionBarHeight;

            int keyboardSize = getKeyboardHeight();

            if (keyboardSize <= AndroidUtilities.dp(20) && !AndroidUtilities.isInMultiwindow) {
                heightSize -= chatActivityEnterView.getEmojiPadding();
            }

            int childCount = getChildCount();

            measureChildWithMargins(chatActivityEnterView, widthMeasureSpec, 0, heightMeasureSpec, 0);
            inputFieldHeight = chatActivityEnterView.getMeasuredHeight();

            for (int i = 0; i < childCount; i++) {
                View child = getChildAt(i);
                if (child == null || child.getVisibility() == GONE || child == chatActivityEnterView
                        || child == actionBar) {
                    continue;
                }
                if (child == chatListView || child == progressView) {
                    int contentWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
                    int contentHeightSpec = MeasureSpec
                            .makeMeasureSpec(
                                    Math.max(AndroidUtilities.dp(10),
                                            heightSize - inputFieldHeight + AndroidUtilities.dp(
                                                    2 + (chatActivityEnterView.isTopViewVisible() ? 48 : 0))),
                                    MeasureSpec.EXACTLY);
                    child.measure(contentWidthSpec, contentHeightSpec);
                } else if (child == emptyViewContainer) {
                    int contentWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
                    int contentHeightSpec = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY);
                    child.measure(contentWidthSpec, contentHeightSpec);
                } else if (chatActivityEnterView.isPopupView(child)) {
                    if (AndroidUtilities.isInMultiwindow) {
                        if (AndroidUtilities.isTablet()) {
                            child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY),
                                    MeasureSpec.makeMeasureSpec(Math.min(AndroidUtilities.dp(320),
                                            heightSize - inputFieldHeight + actionBarHeight
                                                    - AndroidUtilities.statusBarHeight + getPaddingTop()),
                                            MeasureSpec.EXACTLY));
                        } else {
                            child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY),
                                    MeasureSpec.makeMeasureSpec(
                                            heightSize - inputFieldHeight + actionBarHeight
                                                    - AndroidUtilities.statusBarHeight + getPaddingTop(),
                                            MeasureSpec.EXACTLY));
                        }
                    } else {
                        child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec
                                .makeMeasureSpec(child.getLayoutParams().height, MeasureSpec.EXACTLY));
                    }
                } else if (child == mentionContainer) {
                    FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mentionContainer
                            .getLayoutParams();
                    int height;
                    mentionListViewIgnoreLayout = true;

                    if (mentionsAdapter.isBotContext() && mentionsAdapter.isMediaLayout()) {
                        int size = mentionGridLayoutManager.getRowsCount(widthSize);
                        int maxHeight = size * 102;
                        if (mentionsAdapter.isBotContext()) {
                            if (mentionsAdapter.getBotContextSwitch() != null) {
                                maxHeight += 34;
                            }
                        }
                        height = heightSize - chatActivityEnterView.getMeasuredHeight()
                                + (maxHeight != 0 ? AndroidUtilities.dp(2) : 0);
                        mentionListView.setPadding(0,
                                Math.max(0, height - AndroidUtilities.dp(Math.min(maxHeight, 68 * 1.8f))), 0,
                                0);
                    } else {
                        int size = mentionsAdapter.getItemCount();
                        int maxHeight = 0;
                        if (mentionsAdapter.isBotContext()) {
                            if (mentionsAdapter.getBotContextSwitch() != null) {
                                maxHeight += 36;
                                size -= 1;
                            }
                            maxHeight += size * 68;
                        } else {
                            maxHeight += size * 36;
                        }
                        height = heightSize - chatActivityEnterView.getMeasuredHeight()
                                + (maxHeight != 0 ? AndroidUtilities.dp(2) : 0);
                        mentionListView.setPadding(0,
                                Math.max(0, height - AndroidUtilities.dp(Math.min(maxHeight, 68 * 1.8f))), 0,
                                0);
                    }

                    layoutParams.height = height;
                    layoutParams.topMargin = 0;

                    mentionListViewIgnoreLayout = false;
                    child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY),
                            MeasureSpec.makeMeasureSpec(layoutParams.height, MeasureSpec.EXACTLY));
                } else {
                    measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
                }
            }
        }

        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
            final int count = getChildCount();

            int paddingBottom = getKeyboardHeight() <= AndroidUtilities.dp(20)
                    && !AndroidUtilities.isInMultiwindow ? chatActivityEnterView.getEmojiPadding() : 0;
            setBottomClip(paddingBottom);

            for (int i = 0; i < count; i++) {
                final View child = getChildAt(i);
                if (child.getVisibility() == GONE) {
                    continue;
                }
                final LayoutParams lp = (LayoutParams) child.getLayoutParams();

                final int width = child.getMeasuredWidth();
                final int height = child.getMeasuredHeight();

                int childLeft;
                int childTop;

                int gravity = lp.gravity;
                if (gravity == -1) {
                    gravity = Gravity.TOP | Gravity.LEFT;
                }

                final int absoluteGravity = gravity & Gravity.HORIZONTAL_GRAVITY_MASK;
                final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;

                switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
                case Gravity.CENTER_HORIZONTAL:
                    childLeft = (r - l - width) / 2 + lp.leftMargin - lp.rightMargin;
                    break;
                case Gravity.RIGHT:
                    childLeft = r - width - lp.rightMargin;
                    break;
                case Gravity.LEFT:
                default:
                    childLeft = lp.leftMargin;
                }

                switch (verticalGravity) {
                case Gravity.TOP:
                    childTop = lp.topMargin + getPaddingTop();
                    if (child != actionBar) {
                        childTop += actionBar.getMeasuredHeight();
                    }
                    break;
                case Gravity.CENTER_VERTICAL:
                    childTop = ((b - paddingBottom) - t - height) / 2 + lp.topMargin - lp.bottomMargin;
                    break;
                case Gravity.BOTTOM:
                    childTop = ((b - paddingBottom) - t) - height - lp.bottomMargin;
                    break;
                default:
                    childTop = lp.topMargin;
                }

                if (child == mentionContainer) {
                    childTop -= chatActivityEnterView.getMeasuredHeight() - AndroidUtilities.dp(2);
                } else if (child == pagedownButton) {
                    childTop -= chatActivityEnterView.getMeasuredHeight();
                } else if (child == emptyViewContainer) {
                    childTop -= inputFieldHeight / 2 - actionBar.getMeasuredHeight() / 2;
                } else if (chatActivityEnterView.isPopupView(child)) {
                    if (AndroidUtilities.isInMultiwindow) {
                        childTop = chatActivityEnterView.getTop() - child.getMeasuredHeight()
                                + AndroidUtilities.dp(1);
                    } else {
                        childTop = chatActivityEnterView.getBottom();
                    }
                } else if (child == gifHintTextView) {
                    childTop -= inputFieldHeight;
                } else if (child == chatListView || child == progressView) {
                    if (chatActivityEnterView.isTopViewVisible()) {
                        childTop -= AndroidUtilities.dp(48);
                    }
                } else if (child == actionBar) {
                    childTop -= getPaddingTop();
                }
                child.layout(childLeft, childTop, childLeft + width, childTop + height);
            }

            updateMessagesVisisblePart();
            notifyHeightChanged();
        }
    };

    SizeNotifierFrameLayout contentView = (SizeNotifierFrameLayout) fragmentView;

    contentView.setBackgroundImage(ApplicationLoader.getCachedWallpaper());

    emptyViewContainer = new FrameLayout(context);
    emptyViewContainer.setVisibility(View.INVISIBLE);
    contentView.addView(emptyViewContainer,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
    emptyViewContainer.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });

    if (currentEncryptedChat == null) {
        if (currentUser != null && currentUser.self) {
            bigEmptyView = new ChatBigEmptyView(context, false);
            emptyViewContainer.addView(bigEmptyView, new FrameLayout.LayoutParams(LayoutHelper.WRAP_CONTENT,
                    LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
        } else {
            TextView emptyView = new TextView(context);
            if (currentUser != null && currentUser.id != 777000 && currentUser.id != 429000
                    && (currentUser.id / 1000 == 333 || currentUser.id % 1000 == 0)) {
                emptyView.setText(
                        LocaleController.getString("GotAQuestion", kr.wdream.storyshop.R.string.GotAQuestion));
            } else {
                emptyView.setText(
                        LocaleController.getString("NoMessages", kr.wdream.storyshop.R.string.NoMessages));
            }
            emptyView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
            emptyView.setGravity(Gravity.CENTER);
            emptyView.setTextColor(Theme.CHAT_EMPTY_VIEW_TEXT_COLOR);
            emptyView.setBackgroundResource(kr.wdream.storyshop.R.drawable.system);
            emptyView.getBackground().setColorFilter(Theme.colorFilter);
            emptyView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
            emptyView.setPadding(AndroidUtilities.dp(10), AndroidUtilities.dp(2), AndroidUtilities.dp(10),
                    AndroidUtilities.dp(3));
            emptyViewContainer.addView(emptyView, new FrameLayout.LayoutParams(LayoutHelper.WRAP_CONTENT,
                    LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
        }
    } else {
        bigEmptyView = new ChatBigEmptyView(context, true);
        if (currentEncryptedChat.admin_id == UserConfig.getClientUserId()) {
            bigEmptyView.setSecretText(LocaleController.formatString("EncryptedPlaceholderTitleOutgoing",
                    kr.wdream.storyshop.R.string.EncryptedPlaceholderTitleOutgoing,
                    UserObject.getFirstName(currentUser)));
        } else {
            bigEmptyView.setSecretText(LocaleController.formatString("EncryptedPlaceholderTitleIncoming",
                    kr.wdream.storyshop.R.string.EncryptedPlaceholderTitleIncoming,
                    UserObject.getFirstName(currentUser)));
        }
        emptyViewContainer.addView(bigEmptyView, new FrameLayout.LayoutParams(LayoutHelper.WRAP_CONTENT,
                LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
    }

    if (chatActivityEnterView != null) {
        chatActivityEnterView.onDestroy();
    }
    if (mentionsAdapter != null) {
        mentionsAdapter.onDestroy();
    }

    chatListView = new RecyclerListView(context) {
        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
            super.onLayout(changed, l, t, r, b);
            forceScrollToTop = false;
            if (chatAdapter.isBot) {
                int childCount = getChildCount();
                for (int a = 0; a < childCount; a++) {
                    View child = getChildAt(a);
                    if (child instanceof BotHelpCell) {
                        int height = b - t;
                        int top = height / 2 - child.getMeasuredHeight() / 2;
                        if (child.getTop() > top) {
                            child.layout(0, top, r - l, top + child.getMeasuredHeight());
                        }
                        break;
                    }
                }
            }
        }
    };
    chatListView.setTag(1);
    chatListView.setVerticalScrollBarEnabled(true);
    chatListView.setAdapter(chatAdapter = new ChatActivityAdapter(context));
    chatListView.setClipToPadding(false);
    chatListView.setPadding(0, AndroidUtilities.dp(4), 0, AndroidUtilities.dp(3));
    chatListView.setItemAnimator(null);
    chatListView.setLayoutAnimation(null);
    chatLayoutManager = new LinearLayoutManager(context) {
        @Override
        public boolean supportsPredictiveItemAnimations() {
            return false;
        }
    };
    chatLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    chatLayoutManager.setStackFromEnd(true);
    chatListView.setLayoutManager(chatLayoutManager);
    contentView.addView(chatListView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    chatListView.setOnItemLongClickListener(onItemLongClickListener);
    chatListView.setOnItemClickListener(onItemClickListener);
    chatListView.setOnScrollListener(new RecyclerView.OnScrollListener() {

        private float totalDy = 0;
        private final int scrollValue = AndroidUtilities.dp(100);

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            if (newState == RecyclerView.SCROLL_STATE_DRAGGING && highlightMessageId != Integer.MAX_VALUE) {
                highlightMessageId = Integer.MAX_VALUE;
                updateVisibleRows();
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            checkScrollForLoad(true);
            int firstVisibleItem = chatLayoutManager.findFirstVisibleItemPosition();
            int visibleItemCount = firstVisibleItem == RecyclerView.NO_POSITION ? 0
                    : Math.abs(chatLayoutManager.findLastVisibleItemPosition() - firstVisibleItem) + 1;
            if (visibleItemCount > 0) {
                int totalItemCount = chatAdapter.getItemCount();
                if (firstVisibleItem + visibleItemCount == totalItemCount && forwardEndReached[0]) {
                    showPagedownButton(false, true);
                } else {
                    if (dy > 0) {
                        if (pagedownButton.getTag() == null) {
                            totalDy += dy;
                            if (totalDy > scrollValue) {
                                totalDy = 0;
                                showPagedownButton(true, true);
                                pagedownButtonShowedByScroll = true;
                            }
                        }
                    } else {
                        if (pagedownButtonShowedByScroll && pagedownButton.getTag() != null) {
                            totalDy += dy;
                            if (totalDy < -scrollValue) {
                                showPagedownButton(false, true);
                                totalDy = 0;
                            }
                        }
                    }
                }
            }
            updateMessagesVisisblePart();
        }
    });
    chatListView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (openSecretPhotoRunnable != null || SecretPhotoViewer.getInstance().isVisible()) {
                if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL
                        || event.getAction() == MotionEvent.ACTION_POINTER_UP) {
                    AndroidUtilities.runOnUIThread(new Runnable() {
                        @Override
                        public void run() {
                            chatListView.setOnItemClickListener(onItemClickListener);
                        }
                    }, 150);
                    if (openSecretPhotoRunnable != null) {
                        AndroidUtilities.cancelRunOnUIThread(openSecretPhotoRunnable);
                        openSecretPhotoRunnable = null;
                        try {
                            Toast.makeText(v.getContext(), LocaleController.getString("PhotoTip",
                                    kr.wdream.storyshop.R.string.PhotoTip), Toast.LENGTH_SHORT).show();
                        } catch (Exception e) {
                            FileLog.e("tmessages", e);
                        }
                    } else if (SecretPhotoViewer.getInstance().isVisible()) {
                        AndroidUtilities.runOnUIThread(new Runnable() {
                            @Override
                            public void run() {
                                chatListView.setOnItemLongClickListener(onItemLongClickListener);
                                chatListView.setLongClickable(true);
                            }
                        });
                        SecretPhotoViewer.getInstance().closePhoto();
                    }
                } else if (event.getAction() != MotionEvent.ACTION_DOWN) {
                    if (SecretPhotoViewer.getInstance().isVisible()) {
                        return true;
                    } else if (openSecretPhotoRunnable != null) {
                        if (event.getAction() == MotionEvent.ACTION_MOVE) {
                            if (Math.hypot(startX - event.getX(), startY - event.getY()) > AndroidUtilities
                                    .dp(5)) {
                                AndroidUtilities.cancelRunOnUIThread(openSecretPhotoRunnable);
                                openSecretPhotoRunnable = null;
                            }
                        } else {
                            AndroidUtilities.cancelRunOnUIThread(openSecretPhotoRunnable);
                            openSecretPhotoRunnable = null;
                        }
                        chatListView.setOnItemClickListener(onItemClickListener);
                        chatListView.setOnItemLongClickListener(onItemLongClickListener);
                        chatListView.setLongClickable(true);
                    }
                }
            }
            return false;
        }
    });
    chatListView.setOnInterceptTouchListener(new RecyclerListView.OnInterceptTouchListener() {
        @Override
        public boolean onInterceptTouchEvent(MotionEvent event) {
            if (chatActivityEnterView != null && chatActivityEnterView.isEditingMessage()) {
                return true;
            }
            if (actionBar.isActionModeShowed()) {
                return false;
            }
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                int x = (int) event.getX();
                int y = (int) event.getY();
                int count = chatListView.getChildCount();
                for (int a = 0; a < count; a++) {
                    View view = chatListView.getChildAt(a);
                    int top = view.getTop();
                    int bottom = view.getBottom();
                    if (top > y || bottom < y) {
                        continue;
                    }
                    if (!(view instanceof ChatMessageCell)) {
                        break;
                    }
                    final ChatMessageCell cell = (ChatMessageCell) view;
                    final MessageObject messageObject = cell.getMessageObject();
                    if (messageObject == null || messageObject.isSending() || !messageObject.isSecretPhoto()
                            || !cell.getPhotoImage().isInsideImage(x, y - top)) {
                        break;
                    }
                    File file = FileLoader.getPathToMessage(messageObject.messageOwner);
                    if (!file.exists()) {
                        break;
                    }
                    startX = x;
                    startY = y;
                    chatListView.setOnItemClickListener(null);
                    openSecretPhotoRunnable = new Runnable() {
                        @Override
                        public void run() {
                            if (openSecretPhotoRunnable == null) {
                                return;
                            }
                            chatListView.requestDisallowInterceptTouchEvent(true);
                            chatListView.setOnItemLongClickListener(null);
                            chatListView.setLongClickable(false);
                            openSecretPhotoRunnable = null;
                            if (sendSecretMessageRead(messageObject)) {
                                cell.invalidate();
                            }
                            SecretPhotoViewer.getInstance().setParentActivity(getParentActivity());
                            SecretPhotoViewer.getInstance().openPhoto(messageObject);
                        }
                    };
                    AndroidUtilities.runOnUIThread(openSecretPhotoRunnable, 100);
                    return true;
                }
            }
            return false;
        }
    });

    progressView = new FrameLayout(context);
    progressView.setVisibility(View.INVISIBLE);
    contentView.addView(progressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));

    View view = new View(context);
    view.setBackgroundResource(kr.wdream.storyshop.R.drawable.system_loader);
    view.getBackground().setColorFilter(Theme.colorFilter);
    progressView.addView(view, LayoutHelper.createFrame(36, 36, Gravity.CENTER));

    ProgressBar progressBar = new ProgressBar(context);
    try {
        progressBar.setIndeterminateDrawable(
                context.getResources().getDrawable(kr.wdream.storyshop.R.drawable.loading_animation));
    } catch (Exception e) {
        //don't promt
    }
    progressBar.setIndeterminate(true);
    AndroidUtilities.setProgressBarAnimationDuration(progressBar, 1500);
    progressView.addView(progressBar, LayoutHelper.createFrame(32, 32, Gravity.CENTER));

    if (ChatObject.isChannel(currentChat)) {
        pinnedMessageView = new FrameLayout(context);
        pinnedMessageView.setTag(1);
        pinnedMessageView.setTranslationY(-AndroidUtilities.dp(50));
        pinnedMessageView.setVisibility(View.GONE);
        pinnedMessageView.setBackgroundResource(kr.wdream.storyshop.R.drawable.blockpanel);
        contentView.addView(pinnedMessageView,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 50, Gravity.TOP | Gravity.LEFT));
        pinnedMessageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scrollToMessageId(info.pinned_msg_id, 0, true, 0);
            }
        });

        View lineView = new View(context);
        lineView.setBackgroundColor(0xff6c9fd2);
        pinnedMessageView.addView(lineView,
                LayoutHelper.createFrame(2, 32, Gravity.LEFT | Gravity.TOP, 8, 8, 0, 0));

        pinnedMessageImageView = new BackupImageView(context);
        pinnedMessageView.addView(pinnedMessageImageView,
                LayoutHelper.createFrame(32, 32, Gravity.TOP | Gravity.LEFT, 17, 8, 0, 0));

        pinnedMessageNameTextView = new SimpleTextView(context);
        pinnedMessageNameTextView.setTextSize(14);
        pinnedMessageNameTextView.setTextColor(Theme.PINNED_PANEL_NAME_TEXT_COLOR);
        pinnedMessageNameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
        pinnedMessageView.addView(pinnedMessageNameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
                AndroidUtilities.dp(18), Gravity.TOP | Gravity.LEFT, 18, 7.3f, 52, 0));

        pinnedMessageTextView = new SimpleTextView(context);
        pinnedMessageTextView.setTextSize(14);
        pinnedMessageTextView.setTextColor(Theme.PINNED_PANEL_MESSAGE_TEXT_COLOR);
        pinnedMessageView.addView(pinnedMessageTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
                AndroidUtilities.dp(18), Gravity.TOP | Gravity.LEFT, 18, 25.3f, 52, 0));

        ImageView closePinned = new ImageView(context);
        closePinned.setImageResource(kr.wdream.storyshop.R.drawable.miniplayer_close);
        closePinned.setScaleType(ImageView.ScaleType.CENTER);
        pinnedMessageView.addView(closePinned, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.TOP));
        closePinned.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getParentActivity() == null) {
                    return;
                }
                if (currentChat.creator || currentChat.editor) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                    builder.setMessage(LocaleController.getString("UnpinMessageAlert",
                            kr.wdream.storyshop.R.string.UnpinMessageAlert));
                    builder.setPositiveButton(LocaleController.getString("OK", kr.wdream.storyshop.R.string.OK),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    MessagesController.getInstance().pinChannelMessage(currentChat, 0, false);
                                }
                            });
                    builder.setTitle(
                            LocaleController.getString("AppName", kr.wdream.storyshop.R.string.AppName));
                    builder.setNegativeButton(
                            LocaleController.getString("Cancel", kr.wdream.storyshop.R.string.Cancel), null);
                    showDialog(builder.create());
                } else {
                    SharedPreferences preferences = ApplicationLoader.applicationContext
                            .getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
                    preferences.edit().putInt("pin_" + dialog_id, info.pinned_msg_id).commit();
                    updatePinnedMessageView(true);
                }
            }
        });
    }

    reportSpamView = new LinearLayout(context);
    reportSpamView.setTag(1);
    reportSpamView.setTranslationY(-AndroidUtilities.dp(50));
    reportSpamView.setVisibility(View.GONE);
    reportSpamView.setBackgroundResource(kr.wdream.storyshop.R.drawable.blockpanel);
    contentView.addView(reportSpamView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 50, Gravity.TOP | Gravity.LEFT));

    addToContactsButton = new TextView(context);
    addToContactsButton.setTextColor(Theme.CHAT_ADD_CONTACT_TEXT_COLOR);
    addToContactsButton.setVisibility(View.GONE);
    addToContactsButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    addToContactsButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    addToContactsButton.setSingleLine(true);
    addToContactsButton.setMaxLines(1);
    addToContactsButton.setPadding(AndroidUtilities.dp(4), 0, AndroidUtilities.dp(4), 0);
    addToContactsButton.setGravity(Gravity.CENTER);
    addToContactsButton
            .setText(LocaleController.getString("AddContactChat", kr.wdream.storyshop.R.string.AddContactChat));
    reportSpamView.addView(addToContactsButton, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT,
            LayoutHelper.MATCH_PARENT, 0.5f, Gravity.LEFT | Gravity.TOP, 0, 0, 0, AndroidUtilities.dp(1)));
    addToContactsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Bundle args = new Bundle();
            args.putInt("user_id", currentUser.id);
            args.putBoolean("addContact", true);
            presentFragment(new ContactAddActivity(args));
        }
    });

    reportSpamContainer = new FrameLayout(context);
    reportSpamView.addView(reportSpamContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT,
            LayoutHelper.MATCH_PARENT, 1.0f, Gravity.LEFT | Gravity.TOP, 0, 0, 0, AndroidUtilities.dp(1)));

    reportSpamButton = new TextView(context);
    reportSpamButton.setTextColor(Theme.CHAT_REPORT_SPAM_TEXT_COLOR);
    reportSpamButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    reportSpamButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    reportSpamButton.setSingleLine(true);
    reportSpamButton.setMaxLines(1);
    if (currentChat != null) {
        reportSpamButton.setText(LocaleController.getString("ReportSpamAndLeave",
                kr.wdream.storyshop.R.string.ReportSpamAndLeave));
    } else {
        reportSpamButton
                .setText(LocaleController.getString("ReportSpam", kr.wdream.storyshop.R.string.ReportSpam));
    }
    reportSpamButton.setGravity(Gravity.CENTER);
    reportSpamButton.setPadding(AndroidUtilities.dp(50), 0, AndroidUtilities.dp(50), 0);
    reportSpamContainer.addView(reportSpamButton, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
    reportSpamButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (getParentActivity() == null) {
                return;
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
            if (ChatObject.isChannel(currentChat) && !currentChat.megagroup) {
                builder.setMessage(LocaleController.getString("ReportSpamAlertChannel",
                        kr.wdream.storyshop.R.string.ReportSpamAlertChannel));
            } else if (currentChat != null) {
                builder.setMessage(LocaleController.getString("ReportSpamAlertGroup",
                        kr.wdream.storyshop.R.string.ReportSpamAlertGroup));
            } else {
                builder.setMessage(LocaleController.getString("ReportSpamAlert",
                        kr.wdream.storyshop.R.string.ReportSpamAlert));
            }
            builder.setTitle(LocaleController.getString("AppName", kr.wdream.storyshop.R.string.AppName));
            builder.setPositiveButton(LocaleController.getString("OK", kr.wdream.storyshop.R.string.OK),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            if (currentUser != null) {
                                MessagesController.getInstance().blockUser(currentUser.id);
                            }
                            MessagesController.getInstance().reportSpam(dialog_id, currentUser, currentChat);
                            updateSpamView();
                            if (currentChat != null) {
                                if (ChatObject.isNotInChat(currentChat)) {
                                    MessagesController.getInstance().deleteDialog(dialog_id, 0);
                                } else {
                                    MessagesController.getInstance().deleteUserFromChat((int) -dialog_id,
                                            MessagesController.getInstance()
                                                    .getUser(UserConfig.getClientUserId()),
                                            null);
                                }
                            } else {
                                MessagesController.getInstance().deleteDialog(dialog_id, 0);
                            }
                            finishFragment();
                        }
                    });
            builder.setNegativeButton(LocaleController.getString("Cancel", kr.wdream.storyshop.R.string.Cancel),
                    null);
            showDialog(builder.create());
        }
    });

    ImageView closeReportSpam = new ImageView(context);
    closeReportSpam.setImageResource(kr.wdream.storyshop.R.drawable.miniplayer_close);
    closeReportSpam.setScaleType(ImageView.ScaleType.CENTER);
    reportSpamContainer.addView(closeReportSpam, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.TOP));
    closeReportSpam.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MessagesController.getInstance().hideReportSpam(dialog_id, currentUser, currentChat);
            updateSpamView();
        }
    });

    alertView = new FrameLayout(context);
    alertView.setTag(1);
    alertView.setTranslationY(-AndroidUtilities.dp(50));
    alertView.setVisibility(View.GONE);
    alertView.setBackgroundResource(kr.wdream.storyshop.R.drawable.blockpanel);
    contentView.addView(alertView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 50, Gravity.TOP | Gravity.LEFT));

    alertNameTextView = new TextView(context);
    alertNameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    alertNameTextView.setTextColor(Theme.ALERT_PANEL_NAME_TEXT_COLOR);
    alertNameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    alertNameTextView.setSingleLine(true);
    alertNameTextView.setEllipsize(TextUtils.TruncateAt.END);
    alertNameTextView.setMaxLines(1);
    alertView.addView(alertNameTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 8, 5, 8, 0));

    alertTextView = new TextView(context);
    alertTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    alertTextView.setTextColor(Theme.ALERT_PANEL_MESSAGE_TEXT_COLOR);
    alertTextView.setSingleLine(true);
    alertTextView.setEllipsize(TextUtils.TruncateAt.END);
    alertTextView.setMaxLines(1);
    alertView.addView(alertTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 8, 23, 8, 0));

    if (!isBroadcast) {
        mentionContainer = new FrameLayout(context) {

            private Drawable background;

            @Override
            public void onDraw(Canvas canvas) {
                if (mentionListView.getChildCount() <= 0) {
                    return;
                }
                if (mentionsAdapter.isBotContext() && mentionsAdapter.isMediaLayout()
                        && mentionsAdapter.getBotContextSwitch() == null) {
                    background.setBounds(0, mentionListViewScrollOffsetY - AndroidUtilities.dp(4),
                            getMeasuredWidth(), getMeasuredHeight());
                } else {
                    background.setBounds(0, mentionListViewScrollOffsetY - AndroidUtilities.dp(2),
                            getMeasuredWidth(), getMeasuredHeight());
                }
                background.draw(canvas);
            }

            @Override
            public void setBackgroundResource(int resid) {
                background = getContext().getResources().getDrawable(resid);
            }

            @Override
            public void requestLayout() {
                if (mentionListViewIgnoreLayout) {
                    return;
                }
                super.requestLayout();
            }
        };
        mentionContainer.setBackgroundResource(kr.wdream.storyshop.R.drawable.compose_panel);
        mentionContainer.setVisibility(View.GONE);
        mentionContainer.setWillNotDraw(false);
        contentView.addView(mentionContainer,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 110, Gravity.LEFT | Gravity.BOTTOM));

        mentionListView = new RecyclerListView(context) {

            private int lastWidth;
            private int lastHeight;

            @Override
            public boolean onInterceptTouchEvent(MotionEvent event) {
                if (!mentionListViewIsScrolling && mentionListViewScrollOffsetY != 0
                        && event.getY() < mentionListViewScrollOffsetY) {
                    return false;
                }
                boolean result = StickerPreviewViewer.getInstance().onInterceptTouchEvent(event,
                        mentionListView, 0);
                return super.onInterceptTouchEvent(event) || result;
            }

            @Override
            public boolean onTouchEvent(MotionEvent event) {
                if (!mentionListViewIsScrolling && mentionListViewScrollOffsetY != 0
                        && event.getY() < mentionListViewScrollOffsetY) {
                    return false;
                }
                //supress warning
                return super.onTouchEvent(event);
            }

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

            @Override
            protected void onLayout(boolean changed, int l, int t, int r, int b) {
                int width = r - l;
                int height = b - t;

                int newPosition = -1;
                int newTop = 0;
                if (mentionListView != null && mentionListViewLastViewPosition >= 0 && width == lastWidth
                        && height - lastHeight != 0) {
                    newPosition = mentionListViewLastViewPosition;
                    newTop = mentionListViewLastViewTop + height - lastHeight - getPaddingTop();
                }

                super.onLayout(changed, l, t, r, b);

                if (newPosition != -1) {
                    mentionListViewIgnoreLayout = true;
                    if (mentionsAdapter.isBotContext() && mentionsAdapter.isMediaLayout()) {
                        mentionGridLayoutManager.scrollToPositionWithOffset(newPosition, newTop);
                    } else {
                        mentionLayoutManager.scrollToPositionWithOffset(newPosition, newTop);
                    }
                    super.onLayout(false, l, t, r, b);
                    mentionListViewIgnoreLayout = false;
                }

                lastHeight = height;
                lastWidth = width;
                mentionListViewUpdateLayout();
            }
        };
        mentionListView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return StickerPreviewViewer.getInstance().onTouch(event, mentionListView, 0,
                        mentionsOnItemClickListener);
            }
        });
        mentionListView.setTag(2);
        mentionLayoutManager = new LinearLayoutManager(context) {
            @Override
            public boolean supportsPredictiveItemAnimations() {
                return false;
            }
        };
        mentionLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mentionGridLayoutManager = new ExtendedGridLayoutManager(context, 100) {

            private Size size = new Size();

            @Override
            protected Size getSizeForItem(int i) {
                if (mentionsAdapter.getBotContextSwitch() != null) {
                    i++;
                }
                Object object = mentionsAdapter.getItem(i);
                if (object instanceof TLRPC.BotInlineResult) {
                    TLRPC.BotInlineResult inlineResult = (TLRPC.BotInlineResult) object;
                    if (inlineResult.document != null) {
                        size.width = inlineResult.document.thumb != null ? inlineResult.document.thumb.w : 100;
                        size.height = inlineResult.document.thumb != null ? inlineResult.document.thumb.h : 100;
                        for (int b = 0; b < inlineResult.document.attributes.size(); b++) {
                            TLRPC.DocumentAttribute attribute = inlineResult.document.attributes.get(b);
                            if (attribute instanceof TLRPC.TL_documentAttributeImageSize
                                    || attribute instanceof TLRPC.TL_documentAttributeVideo) {
                                size.width = attribute.w;
                                size.height = attribute.h;
                                break;
                            }
                        }
                    } else {
                        size.width = inlineResult.w;
                        size.height = inlineResult.h;
                    }
                }
                return size;
            }

            @Override
            protected int getFlowItemCount() {
                if (mentionsAdapter.getBotContextSwitch() != null) {
                    return getItemCount() - 1;
                }
                return super.getFlowItemCount();
            }
        };
        mentionGridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                Object object = mentionsAdapter.getItem(position);
                if (object instanceof TLRPC.TL_inlineBotSwitchPM) {
                    return 100;
                } else {
                    if (mentionsAdapter.getBotContextSwitch() != null) {
                        position--;
                    }
                    return mentionGridLayoutManager.getSpanSizeForItem(position);
                }
            }
        });
        mentionListView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.left = 0;
                outRect.right = 0;
                outRect.top = 0;
                outRect.bottom = 0;
                if (parent.getLayoutManager() == mentionGridLayoutManager) {
                    int position = parent.getChildAdapterPosition(view);
                    if (mentionsAdapter.getBotContextSwitch() != null) {
                        if (position == 0) {
                            return;
                        }
                        position--;
                        if (!mentionGridLayoutManager.isFirstRow(position)) {
                            outRect.top = AndroidUtilities.dp(2);
                        }
                    } else {
                        outRect.top = AndroidUtilities.dp(2);
                    }
                    outRect.right = mentionGridLayoutManager.isLastInRow(position) ? 0 : AndroidUtilities.dp(2);
                }
            }
        });
        mentionListView.setItemAnimator(null);
        mentionListView.setLayoutAnimation(null);
        mentionListView.setClipToPadding(false);
        mentionListView.setLayoutManager(mentionLayoutManager);
        mentionListView.setOverScrollMode(ListView.OVER_SCROLL_NEVER);
        mentionContainer.addView(mentionListView,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));

        mentionListView.setAdapter(mentionsAdapter = new MentionsAdapter(context, false, dialog_id,
                new MentionsAdapter.MentionsAdapterDelegate() {
                    @Override
                    public void needChangePanelVisibility(boolean show) {
                        if (mentionsAdapter.isBotContext() && mentionsAdapter.isMediaLayout()) {
                            mentionListView.setLayoutManager(mentionGridLayoutManager);
                        } else {
                            mentionListView.setLayoutManager(mentionLayoutManager);
                        }
                        if (show) {
                            if (mentionListAnimation != null) {
                                mentionListAnimation.cancel();
                                mentionListAnimation = null;
                            }

                            if (mentionContainer.getVisibility() == View.VISIBLE) {
                                mentionContainer.setAlpha(1.0f);
                                return;
                            }
                            if (mentionsAdapter.isBotContext() && mentionsAdapter.isMediaLayout()) {
                                mentionGridLayoutManager.scrollToPositionWithOffset(0, 10000);
                            } else {
                                mentionLayoutManager.scrollToPositionWithOffset(0, 10000);
                            }
                            if (allowStickersPanel && (!mentionsAdapter.isBotContext()
                                    || (allowContextBotPanel || allowContextBotPanelSecond))) {
                                if (currentEncryptedChat != null && mentionsAdapter.isBotContext()) {
                                    SharedPreferences preferences = ApplicationLoader.applicationContext
                                            .getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
                                    if (!preferences.getBoolean("secretbot", false)) {
                                        AlertDialog.Builder builder = new AlertDialog.Builder(
                                                getParentActivity());
                                        builder.setTitle(LocaleController.getString("AppName",
                                                kr.wdream.storyshop.R.string.AppName));
                                        builder.setMessage(LocaleController.getString(
                                                "SecretChatContextBotAlert",
                                                kr.wdream.storyshop.R.string.SecretChatContextBotAlert));
                                        builder.setPositiveButton(LocaleController.getString("OK",
                                                kr.wdream.storyshop.R.string.OK), null);
                                        showDialog(builder.create());
                                        preferences.edit().putBoolean("secretbot", true).commit();
                                    }
                                }
                                mentionContainer.setVisibility(View.VISIBLE);
                                mentionContainer.setTag(null);
                                mentionListAnimation = new AnimatorSet();
                                mentionListAnimation.playTogether(
                                        ObjectAnimator.ofFloat(mentionContainer, "alpha", 0.0f, 1.0f));
                                mentionListAnimation.addListener(new AnimatorListenerAdapterProxy() {
                                    @Override
                                    public void onAnimationEnd(Animator animation) {
                                        if (mentionListAnimation != null
                                                && mentionListAnimation.equals(animation)) {
                                            mentionListAnimation = null;
                                        }
                                    }

                                    @Override
                                    public void onAnimationCancel(Animator animation) {
                                        if (mentionListAnimation != null
                                                && mentionListAnimation.equals(animation)) {
                                            mentionListAnimation = null;
                                        }
                                    }
                                });
                                mentionListAnimation.setDuration(200);
                                mentionListAnimation.start();
                            } else {
                                mentionContainer.setAlpha(1.0f);
                                mentionContainer.setVisibility(View.INVISIBLE);
                            }
                        } else {
                            if (mentionListAnimation != null) {
                                mentionListAnimation.cancel();
                                mentionListAnimation = null;
                            }

                            if (mentionContainer.getVisibility() == View.GONE) {
                                return;
                            }
                            if (allowStickersPanel) {
                                mentionListAnimation = new AnimatorSet();
                                mentionListAnimation
                                        .playTogether(ObjectAnimator.ofFloat(mentionContainer, "alpha", 0.0f));
                                mentionListAnimation.addListener(new AnimatorListenerAdapterProxy() {
                                    @Override
                                    public void onAnimationEnd(Animator animation) {
                                        if (mentionListAnimation != null
                                                && mentionListAnimation.equals(animation)) {
                                            mentionContainer.setVisibility(View.GONE);
                                            mentionContainer.setTag(null);
                                            mentionListAnimation = null;
                                        }
                                    }

                                    @Override
                                    public void onAnimationCancel(Animator animation) {
                                        if (mentionListAnimation != null
                                                && mentionListAnimation.equals(animation)) {
                                            mentionListAnimation = null;
                                        }
                                    }
                                });
                                mentionListAnimation.setDuration(200);
                                mentionListAnimation.start();
                            } else {
                                mentionContainer.setTag(null);
                                mentionContainer.setVisibility(View.GONE);
                            }
                        }
                    }

                    @Override
                    public void onContextSearch(boolean searching) {
                        if (chatActivityEnterView != null) {
                            chatActivityEnterView.setCaption(mentionsAdapter.getBotCaption());
                            chatActivityEnterView.showContextProgress(searching);
                        }
                    }

                    @Override
                    public void onContextClick(TLRPC.BotInlineResult result) {
                        if (getParentActivity() == null || result.content_url == null) {
                            return;
                        }
                        if (result.type.equals("video") || result.type.equals("web_player_video")) {
                            BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity());
                            builder.setCustomView(new WebFrameLayout(getParentActivity(), builder.create(),
                                    result.title != null ? result.title : "", result.description,
                                    result.content_url, result.content_url, result.w, result.h));
                            builder.setUseFullWidth(true);
                            showDialog(builder.create());
                        } else {
                            Browser.openUrl(getParentActivity(), result.content_url);
                        }
                    }
                }));
        if (!ChatObject.isChannel(currentChat) || currentChat != null && currentChat.megagroup) {
            mentionsAdapter.setBotInfo(botInfo);
        }
        mentionsAdapter.setParentFragment(this);
        mentionsAdapter.setChatInfo(info);
        mentionsAdapter.setNeedUsernames(currentChat != null);
        mentionsAdapter.setNeedBotContext(currentEncryptedChat == null
                || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 46);
        mentionsAdapter.setBotsCount(currentChat != null ? botsCount : 1);
        mentionListView.setOnItemClickListener(
                mentionsOnItemClickListener = new RecyclerListView.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        Object object = mentionsAdapter.getItem(position);
                        int start = mentionsAdapter.getResultStartPosition();
                        int len = mentionsAdapter.getResultLength();
                        if (object instanceof TLRPC.User) {
                            TLRPC.User user = (TLRPC.User) object;
                            if (user != null) {
                                if (user.username != null) {
                                    chatActivityEnterView.replaceWithText(start, len,
                                            "@" + user.username + " ");
                                } else {
                                    String name = user.first_name;
                                    if (name == null || name.length() == 0) {
                                        name = user.last_name;
                                    }
                                    Spannable spannable = new SpannableString(name + " ");
                                    spannable.setSpan(new URLSpanUserMention("" + user.id), 0,
                                            spannable.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    chatActivityEnterView.replaceWithText(start, len, spannable);
                                }
                            }
                        } else if (object instanceof String) {
                            if (mentionsAdapter.isBotCommands()) {
                                SendMessagesHelper.getInstance().sendMessage((String) object, dialog_id, null,
                                        null, false, null, null, null);
                                chatActivityEnterView.setFieldText("");
                            } else {
                                chatActivityEnterView.replaceWithText(start, len, object + " ");
                            }
                        } else if (object instanceof TLRPC.BotInlineResult) {
                            if (chatActivityEnterView.getFieldText() == null) {
                                return;
                            }
                            TLRPC.BotInlineResult result = (TLRPC.BotInlineResult) object;
                            if (Build.VERSION.SDK_INT >= 16 && (result.type.equals("photo")
                                    && (result.photo != null || result.content_url != null)
                                    || result.type.equals("gif")
                                            && (result.document != null || result.content_url != null)
                                    || result.type.equals("video")
                                            && (result.document != null/* || result.content_url != null*/))) {
                                ArrayList<Object> arrayList = botContextResults = new ArrayList<Object>(
                                        mentionsAdapter.getSearchResultBotContext());
                                PhotoViewer.getInstance().setParentActivity(getParentActivity());
                                PhotoViewer.getInstance().openPhotoForSelect(arrayList,
                                        mentionsAdapter.getItemPosition(position), 3, botContextProvider, null);
                            } else {
                                sendBotInlineResult(result);
                            }
                        } else if (object instanceof TLRPC.TL_inlineBotSwitchPM) {
                            processInlineBotContextPM((TLRPC.TL_inlineBotSwitchPM) object);
                        }
                    }
                });

        mentionListView.setOnItemLongClickListener(new RecyclerListView.OnItemLongClickListener() {
            @Override
            public boolean onItemClick(View view, int position) {
                if (getParentActivity() == null || !mentionsAdapter.isLongClickEnabled()) {
                    return false;
                }
                Object object = mentionsAdapter.getItem(position);
                if (object instanceof String) {
                    if (mentionsAdapter.isBotCommands()) {
                        if (URLSpanBotCommand.enabled) {
                            chatActivityEnterView.setFieldText("");
                            chatActivityEnterView.setCommand(null, (String) object, true,
                                    currentChat != null && currentChat.megagroup);
                            return true;
                        }
                        return false;
                    } else {
                        AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                        builder.setTitle(
                                LocaleController.getString("AppName", kr.wdream.storyshop.R.string.AppName));
                        builder.setMessage(LocaleController.getString("ClearSearch",
                                kr.wdream.storyshop.R.string.ClearSearch));
                        builder.setPositiveButton(LocaleController
                                .getString("ClearButton", kr.wdream.storyshop.R.string.ClearButton)
                                .toUpperCase(), new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        mentionsAdapter.clearRecentHashtags();
                                    }
                                });
                        builder.setNegativeButton(
                                LocaleController.getString("Cancel", kr.wdream.storyshop.R.string.Cancel),
                                null);
                        showDialog(builder.create());
                        return true;
                    }
                }
                return false;
            }
        });

        mentionListView.setOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                mentionListViewIsScrolling = newState == RecyclerView.SCROLL_STATE_DRAGGING;
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                int lastVisibleItem;
                if (mentionsAdapter.isBotContext() && mentionsAdapter.isMediaLayout()) {
                    lastVisibleItem = mentionGridLayoutManager.findLastVisibleItemPosition();
                } else {
                    lastVisibleItem = mentionLayoutManager.findLastVisibleItemPosition();
                }
                int visibleItemCount = lastVisibleItem == RecyclerView.NO_POSITION ? 0 : lastVisibleItem;
                if (visibleItemCount > 0 && lastVisibleItem > mentionsAdapter.getItemCount() - 5) {
                    mentionsAdapter.searchForContextBotForNextOffset();
                }
                mentionListViewUpdateLayout();
            }
        });
    }

    pagedownButton = new FrameLayout(context);
    pagedownButton.setVisibility(View.INVISIBLE);
    contentView.addView(pagedownButton,
            LayoutHelper.createFrame(46, 59, Gravity.RIGHT | Gravity.BOTTOM, 0, 0, 7, 5));
    pagedownButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (returnToMessageId > 0) {
                scrollToMessageId(returnToMessageId, 0, true, returnToLoadIndex);
            } else {
                scrollToLastMessage(true);
            }
        }
    });

    ImageView pagedownButtonImage = new ImageView(context);
    pagedownButtonImage.setImageResource(kr.wdream.storyshop.R.drawable.pagedown);
    pagedownButton.addView(pagedownButtonImage,
            LayoutHelper.createFrame(46, 46, Gravity.LEFT | Gravity.BOTTOM));

    pagedownButtonCounter = new TextView(context);
    pagedownButtonCounter.setVisibility(View.INVISIBLE);
    pagedownButtonCounter.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    pagedownButtonCounter.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
    pagedownButtonCounter.setTextColor(0xffffffff);
    pagedownButtonCounter.setGravity(Gravity.CENTER);
    pagedownButtonCounter.setBackgroundResource(kr.wdream.storyshop.R.drawable.chat_badge);
    pagedownButtonCounter.setMinWidth(AndroidUtilities.dp(23));
    pagedownButtonCounter.setPadding(AndroidUtilities.dp(8), 0, AndroidUtilities.dp(8), AndroidUtilities.dp(1));
    pagedownButton.addView(pagedownButtonCounter,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 23, Gravity.TOP | Gravity.CENTER_HORIZONTAL));

    chatActivityEnterView = new ChatActivityEnterView(getParentActivity(), contentView, this, true);
    chatActivityEnterView.setDialogId(dialog_id);
    chatActivityEnterView.addToAttachLayout(menuItem);
    chatActivityEnterView.setId(id_chat_compose_panel);
    chatActivityEnterView.setBotsCount(botsCount, hasBotsCommands);
    chatActivityEnterView.setAllowStickersAndGifs(
            currentEncryptedChat == null
                    || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 23,
            currentEncryptedChat == null
                    || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 46);
    contentView.addView(chatActivityEnterView, contentView.getChildCount() - 1, LayoutHelper
            .createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.BOTTOM));
    chatActivityEnterView.setDelegate(new ChatActivityEnterView.ChatActivityEnterViewDelegate() {
        @Override
        public void onMessageSend(CharSequence message) {
            moveScrollToLastMessage();
            showReplyPanel(false, null, null, null, false, true);
            if (mentionsAdapter != null) {
                mentionsAdapter.addHashtagsFromMessage(message);
            }
        }

        @Override
        public void onTextChanged(final CharSequence text, boolean bigChange) {
            MediaController.getInstance().setInputFieldHasText(
                    text != null && text.length() != 0 || chatActivityEnterView.isEditingMessage());
            if (stickersAdapter != null && !chatActivityEnterView.isEditingMessage()) {
                stickersAdapter.loadStikersForEmoji(text);
            }
            if (mentionsAdapter != null) {
                mentionsAdapter.searchUsernameOrHashtag(text.toString(),
                        chatActivityEnterView.getCursorPosition(), messages);
            }
            if (waitingForCharaterEnterRunnable != null) {
                AndroidUtilities.cancelRunOnUIThread(waitingForCharaterEnterRunnable);
                waitingForCharaterEnterRunnable = null;
            }
            if (chatActivityEnterView.isMessageWebPageSearchEnabled()
                    && (!chatActivityEnterView.isEditingMessage()
                            || !chatActivityEnterView.isEditingCaption())) {
                if (bigChange) {
                    searchLinks(text, true);
                } else {
                    waitingForCharaterEnterRunnable = new Runnable() {
                        @Override
                        public void run() {
                            if (this == waitingForCharaterEnterRunnable) {
                                searchLinks(text, false);
                                waitingForCharaterEnterRunnable = null;
                            }
                        }
                    };
                    AndroidUtilities.runOnUIThread(waitingForCharaterEnterRunnable,
                            AndroidUtilities.WEB_URL == null ? 3000 : 1000);
                }
            }
        }

        @Override
        public void needSendTyping() {
            MessagesController.getInstance().sendTyping(dialog_id, 0, classGuid);
        }

        @Override
        public void onAttachButtonHidden() {
            if (actionBar.isSearchFieldVisible()) {
                return;
            }
            if (attachItem != null) {
                attachItem.setVisibility(View.VISIBLE);
            }
            if (headerItem != null) {
                headerItem.setVisibility(View.GONE);
            }
        }

        @Override
        public void onAttachButtonShow() {
            if (actionBar.isSearchFieldVisible()) {
                return;
            }
            if (attachItem != null) {
                attachItem.setVisibility(View.GONE);
            }
            if (headerItem != null) {
                headerItem.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onMessageEditEnd(boolean loading) {
            if (loading) {
                showEditDoneProgress(true, true);
            } else {
                mentionsAdapter.setNeedBotContext(currentEncryptedChat == null
                        || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 46);
                chatListView.setOnItemLongClickListener(onItemLongClickListener);
                chatListView.setOnItemClickListener(onItemClickListener);
                chatListView.setClickable(true);
                chatListView.setLongClickable(true);
                mentionsAdapter.setAllowNewMentions(true);
                actionModeTitleContainer.setVisibility(View.GONE);
                selectedMessagesCountTextView.setVisibility(View.VISIBLE);
                chatActivityEnterView.setAllowStickersAndGifs(
                        currentEncryptedChat == null
                                || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 23,
                        currentEncryptedChat == null
                                || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 46);
                if (editingMessageObjectReqId != 0) {
                    ConnectionsManager.getInstance().cancelRequest(editingMessageObjectReqId, true);
                    editingMessageObjectReqId = 0;
                }
                actionBar.hideActionMode();
                updatePinnedMessageView(true);
                updateVisibleRows();
            }
        }

        @Override
        public void onWindowSizeChanged(int size) {
            if (size < AndroidUtilities.dp(72) + ActionBar.getCurrentActionBarHeight()) {
                allowStickersPanel = false;
                if (stickersPanel.getVisibility() == View.VISIBLE) {
                    stickersPanel.setVisibility(View.INVISIBLE);
                }
                if (mentionContainer != null && mentionContainer.getVisibility() == View.VISIBLE) {
                    mentionContainer.setVisibility(View.INVISIBLE);
                }
            } else {
                allowStickersPanel = true;
                if (stickersPanel.getVisibility() == View.INVISIBLE) {
                    stickersPanel.setVisibility(View.VISIBLE);
                }
                if (mentionContainer != null && mentionContainer.getVisibility() == View.INVISIBLE
                        && (!mentionsAdapter.isBotContext()
                                || (allowContextBotPanel || allowContextBotPanelSecond))) {
                    mentionContainer.setVisibility(View.VISIBLE);
                    mentionContainer.setTag(null);
                }
            }

            allowContextBotPanel = !chatActivityEnterView.isPopupShowing();
            checkContextBotPanel();
        }

        @Override
        public void onStickersTab(boolean opened) {
            if (emojiButtonRed != null) {
                emojiButtonRed.setVisibility(View.GONE);
            }
            allowContextBotPanelSecond = !opened;
            checkContextBotPanel();
        }
    });

    FrameLayout replyLayout = new FrameLayout(context) {
        @Override
        public void setTranslationY(float translationY) {
            super.setTranslationY(translationY);
            if (chatActivityEnterView != null) {
                chatActivityEnterView.invalidate();
            }
            if (getVisibility() != GONE) {
                int height = getLayoutParams().height;
                if (chatListView != null) {
                    chatListView.setTranslationY(translationY);
                }
                if (progressView != null) {
                    progressView.setTranslationY(translationY);
                }
                if (mentionContainer != null) {
                    mentionContainer.setTranslationY(translationY);
                }
                if (pagedownButton != null) {
                    pagedownButton.setTranslationY(translationY);
                }
            }
        }

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

        @Override
        public void setVisibility(int visibility) {
            super.setVisibility(visibility);
            if (visibility == GONE) {
                if (chatListView != null) {
                    chatListView.setTranslationY(0);
                }
                if (progressView != null) {
                    progressView.setTranslationY(0);
                }
                if (mentionContainer != null) {
                    mentionContainer.setTranslationY(0);
                }
                if (pagedownButton != null) {
                    pagedownButton
                            .setTranslationY(pagedownButton.getTag() == null ? AndroidUtilities.dp(100) : 0);
                }
            }
        }
    };
    replyLayout.setClickable(true);
    chatActivityEnterView.addTopView(replyLayout, 48);

    View lineView = new View(context);
    lineView.setBackgroundColor(0xffe8e8e8);
    replyLayout.addView(lineView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 1, Gravity.BOTTOM | Gravity.LEFT));

    replyIconImageView = new ImageView(context);
    replyIconImageView.setScaleType(ImageView.ScaleType.CENTER);
    replyLayout.addView(replyIconImageView, LayoutHelper.createFrame(52, 46, Gravity.TOP | Gravity.LEFT));

    ImageView imageView = new ImageView(context);
    imageView.setImageResource(kr.wdream.storyshop.R.drawable.delete_reply);
    imageView.setScaleType(ImageView.ScaleType.CENTER);
    replyLayout.addView(imageView,
            LayoutHelper.createFrame(52, 46, Gravity.RIGHT | Gravity.TOP, 0, 0.5f, 0, 0));
    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (forwardingMessages != null) {
                forwardingMessages.clear();
            }
            showReplyPanel(false, null, null, foundWebPage, true, true);
        }
    });

    replyNameTextView = new SimpleTextView(context);
    replyNameTextView.setTextSize(14);
    replyNameTextView.setTextColor(Theme.REPLY_PANEL_NAME_TEXT_COLOR);
    replyNameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    replyLayout.addView(replyNameTextView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.TOP | Gravity.LEFT, 52, 6, 52, 0));

    replyObjectTextView = new SimpleTextView(context);
    replyObjectTextView.setTextSize(14);
    replyObjectTextView.setTextColor(Theme.REPLY_PANEL_MESSAGE_TEXT_COLOR);
    replyLayout.addView(replyObjectTextView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.TOP | Gravity.LEFT, 52, 24, 52, 0));

    replyImageView = new BackupImageView(context);
    replyLayout.addView(replyImageView,
            LayoutHelper.createFrame(34, 34, Gravity.TOP | Gravity.LEFT, 52, 6, 0, 0));

    stickersPanel = new FrameLayout(context);
    stickersPanel.setVisibility(View.GONE);
    contentView.addView(stickersPanel, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 81.5f,
            Gravity.LEFT | Gravity.BOTTOM, 0, 0, 0, 38));

    stickersListView = new RecyclerListView(context) {
        @Override
        public boolean onInterceptTouchEvent(MotionEvent event) {
            boolean result = StickerPreviewViewer.getInstance().onInterceptTouchEvent(event, stickersListView,
                    0);
            return super.onInterceptTouchEvent(event) || result;
        }
    };
    stickersListView.setTag(3);
    stickersListView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return StickerPreviewViewer.getInstance().onTouch(event, stickersListView, 0,
                    stickersOnItemClickListener);
        }
    });
    stickersListView.setDisallowInterceptTouchEvents(true);
    LinearLayoutManager layoutManager = new LinearLayoutManager(context);
    layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
    stickersListView.setLayoutManager(layoutManager);
    stickersListView.setClipToPadding(false);
    stickersListView.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER);
    stickersPanel.addView(stickersListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 78));
    initStickers();

    imageView = new ImageView(context);
    imageView.setImageResource(kr.wdream.storyshop.R.drawable.stickers_back_arrow);
    stickersPanel.addView(imageView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 53, 0, 0, 0));

    searchContainer = new FrameLayout(context);
    searchContainer.setBackgroundResource(kr.wdream.storyshop.R.drawable.compose_panel);
    searchContainer.setVisibility(View.INVISIBLE);
    searchContainer.setFocusable(true);
    searchContainer.setFocusableInTouchMode(true);
    searchContainer.setClickable(true);
    searchContainer.setBackgroundResource(kr.wdream.storyshop.R.drawable.compose_panel);
    searchContainer.setPadding(0, AndroidUtilities.dp(3), 0, 0);
    contentView.addView(searchContainer,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM));

    searchUpButton = new ImageView(context);
    searchUpButton.setScaleType(ImageView.ScaleType.CENTER);
    searchUpButton.setImageResource(kr.wdream.storyshop.R.drawable.search_up);
    searchContainer.addView(searchUpButton, LayoutHelper.createFrame(48, 48));
    searchUpButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            MessagesSearchQuery.searchMessagesInChat(null, dialog_id, mergeDialogId, classGuid, 1);
        }
    });

    searchDownButton = new ImageView(context);
    searchDownButton.setScaleType(ImageView.ScaleType.CENTER);
    searchDownButton.setImageResource(kr.wdream.storyshop.R.drawable.search_down);
    searchContainer.addView(searchDownButton,
            LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.TOP, 48, 0, 0, 0));
    searchDownButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            MessagesSearchQuery.searchMessagesInChat(null, dialog_id, mergeDialogId, classGuid, 2);
        }
    });

    searchCountText = new SimpleTextView(context);
    searchCountText.setTextColor(Theme.CHAT_SEARCH_COUNT_TEXT_COLOR);
    searchCountText.setTextSize(15);
    searchCountText.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    searchContainer.addView(searchCountText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL, 108, 0, 0, 0));

    bottomOverlay = new FrameLayout(context);
    bottomOverlay.setVisibility(View.INVISIBLE);
    bottomOverlay.setFocusable(true);
    bottomOverlay.setFocusableInTouchMode(true);
    bottomOverlay.setClickable(true);
    bottomOverlay.setBackgroundResource(kr.wdream.storyshop.R.drawable.compose_panel);
    bottomOverlay.setPadding(0, AndroidUtilities.dp(3), 0, 0);
    contentView.addView(bottomOverlay, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM));

    bottomOverlayText = new TextView(context);
    bottomOverlayText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
    bottomOverlayText.setTextColor(Theme.CHAT_BOTTOM_OVERLAY_TEXT_COLOR);
    bottomOverlay.addView(bottomOverlayText,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));

    bottomOverlayChat = new FrameLayout(context);
    bottomOverlayChat.setBackgroundResource(kr.wdream.storyshop.R.drawable.compose_panel);
    bottomOverlayChat.setPadding(0, AndroidUtilities.dp(3), 0, 0);
    bottomOverlayChat.setVisibility(View.INVISIBLE);
    contentView.addView(bottomOverlayChat,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM));
    bottomOverlayChat.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (getParentActivity() == null) {
                return;
            }
            AlertDialog.Builder builder = null;
            if (currentUser != null && userBlocked) {
                if (currentUser.bot) {
                    String botUserLast = botUser;
                    botUser = null;
                    MessagesController.getInstance().unblockUser(currentUser.id);
                    if (botUserLast != null && botUserLast.length() != 0) {
                        MessagesController.getInstance().sendBotStart(currentUser, botUserLast);
                    } else {
                        SendMessagesHelper.getInstance().sendMessage("/start", dialog_id, null, null, false,
                                null, null, null);
                    }
                } else {
                    builder = new AlertDialog.Builder(getParentActivity());
                    builder.setMessage(LocaleController.getString("AreYouSureUnblockContact",
                            kr.wdream.storyshop.R.string.AreYouSureUnblockContact));
                    builder.setPositiveButton(LocaleController.getString("OK", kr.wdream.storyshop.R.string.OK),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    MessagesController.getInstance().unblockUser(currentUser.id);
                                }
                            });
                }
            } else if (currentUser != null && currentUser.bot && botUser != null) {
                if (botUser.length() != 0) {
                    MessagesController.getInstance().sendBotStart(currentUser, botUser);
                } else {
                    SendMessagesHelper.getInstance().sendMessage("/start", dialog_id, null, null, false, null,
                            null, null);
                }
                botUser = null;
                updateBottomOverlay();
            } else {
                if (ChatObject.isChannel(currentChat) && !(currentChat instanceof TLRPC.TL_channelForbidden)) {
                    if (ChatObject.isNotInChat(currentChat)) {
                        MessagesController.getInstance().addUserToChat(currentChat.id,
                                UserConfig.getCurrentUser(), null, 0, null, null);
                    } else {
                        toggleMute(true);
                    }
                } else {
                    builder = new AlertDialog.Builder(getParentActivity());
                    builder.setMessage(LocaleController.getString("AreYouSureDeleteThisChat",
                            kr.wdream.storyshop.R.string.AreYouSureDeleteThisChat));
                    builder.setPositiveButton(LocaleController.getString("OK", kr.wdream.storyshop.R.string.OK),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    MessagesController.getInstance().deleteDialog(dialog_id, 0);
                                    finishFragment();
                                }
                            });
                }
            }
            if (builder != null) {
                builder.setTitle(LocaleController.getString("AppName", kr.wdream.storyshop.R.string.AppName));
                builder.setNegativeButton(
                        LocaleController.getString("Cancel", kr.wdream.storyshop.R.string.Cancel), null);
                showDialog(builder.create());
            }
        }
    });

    bottomOverlayChatText = new TextView(context);
    bottomOverlayChatText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
    bottomOverlayChatText.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    bottomOverlayChatText.setTextColor(Theme.CHAT_BOTTOM_CHAT_OVERLAY_TEXT_COLOR);
    bottomOverlayChat.addView(bottomOverlayChatText,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));

    chatAdapter.updateRows();
    if (loading && messages.isEmpty()) {
        progressView.setVisibility(chatAdapter.botInfoRow == -1 ? View.VISIBLE : View.INVISIBLE);
        chatListView.setEmptyView(null);
    } else {
        progressView.setVisibility(View.INVISIBLE);
        chatListView.setEmptyView(emptyViewContainer);
    }

    chatActivityEnterView.setButtons(userBlocked ? null : botButtons);

    if (!AndroidUtilities.isTablet() || AndroidUtilities.isSmallTablet()) {
        contentView.addView(playerView = new PlayerView(context, this), LayoutHelper
                .createFrame(LayoutHelper.MATCH_PARENT, 39, Gravity.TOP | Gravity.LEFT, 0, -36, 0, 0));
    }

    updateContactStatus();
    updateBottomOverlay();
    updateSecretStatus();
    updateSpamView();
    updatePinnedMessageView(true);

    try {
        if (currentEncryptedChat != null && Build.VERSION.SDK_INT >= 23) {
            getParentActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE,
                    WindowManager.LayoutParams.FLAG_SECURE);
        }
    } catch (Throwable e) {
        FileLog.e("tmessages", e);
    }
    fixLayoutInternal();

    contentView.addView(actionBar);

    return fragmentView;
}

From source file:com.android.mail.compose.ComposeActivity.java

private void showErrorToast(String message) {
    Toast t = Toast.makeText(this, message, Toast.LENGTH_LONG);
    t.setText(message);//from www  . j a  va 2 s .  com
    t.setGravity(Gravity.CENTER_HORIZONTAL, 0,
            getResources().getDimensionPixelSize(R.dimen.attachment_toast_yoffset));
    t.show();
}

From source file:net.bluehack.ui.PhotoViewer.java

public void setParentActivity(final Activity activity) {
    if (parentActivity == activity) {
        return;/*ww w . j  a  va  2 s .  c  o  m*/
    }
    parentActivity = activity;
    actvityContext = new ContextThemeWrapper(parentActivity, R.style.Theme_TMessages);

    if (progressDrawables == null) {
        progressDrawables = new Drawable[4];
        progressDrawables[0] = parentActivity.getResources().getDrawable(R.drawable.circle_big);
        progressDrawables[1] = parentActivity.getResources().getDrawable(R.drawable.cancel_big);
        progressDrawables[2] = parentActivity.getResources().getDrawable(R.drawable.load_big);
        progressDrawables[3] = parentActivity.getResources().getDrawable(R.drawable.play_big);
    }

    scroller = new Scroller(activity);

    windowView = new FrameLayout(activity) {

        private Runnable attachRunnable;

        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            return isVisible && super.onInterceptTouchEvent(ev);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            return isVisible && PhotoViewer.this.onTouchEvent(event);
        }

        @Override
        protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
            boolean result = super.drawChild(canvas, child, drawingTime);
            if (Build.VERSION.SDK_INT >= 21 && child == animatingImageView && lastInsets != null) {
                WindowInsets insets = (WindowInsets) lastInsets;
                canvas.drawRect(0, getMeasuredHeight(), getMeasuredWidth(),
                        getMeasuredHeight() + insets.getSystemWindowInsetBottom(), blackPaint);
            }
            return result;
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int widthSize = MeasureSpec.getSize(widthMeasureSpec);
            int heightSize = MeasureSpec.getSize(heightMeasureSpec);
            if (Build.VERSION.SDK_INT >= 21 && lastInsets != null) {
                WindowInsets insets = (WindowInsets) lastInsets;
                if (AndroidUtilities.incorrectDisplaySizeFix) {
                    if (heightSize > AndroidUtilities.displaySize.y) {
                        heightSize = AndroidUtilities.displaySize.y;
                    }
                    heightSize += AndroidUtilities.statusBarHeight;
                }
                heightSize -= insets.getSystemWindowInsetBottom();
                widthSize -= insets.getSystemWindowInsetRight();
            } else {
                if (heightSize > AndroidUtilities.displaySize.y) {
                    heightSize = AndroidUtilities.displaySize.y;
                }
            }
            setMeasuredDimension(widthSize, heightSize);
            ViewGroup.LayoutParams layoutParams = animatingImageView.getLayoutParams();
            animatingImageView.measure(MeasureSpec.makeMeasureSpec(layoutParams.width, MeasureSpec.AT_MOST),
                    MeasureSpec.makeMeasureSpec(layoutParams.height, MeasureSpec.AT_MOST));
            containerView.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY),
                    MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY));
        }

        @SuppressWarnings("DrawAllocation")
        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            animatingImageView.layout(0, 0, animatingImageView.getMeasuredWidth(),
                    animatingImageView.getMeasuredHeight());
            containerView.layout(0, 0, containerView.getMeasuredWidth(), containerView.getMeasuredHeight());
            wasLayout = true;
            if (changed) {
                if (!dontResetZoomOnFirstLayout) {
                    scale = 1;
                    translationX = 0;
                    translationY = 0;
                    updateMinMax(scale);
                }

                if (checkImageView != null) {
                    checkImageView.post(new Runnable() {
                        @Override
                        public void run() {
                            FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) checkImageView
                                    .getLayoutParams();
                            WindowManager manager = (WindowManager) ApplicationLoader.applicationContext
                                    .getSystemService(Activity.WINDOW_SERVICE);
                            int rotation = manager.getDefaultDisplay().getRotation();
                            layoutParams.topMargin = AndroidUtilities
                                    .dp(rotation == Surface.ROTATION_270 || rotation == Surface.ROTATION_90 ? 58
                                            : 68)
                                    + (Build.VERSION.SDK_INT >= 21 ? AndroidUtilities.statusBarHeight : 0);
                            checkImageView.setLayoutParams(layoutParams);
                        }
                    });
                }
            }
            if (dontResetZoomOnFirstLayout) {
                setScaleToFill();
                dontResetZoomOnFirstLayout = false;
            }
        }

        @Override
        protected void onAttachedToWindow() {
            super.onAttachedToWindow();
            attachedToWindow = true;
        }

        @Override
        protected void onDetachedFromWindow() {
            super.onDetachedFromWindow();
            attachedToWindow = false;
            wasLayout = false;
        }

        @Override
        public boolean dispatchKeyEventPreIme(KeyEvent event) {
            if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_BACK
                    && event.getAction() == KeyEvent.ACTION_UP) {
                if (captionEditText.isPopupShowing() || captionEditText.isKeyboardVisible()) {
                    closeCaptionEnter(false);
                    return false;
                }
                PhotoViewer.getInstance().closePhoto(true, false);
                return true;
            }
            return super.dispatchKeyEventPreIme(event);
        }

        @Override
        public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback, int type) {
            if (Build.VERSION.SDK_INT >= 23) {
                View view = parentActivity.findViewById(android.R.id.content);
                if (view instanceof ViewGroup) {
                    try {
                        return ((ViewGroup) view).startActionModeForChild(originalView, callback, type);
                    } catch (Throwable e) {
                        FileLog.e("tmessages", e);
                    }
                }
            }
            return super.startActionModeForChild(originalView, callback, type);
        }
    };
    windowView.setBackgroundDrawable(backgroundDrawable);
    windowView.setClipChildren(true);
    windowView.setFocusable(false);

    animatingImageView = new ClippingImageView(activity);
    animatingImageView.setAnimationValues(animationValues);
    windowView.addView(animatingImageView, LayoutHelper.createFrame(40, 40));

    containerView = new FrameLayoutDrawer(activity);
    containerView.setFocusable(false);
    windowView.addView(containerView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));
    if (Build.VERSION.SDK_INT >= 21) {
        //containerView.setFitsSystemWindows(true);
        containerView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
            @SuppressLint("NewApi")
            @Override
            public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
                lastInsets = insets;
                windowView.requestLayout();
                return insets.consumeSystemWindowInsets();
            }
        });
        //containerView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);*/
    }

    windowLayoutParams = new WindowManager.LayoutParams();
    windowLayoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
    windowLayoutParams.format = PixelFormat.TRANSLUCENT;
    windowLayoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
    windowLayoutParams.gravity = Gravity.TOP | Gravity.LEFT;
    windowLayoutParams.type = WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
    if (Build.VERSION.SDK_INT >= 21) {
        windowLayoutParams.flags = WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
                | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR
                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
    } else {
        windowLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
    }

    actionBar = new ActionBar(activity);
    actionBar.setBackgroundColor(Theme.ACTION_BAR_PHOTO_VIEWER_COLOR);
    actionBar.setOccupyStatusBar(Build.VERSION.SDK_INT >= 21);
    actionBar.setItemsBackgroundColor(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR);
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setTitle(LocaleController.formatString("Of", R.string.Of, 1, 1));
    containerView.addView(actionBar,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                if (needCaptionLayout
                        && (captionEditText.isPopupShowing() || captionEditText.isKeyboardVisible())) {
                    closeCaptionEnter(false);
                    return;
                }
                closePhoto(true, false);
            } else if (id == gallery_menu_save) {
                if (Build.VERSION.SDK_INT >= 23 && parentActivity.checkSelfPermission(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    parentActivity
                            .requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 4);
                    return;
                }

                File f = null;
                if (currentMessageObject != null) {
                    f = FileLoader.getPathToMessage(currentMessageObject.messageOwner);
                } else if (currentFileLocation != null) {
                    f = FileLoader.getPathToAttach(currentFileLocation, avatarsDialogId != 0);
                }

                if (f != null && f.exists()) {
                    MediaController.saveFile(f.toString(), parentActivity,
                            currentMessageObject != null && currentMessageObject.isVideo() ? 1 : 0, null, null);
                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
                    builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                    builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
                    builder.setMessage(LocaleController.getString("PleaseDownload", R.string.PleaseDownload));
                    showAlertDialog(builder);
                }
            } else if (id == gallery_menu_showall) {
                if (opennedFromMedia) {
                    closePhoto(true, false);
                } else if (currentDialogId != 0) {
                    disableShowCheck = true;
                    Bundle args2 = new Bundle();
                    args2.putLong("dialog_id", currentDialogId);
                    MediaActivity mediaActivity = new MediaActivity(args2);
                    if (parentChatActivity != null) {
                        mediaActivity.setChatInfo(parentChatActivity.getCurrentChatInfo());
                    }
                    closePhoto(false, false);
                    ((LaunchActivity) parentActivity).presentFragment(mediaActivity, false, true);
                }
            } else if (id == gallery_menu_send) {
                /*Intent intent = new Intent(this, MessagesActivity.class);
                intent.putExtra("onlySelect", true);
                startActivityForResult(intent, 10);
                if (requestCode == 10) {
                int chatId = data.getIntExtra("chatId", 0);
                int userId = data.getIntExtra("userId", 0);
                int dialog_id = 0;
                if (chatId != 0) {
                    dialog_id = -chatId;
                } else if (userId != 0) {
                    dialog_id = userId;
                }
                TLRPC.FileLocation location = getCurrentFile();
                if (dialog_id != 0 && location != null) {
                    Intent intent = new Intent(GalleryImageViewer.this, ChatActivity.class);
                    if (chatId != 0) {
                        intent.putExtra("chatId", chatId);
                    } else {
                        intent.putExtra("userId", userId);
                    }
                    startActivity(intent);
                    NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats);
                    finish();
                    if (withoutBottom) {
                        MessagesController.getInstance().sendMessage(location, dialog_id);
                    } else {
                        int item = mViewPager.getCurrentItem();
                        MessageObject obj = localPagerAdapter.imagesArr.get(item);
                        MessagesController.getInstance().sendMessage(obj, dialog_id);
                    }
                }
                }*/
            } else if (id == gallery_menu_delete) {
                if (parentActivity == null) {
                    return;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
                if (currentMessageObject != null && currentMessageObject.isVideo()) {
                    builder.setMessage(LocaleController.formatString("AreYouSureDeleteVideo",
                            R.string.AreYouSureDeleteVideo));
                } else if (currentMessageObject != null && currentMessageObject.isGif()) {
                    builder.setMessage(LocaleController.formatString("AreYouSure", R.string.AreYouSure));
                } else {
                    builder.setMessage(LocaleController.formatString("AreYouSureDeletePhoto",
                            R.string.AreYouSureDeletePhoto));
                }
                builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                builder.setPositiveButton(LocaleController.getString("OK", R.string.OK),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                if (!imagesArr.isEmpty()) {
                                    if (currentIndex < 0 || currentIndex >= imagesArr.size()) {
                                        return;
                                    }
                                    MessageObject obj = imagesArr.get(currentIndex);
                                    if (obj.isSent()) {
                                        closePhoto(false, false);
                                        ArrayList<Integer> arr = new ArrayList<>();
                                        arr.add(obj.getId());

                                        ArrayList<Long> random_ids = null;
                                        TLRPC.EncryptedChat encryptedChat = null;
                                        if ((int) obj.getDialogId() == 0 && obj.messageOwner.random_id != 0) {
                                            random_ids = new ArrayList<>();
                                            random_ids.add(obj.messageOwner.random_id);
                                            encryptedChat = MessagesController.getInstance()
                                                    .getEncryptedChat((int) (obj.getDialogId() >> 32));
                                        }

                                        MessagesController.getInstance().deleteMessages(arr, random_ids,
                                                encryptedChat, obj.messageOwner.to_id.channel_id);
                                    }
                                } else if (!avatarsArr.isEmpty()) {
                                    if (currentIndex < 0 || currentIndex >= avatarsArr.size()) {
                                        return;
                                    }
                                    TLRPC.Photo photo = avatarsArr.get(currentIndex);
                                    TLRPC.FileLocation currentLocation = imagesArrLocations.get(currentIndex);
                                    if (photo instanceof TLRPC.TL_photoEmpty) {
                                        photo = null;
                                    }
                                    boolean current = false;
                                    if (currentUserAvatarLocation != null) {
                                        if (photo != null) {
                                            for (TLRPC.PhotoSize size : photo.sizes) {
                                                if (size.location.local_id == currentUserAvatarLocation.local_id
                                                        && size.location.volume_id == currentUserAvatarLocation.volume_id) {
                                                    current = true;
                                                    break;
                                                }
                                            }
                                        } else if (currentLocation.local_id == currentUserAvatarLocation.local_id
                                                && currentLocation.volume_id == currentUserAvatarLocation.volume_id) {
                                            current = true;
                                        }
                                    }
                                    if (current) {
                                        MessagesController.getInstance().deleteUserPhoto(null);
                                        closePhoto(false, false);
                                    } else if (photo != null) {
                                        TLRPC.TL_inputPhoto inputPhoto = new TLRPC.TL_inputPhoto();
                                        inputPhoto.id = photo.id;
                                        inputPhoto.access_hash = photo.access_hash;
                                        MessagesController.getInstance().deleteUserPhoto(inputPhoto);
                                        MessagesStorage.getInstance().clearUserPhoto(avatarsDialogId, photo.id);
                                        imagesArrLocations.remove(currentIndex);
                                        imagesArrLocationsSizes.remove(currentIndex);
                                        avatarsArr.remove(currentIndex);
                                        if (imagesArrLocations.isEmpty()) {
                                            closePhoto(false, false);
                                        } else {
                                            int index = currentIndex;
                                            if (index >= avatarsArr.size()) {
                                                index = avatarsArr.size() - 1;
                                            }
                                            currentIndex = -1;
                                            setImageIndex(index, true);
                                        }
                                    }
                                }
                            }
                        });
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                showAlertDialog(builder);
            } else if (id == gallery_menu_caption_done) {
                closeCaptionEnter(true);
            } else if (id == gallery_menu_share) {
                onSharePressed();
            } else if (id == gallery_menu_openin) {
                try {
                    AndroidUtilities.openForView(currentMessageObject, parentActivity);
                    closePhoto(false, false);
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
            } else if (id == gallery_menu_mute) {
                muteVideo = !muteVideo;
                if (videoPlayer != null) {
                    videoPlayer.setMute(muteVideo);
                }
                if (muteVideo) {
                    actionBar.setTitle(LocaleController.getString("AttachGif", R.string.AttachGif));
                    muteItem.setIcon(R.drawable.volume_off);
                } else {
                    actionBar.setTitle(LocaleController.getString("AttachVideo", R.string.AttachVideo));
                    muteItem.setIcon(R.drawable.volume_on);
                }
            } else if (id == gallery_menu_masks) {
                if (parentActivity == null || currentMessageObject == null
                        || currentMessageObject.messageOwner.media == null
                        || currentMessageObject.messageOwner.media.photo == null) {
                    return;
                }
                StickersAlert stickersAlert = new StickersAlert(parentActivity,
                        currentMessageObject.messageOwner.media.photo);
                stickersAlert.show();
            }
        }

        @Override
        public boolean canOpenMenu() {
            if (currentMessageObject != null) {
                File f = FileLoader.getPathToMessage(currentMessageObject.messageOwner);
                if (f.exists()) {
                    return true;
                }
            } else if (currentFileLocation != null) {
                File f = FileLoader.getPathToAttach(currentFileLocation, avatarsDialogId != 0);
                if (f.exists()) {
                    return true;
                }
            }
            return false;
        }
    });

    ActionBarMenu menu = actionBar.createMenu();

    masksItem = menu.addItem(gallery_menu_masks, R.drawable.ic_masks_msk1);
    muteItem = menu.addItem(gallery_menu_mute, R.drawable.volume_on);

    menuItem = menu.addItem(0, R.drawable.ic_ab_other);
    menuItem.addSubItem(gallery_menu_openin,
            LocaleController.getString("OpenInExternalApp", R.string.OpenInExternalApp), 0);
    menuItem.addSubItem(gallery_menu_showall, LocaleController.getString("ShowAllMedia", R.string.ShowAllMedia),
            0);
    menuItem.addSubItem(gallery_menu_share, LocaleController.getString("ShareFile", R.string.ShareFile), 0);
    menuItem.addSubItem(gallery_menu_save, LocaleController.getString("SaveToGallery", R.string.SaveToGallery),
            0);
    menuItem.addSubItem(gallery_menu_delete, LocaleController.getString("Delete", R.string.Delete), 0);

    captionDoneItem = menu.addItemWithWidth(gallery_menu_caption_done, R.drawable.ic_done,
            AndroidUtilities.dp(56));

    bottomLayout = new FrameLayout(actvityContext);
    bottomLayout.setBackgroundColor(0x7f000000);
    containerView.addView(bottomLayout,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.BOTTOM | Gravity.LEFT));

    captionTextViewOld = new TextView(actvityContext);
    captionTextViewOld.setMaxLines(10);
    captionTextViewOld.setBackgroundColor(0x7f000000);
    captionTextViewOld.setPadding(AndroidUtilities.dp(20), AndroidUtilities.dp(8), AndroidUtilities.dp(20),
            AndroidUtilities.dp(8));
    captionTextViewOld.setLinkTextColor(0xffffffff);
    captionTextViewOld.setTextColor(0xffffffff);
    captionTextViewOld.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
    captionTextViewOld.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
    captionTextViewOld.setVisibility(View.INVISIBLE);
    containerView.addView(captionTextViewOld, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 0, 0, 0, 48));
    captionTextViewOld.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (cropItem.getVisibility() == View.VISIBLE) {
                openCaptionEnter();
            }
        }
    });

    captionTextView = captionTextViewNew = new TextView(actvityContext);
    captionTextViewNew.setMaxLines(10);
    captionTextViewNew.setBackgroundColor(0x7f000000);
    captionTextViewNew.setPadding(AndroidUtilities.dp(20), AndroidUtilities.dp(8), AndroidUtilities.dp(20),
            AndroidUtilities.dp(8));
    captionTextViewNew.setLinkTextColor(0xffffffff);
    captionTextViewNew.setTextColor(0xffffffff);
    captionTextViewNew.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
    captionTextViewNew.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
    captionTextViewNew.setVisibility(View.INVISIBLE);
    containerView.addView(captionTextViewNew, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 0, 0, 0, 48));
    captionTextViewNew.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (cropItem.getVisibility() == View.VISIBLE) {
                openCaptionEnter();
            }
        }
    });

    radialProgressViews[0] = new RadialProgressView(containerView.getContext(), containerView);
    radialProgressViews[0].setBackgroundState(0, false);
    radialProgressViews[1] = new RadialProgressView(containerView.getContext(), containerView);
    radialProgressViews[1].setBackgroundState(0, false);
    radialProgressViews[2] = new RadialProgressView(containerView.getContext(), containerView);
    radialProgressViews[2].setBackgroundState(0, false);

    shareButton = new ImageView(containerView.getContext());
    shareButton.setImageResource(R.drawable.share);
    shareButton.setScaleType(ImageView.ScaleType.CENTER);
    shareButton.setBackgroundDrawable(Theme.createBarSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    bottomLayout.addView(shareButton,
            LayoutHelper.createFrame(50, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.RIGHT));
    shareButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onSharePressed();
        }
    });

    nameTextView = new TextView(containerView.getContext());
    nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    nameTextView.setSingleLine(true);
    nameTextView.setMaxLines(1);
    nameTextView.setEllipsize(TextUtils.TruncateAt.END);
    nameTextView.setTextColor(0xffffffff);
    nameTextView.setGravity(Gravity.LEFT);
    bottomLayout.addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 16, 5, 60, 0));

    dateTextView = new TextView(containerView.getContext());
    dateTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
    dateTextView.setSingleLine(true);
    dateTextView.setMaxLines(1);
    dateTextView.setEllipsize(TextUtils.TruncateAt.END);
    dateTextView.setTextColor(0xffffffff);
    dateTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    dateTextView.setGravity(Gravity.LEFT);
    bottomLayout.addView(dateTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 16, 25, 50, 0));

    if (Build.VERSION.SDK_INT >= 16) {
        videoPlayerSeekbar = new SeekBar(containerView.getContext());
        videoPlayerSeekbar.setColors(0x66ffffff, 0xffffffff, 0xffffffff);
        videoPlayerSeekbar.setDelegate(new SeekBar.SeekBarDelegate() {
            @Override
            public void onSeekBarDrag(float progress) {
                if (videoPlayer != null) {
                    videoPlayer.getPlayerControl().seekTo((int) (progress * videoPlayer.getDuration()));
                }
            }
        });

        videoPlayerControlFrameLayout = new FrameLayout(containerView.getContext()) {

            @Override
            public boolean onTouchEvent(MotionEvent event) {
                int x = (int) event.getX();
                int y = (int) event.getY();
                if (videoPlayerSeekbar.onTouch(event.getAction(), event.getX() - AndroidUtilities.dp(48),
                        event.getY())) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                    invalidate();
                    return true;
                }
                return super.onTouchEvent(event);
            }

            @Override
            protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
                long duration;
                if (videoPlayer != null) {
                    duration = videoPlayer.getDuration();
                    if (duration == ExoPlayer.UNKNOWN_TIME) {
                        duration = 0;
                    }
                } else {
                    duration = 0;
                }
                duration /= 1000;
                int size = (int) Math
                        .ceil(videoPlayerTime.getPaint().measureText(String.format("%02d:%02d / %02d:%02d",
                                duration / 60, duration % 60, duration / 60, duration % 60)));
                videoPlayerSeekbar.setSize(getMeasuredWidth() - AndroidUtilities.dp(48 + 16) - size,
                        getMeasuredHeight());
            }

            @Override
            protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
                super.onLayout(changed, left, top, right, bottom);
                float progress = 0;
                if (videoPlayer != null) {
                    PlayerControl playerControl = videoPlayer.getPlayerControl();
                    progress = playerControl.getCurrentPosition() / (float) playerControl.getDuration();
                }
                videoPlayerSeekbar.setProgress(progress);
            }

            @Override
            protected void onDraw(Canvas canvas) {
                canvas.save();
                canvas.translate(AndroidUtilities.dp(48), 0);
                videoPlayerSeekbar.draw(canvas);
                canvas.restore();
            }
        };
        videoPlayerControlFrameLayout.setWillNotDraw(false);
        bottomLayout.addView(videoPlayerControlFrameLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
                LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));

        videoPlayButton = new ImageView(containerView.getContext());
        videoPlayButton.setScaleType(ImageView.ScaleType.CENTER);
        videoPlayerControlFrameLayout.addView(videoPlayButton,
                LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.TOP));
        videoPlayButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (videoPlayer != null) {
                    if (isPlaying) {
                        videoPlayer.getPlayerControl().pause();
                    } else {
                        videoPlayer.getPlayerControl().start();
                    }
                }
            }
        });

        videoPlayerTime = new TextView(containerView.getContext());
        videoPlayerTime.setTextColor(0xffffffff);
        videoPlayerTime.setGravity(Gravity.CENTER_VERTICAL);
        videoPlayerTime.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
        videoPlayerControlFrameLayout.addView(videoPlayerTime, LayoutHelper.createFrame(
                LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.RIGHT | Gravity.TOP, 0, 0, 8, 0));
    }

    pickerView = new PickerBottomLayoutViewer(actvityContext);
    pickerView.setBackgroundColor(0x7f000000);
    containerView.addView(pickerView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.BOTTOM | Gravity.LEFT));
    pickerView.cancelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (placeProvider instanceof EmptyPhotoViewerProvider) {
                closePhoto(false, false);
            } else if (placeProvider != null) {
                closePhoto(!placeProvider.cancelButtonPressed(), false);
            }
        }
    });
    pickerView.doneButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (placeProvider != null) {
                placeProvider.sendButtonPressed(currentIndex);
                closePhoto(false, false);
            }
        }
    });

    LinearLayout itemsLayout = new LinearLayout(parentActivity);
    itemsLayout.setOrientation(LinearLayout.HORIZONTAL);
    pickerView.addView(itemsLayout,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 48, Gravity.TOP | Gravity.CENTER_HORIZONTAL));

    tuneItem = new ImageView(parentActivity);
    tuneItem.setScaleType(ImageView.ScaleType.CENTER);
    tuneItem.setImageResource(R.drawable.photo_tools);
    tuneItem.setBackgroundDrawable(Theme.createBarSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    itemsLayout.addView(tuneItem, LayoutHelper.createLinear(56, 48));
    tuneItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switchToEditMode(2);
        }
    });

    paintItem = new ImageView(parentActivity);
    paintItem.setScaleType(ImageView.ScaleType.CENTER);
    paintItem.setImageResource(R.drawable.photo_paint);
    paintItem.setBackgroundDrawable(Theme.createBarSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    itemsLayout.addView(paintItem, LayoutHelper.createLinear(56, 48));
    paintItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switchToEditMode(3);
        }
    });

    cropItem = new ImageView(parentActivity);
    cropItem.setScaleType(ImageView.ScaleType.CENTER);
    cropItem.setImageResource(R.drawable.photo_crop);
    cropItem.setBackgroundDrawable(Theme.createBarSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    itemsLayout.addView(cropItem, LayoutHelper.createLinear(56, 48));
    cropItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switchToEditMode(1);
        }
    });

    editorDoneLayout = new PickerBottomLayoutViewer(actvityContext);
    editorDoneLayout.setBackgroundColor(0x7f000000);
    editorDoneLayout.updateSelectedCount(0, false);
    editorDoneLayout.setVisibility(View.GONE);
    containerView.addView(editorDoneLayout,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.BOTTOM));
    editorDoneLayout.cancelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (currentEditMode == 1) {
                photoCropView.cancelAnimationRunnable();
            }
            switchToEditMode(0);
        }
    });
    editorDoneLayout.doneButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (currentEditMode == 1) {
                photoCropView.cancelAnimationRunnable();
                if (imageMoveAnimation != null) {
                    return;
                }
            }
            applyCurrentEditMode();
            switchToEditMode(0);
        }
    });

    ImageView rotateButton = new ImageView(actvityContext);
    rotateButton.setScaleType(ImageView.ScaleType.CENTER);
    rotateButton.setImageResource(R.drawable.tool_rotate);
    rotateButton.setBackgroundDrawable(Theme.createBarSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    editorDoneLayout.addView(rotateButton, LayoutHelper.createFrame(48, 48, Gravity.CENTER));
    rotateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            centerImage.setOrientation(centerImage.getOrientation() - 90, false);
            photoCropView.setOrientation(centerImage.getOrientation());
            containerView.invalidate();
        }
    });

    gestureDetector = new GestureDetector(containerView.getContext(), this);
    gestureDetector.setOnDoubleTapListener(this);

    ImageReceiver.ImageReceiverDelegate imageReceiverDelegate = new ImageReceiver.ImageReceiverDelegate() {
        @Override
        public void didSetImage(ImageReceiver imageReceiver, boolean set, boolean thumb) {
            if (imageReceiver == centerImage && set && placeProvider != null && placeProvider.scaleToFill()) {
                if (!wasLayout) {
                    dontResetZoomOnFirstLayout = true;
                } else {
                    setScaleToFill();
                }
            }
        }
    };

    centerImage.setParentView(containerView);
    centerImage.setCrossfadeAlpha((byte) 2);
    centerImage.setInvalidateAll(true);
    centerImage.setDelegate(imageReceiverDelegate);
    leftImage.setParentView(containerView);
    leftImage.setCrossfadeAlpha((byte) 2);
    leftImage.setInvalidateAll(true);
    leftImage.setDelegate(imageReceiverDelegate);
    rightImage.setParentView(containerView);
    rightImage.setCrossfadeAlpha((byte) 2);
    rightImage.setInvalidateAll(true);
    rightImage.setDelegate(imageReceiverDelegate);

    WindowManager manager = (WindowManager) ApplicationLoader.applicationContext
            .getSystemService(Activity.WINDOW_SERVICE);
    int rotation = manager.getDefaultDisplay().getRotation();

    checkImageView = new CheckBox(containerView.getContext(), R.drawable.selectphoto_large);
    checkImageView.setDrawBackground(true);
    checkImageView.setSize(45);
    checkImageView.setCheckOffset(AndroidUtilities.dp(1));
    checkImageView.setColor(0xff3ccaef);
    checkImageView.setVisibility(View.GONE);
    containerView.addView(checkImageView, LayoutHelper.createFrame(45, 45, Gravity.RIGHT | Gravity.TOP, 0,
            rotation == Surface.ROTATION_270 || rotation == Surface.ROTATION_90 ? 58 : 68, 10, 0));
    if (Build.VERSION.SDK_INT >= 21) {
        ((FrameLayout.LayoutParams) checkImageView
                .getLayoutParams()).topMargin += AndroidUtilities.statusBarHeight;
    }
    checkImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (placeProvider != null) {
                placeProvider.setPhotoChecked(currentIndex);
                checkImageView.setChecked(placeProvider.isPhotoChecked(currentIndex), true);
                updateSelectedCount();
            }
        }
    });

    captionEditText = new PhotoViewerCaptionEnterView(actvityContext, containerView, windowView);
    captionEditText.setDelegate(new PhotoViewerCaptionEnterView.PhotoViewerCaptionEnterViewDelegate() {
        @Override
        public void onCaptionEnter() {
            closeCaptionEnter(true);
        }

        @Override
        public void onTextChanged(CharSequence text) {
            if (mentionsAdapter != null && captionEditText != null && parentChatActivity != null
                    && text != null) {
                mentionsAdapter.searchUsernameOrHashtag(text.toString(), captionEditText.getCursorPosition(),
                        parentChatActivity.messages);
            }
        }

        @Override
        public void onWindowSizeChanged(int size) {
            int height = AndroidUtilities.dp(36 * Math.min(3, mentionsAdapter.getItemCount())
                    + (mentionsAdapter.getItemCount() > 3 ? 18 : 0));
            if (size - ActionBar.getCurrentActionBarHeight() * 2 < height) {
                allowMentions = false;
                if (mentionListView != null && mentionListView.getVisibility() == View.VISIBLE) {
                    mentionListView.setVisibility(View.INVISIBLE);
                }
            } else {
                allowMentions = true;
                if (mentionListView != null && mentionListView.getVisibility() == View.INVISIBLE) {
                    mentionListView.setVisibility(View.VISIBLE);
                }
            }
        }
    });
    containerView.addView(captionEditText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 0, 0, 0, -400));

    mentionListView = new RecyclerListView(actvityContext);
    mentionListView.setTag(5);
    mentionLayoutManager = new LinearLayoutManager(actvityContext) {
        @Override
        public boolean supportsPredictiveItemAnimations() {
            return false;
        }
    };
    mentionLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    mentionListView.setLayoutManager(mentionLayoutManager);
    mentionListView.setBackgroundColor(0x7f000000);
    mentionListView.setVisibility(View.GONE);
    mentionListView.setClipToPadding(true);
    mentionListView.setOverScrollMode(ListView.OVER_SCROLL_NEVER);
    containerView.addView(mentionListView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 110, Gravity.LEFT | Gravity.BOTTOM));

    mentionListView.setAdapter(mentionsAdapter = new MentionsAdapter(actvityContext, true, 0,
            new MentionsAdapter.MentionsAdapterDelegate() {
                @Override
                public void needChangePanelVisibility(boolean show) {
                    if (show) {
                        FrameLayout.LayoutParams layoutParams3 = (FrameLayout.LayoutParams) mentionListView
                                .getLayoutParams();
                        int height = 36 * Math.min(3, mentionsAdapter.getItemCount())
                                + (mentionsAdapter.getItemCount() > 3 ? 18 : 0);
                        layoutParams3.height = AndroidUtilities.dp(height);
                        layoutParams3.topMargin = -AndroidUtilities.dp(height);
                        mentionListView.setLayoutParams(layoutParams3);

                        if (mentionListAnimation != null) {
                            mentionListAnimation.cancel();
                            mentionListAnimation = null;
                        }

                        if (mentionListView.getVisibility() == View.VISIBLE) {
                            mentionListView.setAlpha(1.0f);
                            return;
                        } else {
                            mentionLayoutManager.scrollToPositionWithOffset(0, 10000);
                        }
                        if (allowMentions) {
                            mentionListView.setVisibility(View.VISIBLE);
                            mentionListAnimation = new AnimatorSet();
                            mentionListAnimation
                                    .playTogether(ObjectAnimator.ofFloat(mentionListView, "alpha", 0.0f, 1.0f));
                            mentionListAnimation.addListener(new AnimatorListenerAdapterProxy() {
                                @Override
                                public void onAnimationEnd(Animator animation) {
                                    if (mentionListAnimation != null
                                            && mentionListAnimation.equals(animation)) {
                                        mentionListAnimation = null;
                                    }
                                }
                            });
                            mentionListAnimation.setDuration(200);
                            mentionListAnimation.start();
                        } else {
                            mentionListView.setAlpha(1.0f);
                            mentionListView.setVisibility(View.INVISIBLE);
                        }
                    } else {
                        if (mentionListAnimation != null) {
                            mentionListAnimation.cancel();
                            mentionListAnimation = null;
                        }

                        if (mentionListView.getVisibility() == View.GONE) {
                            return;
                        }
                        if (allowMentions) {
                            mentionListAnimation = new AnimatorSet();
                            mentionListAnimation
                                    .playTogether(ObjectAnimator.ofFloat(mentionListView, "alpha", 0.0f));
                            mentionListAnimation.addListener(new AnimatorListenerAdapterProxy() {
                                @Override
                                public void onAnimationEnd(Animator animation) {
                                    if (mentionListAnimation != null
                                            && mentionListAnimation.equals(animation)) {
                                        mentionListView.setVisibility(View.GONE);
                                        mentionListAnimation = null;
                                    }
                                }
                            });
                            mentionListAnimation.setDuration(200);
                            mentionListAnimation.start();
                        } else {
                            mentionListView.setVisibility(View.GONE);
                        }
                    }
                }

                @Override
                public void onContextSearch(boolean searching) {

                }

                @Override
                public void onContextClick(TLRPC.BotInlineResult result) {

                }
            }));
    mentionsAdapter.setAllowNewMentions(false);

    mentionListView.setOnItemClickListener(new RecyclerListView.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {
            Object object = mentionsAdapter.getItem(position);
            int start = mentionsAdapter.getResultStartPosition();
            int len = mentionsAdapter.getResultLength();
            if (object instanceof TLRPC.User) {
                TLRPC.User user = (TLRPC.User) object;
                if (user != null) {
                    captionEditText.replaceWithText(start, len, "@" + user.username + " ");
                }
            } else if (object instanceof String) {
                captionEditText.replaceWithText(start, len, object + " ");
            }
        }
    });

    mentionListView.setOnItemLongClickListener(new RecyclerListView.OnItemLongClickListener() {
        @Override
        public boolean onItemClick(View view, int position) {
            Object object = mentionsAdapter.getItem(position);
            if (object instanceof String) {
                AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
                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(),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                mentionsAdapter.clearRecentHashtags();
                            }
                        });
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                showAlertDialog(builder);
                return true;
            }
            return false;
        }
    });
}

From source file:com.albedinsky.android.ui.widget.SeekBarWidget.java

/**
 * Draws discrete indicator of this SeekBarWidget at its current position updated by
 * {@link #updateDiscreteIndicatorPosition(int, int)} according to the current progress.
 *
 * @param canvas Canvas on which to draw discrete indicator's drawable.
 *///from  w  w w . j ava  2s  .co m
private void drawDiscreteIndicator(Canvas canvas) {
    if (mDiscreteIndicatorHeight == 0) {
        return;
    }
    // todo: draw according to LTR/RTL layout direction.
    mDiscreteIndicator.draw(canvas);

    // Draw current progress over indicator's graphics.
    final Rect indicatorBounds = mDiscreteIndicator.getBounds();
    final Paint textPaint = DISCRETE_INDICATOR_TEXT_INFO.paint;
    textPaint.getTextBounds("0", 0, 1, mRect);
    final float textSize = mRect.height();
    final Rect textPadding = DISCRETE_INDICATOR_TEXT_INFO.padding;
    final int absoluteTextGravity = WidgetGravity.getAbsoluteGravity(DISCRETE_INDICATOR_TEXT_INFO.gravity,
            ViewCompat.getLayoutDirection(this));

    final float textX, textY;
    // Resolve horizontal text position according to the requested gravity.
    switch (absoluteTextGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
    case Gravity.CENTER_HORIZONTAL:
        textPaint.setTextAlign(Paint.Align.CENTER);
        textX = indicatorBounds.centerX();
        break;
    case Gravity.RIGHT:
        textPaint.setTextAlign(Paint.Align.RIGHT);
        textX = indicatorBounds.right - textPadding.right;
        break;
    case Gravity.LEFT:
    default:
        textPaint.setTextAlign(Paint.Align.LEFT);
        textX = indicatorBounds.left + textPadding.left;
        break;
    }
    // Resolve vertical text position according to the requested gravity.
    switch (absoluteTextGravity & Gravity.VERTICAL_GRAVITY_MASK) {
    case Gravity.CENTER_VERTICAL:
        textY = indicatorBounds.centerY() + textSize / 2f;
        break;
    case Gravity.BOTTOM:
        textY = indicatorBounds.bottom - textPadding.bottom;
        break;
    case Gravity.TOP:
    default:
        textY = indicatorBounds.top + textSize + textPadding.top;
        break;
    }
    canvas.drawText(Integer.toString(getProgress()), textX, textY, textPaint);
}

From source file:kr.wdream.ui.PhotoViewer.java

public void setParentActivity(final Activity activity) {
    if (parentActivity == activity) {
        return;/*  ww  w .  ja v  a 2s. co  m*/
    }
    parentActivity = activity;
    actvityContext = new ContextThemeWrapper(parentActivity, kr.wdream.storyshop.R.style.Theme_TMessages);

    if (progressDrawables == null) {
        progressDrawables = new Drawable[4];
        progressDrawables[0] = parentActivity.getResources()
                .getDrawable(kr.wdream.storyshop.R.drawable.circle_big);
        progressDrawables[1] = parentActivity.getResources()
                .getDrawable(kr.wdream.storyshop.R.drawable.cancel_big);
        progressDrawables[2] = parentActivity.getResources()
                .getDrawable(kr.wdream.storyshop.R.drawable.load_big);
        progressDrawables[3] = parentActivity.getResources()
                .getDrawable(kr.wdream.storyshop.R.drawable.play_big);
    }

    scroller = new Scroller(activity);

    windowView = new FrameLayout(activity) {

        private Runnable attachRunnable;

        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            return isVisible && super.onInterceptTouchEvent(ev);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            return isVisible && PhotoViewer.this.onTouchEvent(event);
        }

        @Override
        protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
            boolean result = super.drawChild(canvas, child, drawingTime);
            if (Build.VERSION.SDK_INT >= 21 && child == animatingImageView && lastInsets != null) {
                WindowInsets insets = (WindowInsets) lastInsets;
                canvas.drawRect(0, getMeasuredHeight(), getMeasuredWidth(),
                        getMeasuredHeight() + insets.getSystemWindowInsetBottom(), blackPaint);
            }
            return result;
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int widthSize = MeasureSpec.getSize(widthMeasureSpec);
            int heightSize = MeasureSpec.getSize(heightMeasureSpec);
            if (Build.VERSION.SDK_INT >= 21 && lastInsets != null) {
                WindowInsets insets = (WindowInsets) lastInsets;
                if (AndroidUtilities.incorrectDisplaySizeFix) {
                    if (heightSize > AndroidUtilities.displaySize.y) {
                        heightSize = AndroidUtilities.displaySize.y;
                    }
                    heightSize += AndroidUtilities.statusBarHeight;
                }
                heightSize -= insets.getSystemWindowInsetBottom();
                widthSize -= insets.getSystemWindowInsetRight();
            } else {
                if (heightSize > AndroidUtilities.displaySize.y) {
                    heightSize = AndroidUtilities.displaySize.y;
                }
            }
            setMeasuredDimension(widthSize, heightSize);
            ViewGroup.LayoutParams layoutParams = animatingImageView.getLayoutParams();
            animatingImageView.measure(MeasureSpec.makeMeasureSpec(layoutParams.width, MeasureSpec.AT_MOST),
                    MeasureSpec.makeMeasureSpec(layoutParams.height, MeasureSpec.AT_MOST));
            containerView.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY),
                    MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY));
        }

        @SuppressWarnings("DrawAllocation")
        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            animatingImageView.layout(0, 0, animatingImageView.getMeasuredWidth(),
                    animatingImageView.getMeasuredHeight());
            containerView.layout(0, 0, containerView.getMeasuredWidth(), containerView.getMeasuredHeight());
            wasLayout = true;
            if (changed) {
                if (!dontResetZoomOnFirstLayout) {
                    scale = 1;
                    translationX = 0;
                    translationY = 0;
                    updateMinMax(scale);
                }

                if (checkImageView != null) {
                    checkImageView.post(new Runnable() {
                        @Override
                        public void run() {
                            FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) checkImageView
                                    .getLayoutParams();
                            WindowManager manager = (WindowManager) ApplicationLoader.applicationContext
                                    .getSystemService(Activity.WINDOW_SERVICE);
                            int rotation = manager.getDefaultDisplay().getRotation();
                            layoutParams.topMargin = AndroidUtilities
                                    .dp(rotation == Surface.ROTATION_270 || rotation == Surface.ROTATION_90 ? 58
                                            : 68)
                                    + (Build.VERSION.SDK_INT >= 21 ? AndroidUtilities.statusBarHeight : 0);
                            checkImageView.setLayoutParams(layoutParams);
                        }
                    });
                }
            }
            if (dontResetZoomOnFirstLayout) {
                setScaleToFill();
                dontResetZoomOnFirstLayout = false;
            }
        }

        @Override
        protected void onAttachedToWindow() {
            super.onAttachedToWindow();
            attachedToWindow = true;
        }

        @Override
        protected void onDetachedFromWindow() {
            super.onDetachedFromWindow();
            attachedToWindow = false;
            wasLayout = false;
        }

        @Override
        public boolean dispatchKeyEventPreIme(KeyEvent event) {
            if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_BACK
                    && event.getAction() == KeyEvent.ACTION_UP) {
                if (captionEditText.isPopupShowing() || captionEditText.isKeyboardVisible()) {
                    closeCaptionEnter(false);
                    return false;
                }
                PhotoViewer.getInstance().closePhoto(true, false);
                return true;
            }
            return super.dispatchKeyEventPreIme(event);
        }

        @Override
        public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback, int type) {
            if (Build.VERSION.SDK_INT >= 23) {
                View view = parentActivity.findViewById(android.R.id.content);
                if (view instanceof ViewGroup) {
                    try {
                        return ((ViewGroup) view).startActionModeForChild(originalView, callback, type);
                    } catch (Throwable e) {
                        FileLog.e("tmessages", e);
                    }
                }
            }
            return super.startActionModeForChild(originalView, callback, type);
        }
    };
    windowView.setBackgroundDrawable(backgroundDrawable);
    windowView.setClipChildren(true);
    windowView.setFocusable(false);

    animatingImageView = new ClippingImageView(activity);
    animatingImageView.setAnimationValues(animationValues);
    windowView.addView(animatingImageView, LayoutHelper.createFrame(40, 40));

    containerView = new FrameLayoutDrawer(activity);
    containerView.setFocusable(false);
    windowView.addView(containerView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));
    if (Build.VERSION.SDK_INT >= 21) {
        //containerView.setFitsSystemWindows(true);
        containerView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
            @SuppressLint("NewApi")
            @Override
            public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
                lastInsets = insets;
                windowView.requestLayout();
                return insets.consumeSystemWindowInsets();
            }
        });
        //containerView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);*/
    }

    windowLayoutParams = new WindowManager.LayoutParams();
    windowLayoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
    windowLayoutParams.format = PixelFormat.TRANSLUCENT;
    windowLayoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
    windowLayoutParams.gravity = Gravity.TOP | Gravity.LEFT;
    windowLayoutParams.type = WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
    if (Build.VERSION.SDK_INT >= 21) {
        windowLayoutParams.flags = WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
                | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR
                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
    } else {
        windowLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
    }

    actionBar = new ActionBar(activity);
    actionBar.setBackgroundColor(Theme.ACTION_BAR_PHOTO_VIEWER_COLOR);
    actionBar.setOccupyStatusBar(Build.VERSION.SDK_INT >= 21);
    actionBar.setItemsBackgroundColor(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR);
    actionBar.setBackButtonImage(kr.wdream.storyshop.R.drawable.ic_ab_back);
    actionBar.setTitle(LocaleController.formatString("Of", kr.wdream.storyshop.R.string.Of, 1, 1));
    containerView.addView(actionBar,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                if (needCaptionLayout
                        && (captionEditText.isPopupShowing() || captionEditText.isKeyboardVisible())) {
                    closeCaptionEnter(false);
                    return;
                }
                closePhoto(true, false);
            } else if (id == gallery_menu_save) {
                if (Build.VERSION.SDK_INT >= 23 && parentActivity.checkSelfPermission(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    parentActivity
                            .requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 4);
                    return;
                }

                File f = null;
                if (currentMessageObject != null) {
                    f = FileLoader.getPathToMessage(currentMessageObject.messageOwner);
                } else if (currentFileLocation != null) {
                    f = FileLoader.getPathToAttach(currentFileLocation, avatarsDialogId != 0);
                }

                if (f != null && f.exists()) {
                    MediaController.saveFile(f.toString(), parentActivity,
                            currentMessageObject != null && currentMessageObject.isVideo() ? 1 : 0, null, null);
                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
                    builder.setTitle(
                            LocaleController.getString("AppName", kr.wdream.storyshop.R.string.AppName));
                    builder.setPositiveButton(LocaleController.getString("OK", kr.wdream.storyshop.R.string.OK),
                            null);
                    builder.setMessage(LocaleController.getString("PleaseDownload",
                            kr.wdream.storyshop.R.string.PleaseDownload));
                    showAlertDialog(builder);
                }
            } else if (id == gallery_menu_showall) {
                if (opennedFromMedia) {
                    closePhoto(true, false);
                } else if (currentDialogId != 0) {
                    disableShowCheck = true;
                    Bundle args2 = new Bundle();
                    args2.putLong("dialog_id", currentDialogId);
                    MediaActivity mediaActivity = new MediaActivity(args2);
                    if (parentChatActivity != null) {
                        mediaActivity.setChatInfo(parentChatActivity.getCurrentChatInfo());
                    }
                    closePhoto(false, false);
                    ((LaunchActivity) parentActivity).presentFragment(mediaActivity, false, true);
                }
            } else if (id == gallery_menu_send) {
                /*Intent intent = new Intent(this, MessagesActivity.class);
                intent.putExtra("onlySelect", true);
                startActivityForResult(intent, 10);
                if (requestCode == 10) {
                int chatId = data.getIntExtra("chatId", 0);
                int userId = data.getIntExtra("userId", 0);
                int dialog_id = 0;
                if (chatId != 0) {
                    dialog_id = -chatId;
                } else if (userId != 0) {
                    dialog_id = userId;
                }
                TLRPC.FileLocation location = getCurrentFile();
                if (dialog_id != 0 && location != null) {
                    Intent intent = new Intent(GalleryImageViewer.this, ChatActivity.class);
                    if (chatId != 0) {
                        intent.putExtra("chatId", chatId);
                    } else {
                        intent.putExtra("userId", userId);
                    }
                    startActivity(intent);
                    NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats);
                    finish();
                    if (withoutBottom) {
                        MessagesController.getInstance().sendMessage(location, dialog_id);
                    } else {
                        int item = mViewPager.getCurrentItem();
                        MessageObject obj = localPagerAdapter.imagesArr.get(item);
                        MessagesController.getInstance().sendMessage(obj, dialog_id);
                    }
                }
                }*/
            } else if (id == gallery_menu_delete) {
                if (parentActivity == null) {
                    return;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
                if (currentMessageObject != null && currentMessageObject.isVideo()) {
                    builder.setMessage(LocaleController.formatString("AreYouSureDeleteVideo",
                            kr.wdream.storyshop.R.string.AreYouSureDeleteVideo));
                } else if (currentMessageObject != null && currentMessageObject.isGif()) {
                    builder.setMessage(LocaleController.formatString("AreYouSure",
                            kr.wdream.storyshop.R.string.AreYouSure));
                } else {
                    builder.setMessage(LocaleController.formatString("AreYouSureDeletePhoto",
                            kr.wdream.storyshop.R.string.AreYouSureDeletePhoto));
                }
                builder.setTitle(LocaleController.getString("AppName", kr.wdream.storyshop.R.string.AppName));
                builder.setPositiveButton(LocaleController.getString("OK", kr.wdream.storyshop.R.string.OK),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                if (!imagesArr.isEmpty()) {
                                    if (currentIndex < 0 || currentIndex >= imagesArr.size()) {
                                        return;
                                    }
                                    MessageObject obj = imagesArr.get(currentIndex);
                                    if (obj.isSent()) {
                                        closePhoto(false, false);
                                        ArrayList<Integer> arr = new ArrayList<>();
                                        arr.add(obj.getId());

                                        ArrayList<Long> random_ids = null;
                                        TLRPC.EncryptedChat encryptedChat = null;
                                        if ((int) obj.getDialogId() == 0 && obj.messageOwner.random_id != 0) {
                                            random_ids = new ArrayList<>();
                                            random_ids.add(obj.messageOwner.random_id);
                                            encryptedChat = MessagesController.getInstance()
                                                    .getEncryptedChat((int) (obj.getDialogId() >> 32));
                                        }

                                        MessagesController.getInstance().deleteMessages(arr, random_ids,
                                                encryptedChat, obj.messageOwner.to_id.channel_id);
                                    }
                                } else if (!avatarsArr.isEmpty()) {
                                    if (currentIndex < 0 || currentIndex >= avatarsArr.size()) {
                                        return;
                                    }
                                    TLRPC.Photo photo = avatarsArr.get(currentIndex);
                                    TLRPC.FileLocation currentLocation = imagesArrLocations.get(currentIndex);
                                    if (photo instanceof TLRPC.TL_photoEmpty) {
                                        photo = null;
                                    }
                                    boolean current = false;
                                    if (currentUserAvatarLocation != null) {
                                        if (photo != null) {
                                            for (TLRPC.PhotoSize size : photo.sizes) {
                                                if (size.location.local_id == currentUserAvatarLocation.local_id
                                                        && size.location.volume_id == currentUserAvatarLocation.volume_id) {
                                                    current = true;
                                                    break;
                                                }
                                            }
                                        } else if (currentLocation.local_id == currentUserAvatarLocation.local_id
                                                && currentLocation.volume_id == currentUserAvatarLocation.volume_id) {
                                            current = true;
                                        }
                                    }
                                    if (current) {
                                        MessagesController.getInstance().deleteUserPhoto(null);
                                        closePhoto(false, false);
                                    } else if (photo != null) {
                                        TLRPC.TL_inputPhoto inputPhoto = new TLRPC.TL_inputPhoto();
                                        inputPhoto.id = photo.id;
                                        inputPhoto.access_hash = photo.access_hash;
                                        MessagesController.getInstance().deleteUserPhoto(inputPhoto);
                                        MessagesStorage.getInstance().clearUserPhoto(avatarsDialogId, photo.id);
                                        imagesArrLocations.remove(currentIndex);
                                        imagesArrLocationsSizes.remove(currentIndex);
                                        avatarsArr.remove(currentIndex);
                                        if (imagesArrLocations.isEmpty()) {
                                            closePhoto(false, false);
                                        } else {
                                            int index = currentIndex;
                                            if (index >= avatarsArr.size()) {
                                                index = avatarsArr.size() - 1;
                                            }
                                            currentIndex = -1;
                                            setImageIndex(index, true);
                                        }
                                    }
                                }
                            }
                        });
                builder.setNegativeButton(
                        LocaleController.getString("Cancel", kr.wdream.storyshop.R.string.Cancel), null);
                showAlertDialog(builder);
            } else if (id == gallery_menu_caption_done) {
                closeCaptionEnter(true);
            } else if (id == gallery_menu_share) {
                onSharePressed();
            } else if (id == gallery_menu_openin) {
                try {
                    AndroidUtilities.openForView(currentMessageObject, parentActivity);
                    closePhoto(false, false);
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
            } else if (id == gallery_menu_mute) {
                muteVideo = !muteVideo;
                if (videoPlayer != null) {
                    videoPlayer.setMute(muteVideo);
                }
                if (muteVideo) {
                    actionBar.setTitle(
                            LocaleController.getString("AttachGif", kr.wdream.storyshop.R.string.AttachGif));
                    muteItem.setIcon(kr.wdream.storyshop.R.drawable.volume_off);
                } else {
                    actionBar.setTitle(LocaleController.getString("AttachVideo",
                            kr.wdream.storyshop.R.string.AttachVideo));
                    muteItem.setIcon(kr.wdream.storyshop.R.drawable.volume_on);
                }
            } else if (id == gallery_menu_masks) {
                if (parentActivity == null || currentMessageObject == null
                        || currentMessageObject.messageOwner.media == null
                        || currentMessageObject.messageOwner.media.photo == null) {
                    return;
                }
                StickersAlert stickersAlert = new StickersAlert(parentActivity,
                        currentMessageObject.messageOwner.media.photo);
                stickersAlert.show();
            }
        }

        @Override
        public boolean canOpenMenu() {
            if (currentMessageObject != null) {
                File f = FileLoader.getPathToMessage(currentMessageObject.messageOwner);
                if (f.exists()) {
                    return true;
                }
            } else if (currentFileLocation != null) {
                File f = FileLoader.getPathToAttach(currentFileLocation, avatarsDialogId != 0);
                if (f.exists()) {
                    return true;
                }
            }
            return false;
        }
    });

    ActionBarMenu menu = actionBar.createMenu();

    masksItem = menu.addItem(gallery_menu_masks, kr.wdream.storyshop.R.drawable.ic_masks_msk1);
    muteItem = menu.addItem(gallery_menu_mute, kr.wdream.storyshop.R.drawable.volume_on);

    menuItem = menu.addItem(0, kr.wdream.storyshop.R.drawable.ic_ab_other);
    menuItem.addSubItem(gallery_menu_openin,
            LocaleController.getString("OpenInExternalApp", kr.wdream.storyshop.R.string.OpenInExternalApp), 0);
    menuItem.addSubItem(gallery_menu_showall,
            LocaleController.getString("ShowAllMedia", kr.wdream.storyshop.R.string.ShowAllMedia), 0);
    menuItem.addSubItem(gallery_menu_share,
            LocaleController.getString("ShareFile", kr.wdream.storyshop.R.string.ShareFile), 0);
    menuItem.addSubItem(gallery_menu_save,
            LocaleController.getString("SaveToGallery", kr.wdream.storyshop.R.string.SaveToGallery), 0);
    menuItem.addSubItem(gallery_menu_delete,
            LocaleController.getString("Delete", kr.wdream.storyshop.R.string.Delete), 0);

    captionDoneItem = menu.addItemWithWidth(gallery_menu_caption_done, kr.wdream.storyshop.R.drawable.ic_done,
            AndroidUtilities.dp(56));

    bottomLayout = new FrameLayout(actvityContext);
    bottomLayout.setBackgroundColor(0x7f000000);
    containerView.addView(bottomLayout,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.BOTTOM | Gravity.LEFT));

    captionTextViewOld = new TextView(actvityContext);
    captionTextViewOld.setMaxLines(10);
    captionTextViewOld.setBackgroundColor(0x7f000000);
    captionTextViewOld.setPadding(AndroidUtilities.dp(20), AndroidUtilities.dp(8), AndroidUtilities.dp(20),
            AndroidUtilities.dp(8));
    captionTextViewOld.setLinkTextColor(0xffffffff);
    captionTextViewOld.setTextColor(0xffffffff);
    captionTextViewOld.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
    captionTextViewOld.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
    captionTextViewOld.setVisibility(View.INVISIBLE);
    containerView.addView(captionTextViewOld, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 0, 0, 0, 48));
    captionTextViewOld.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (cropItem.getVisibility() == View.VISIBLE) {
                openCaptionEnter();
            }
        }
    });

    captionTextView = captionTextViewNew = new TextView(actvityContext);
    captionTextViewNew.setMaxLines(10);
    captionTextViewNew.setBackgroundColor(0x7f000000);
    captionTextViewNew.setPadding(AndroidUtilities.dp(20), AndroidUtilities.dp(8), AndroidUtilities.dp(20),
            AndroidUtilities.dp(8));
    captionTextViewNew.setLinkTextColor(0xffffffff);
    captionTextViewNew.setTextColor(0xffffffff);
    captionTextViewNew.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
    captionTextViewNew.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
    captionTextViewNew.setVisibility(View.INVISIBLE);
    containerView.addView(captionTextViewNew, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 0, 0, 0, 48));
    captionTextViewNew.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (cropItem.getVisibility() == View.VISIBLE) {
                openCaptionEnter();
            }
        }
    });

    radialProgressViews[0] = new RadialProgressView(containerView.getContext(), containerView);
    radialProgressViews[0].setBackgroundState(0, false);
    radialProgressViews[1] = new RadialProgressView(containerView.getContext(), containerView);
    radialProgressViews[1].setBackgroundState(0, false);
    radialProgressViews[2] = new RadialProgressView(containerView.getContext(), containerView);
    radialProgressViews[2].setBackgroundState(0, false);

    shareButton = new ImageView(containerView.getContext());
    shareButton.setImageResource(kr.wdream.storyshop.R.drawable.share);
    shareButton.setScaleType(ImageView.ScaleType.CENTER);
    shareButton.setBackgroundDrawable(Theme.createBarSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    bottomLayout.addView(shareButton,
            LayoutHelper.createFrame(50, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.RIGHT));
    shareButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onSharePressed();
        }
    });

    nameTextView = new TextView(containerView.getContext());
    nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    nameTextView.setSingleLine(true);
    nameTextView.setMaxLines(1);
    nameTextView.setEllipsize(TextUtils.TruncateAt.END);
    nameTextView.setTextColor(0xffffffff);
    nameTextView.setGravity(Gravity.LEFT);
    bottomLayout.addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 16, 5, 60, 0));

    dateTextView = new TextView(containerView.getContext());
    dateTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
    dateTextView.setSingleLine(true);
    dateTextView.setMaxLines(1);
    dateTextView.setEllipsize(TextUtils.TruncateAt.END);
    dateTextView.setTextColor(0xffffffff);
    dateTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    dateTextView.setGravity(Gravity.LEFT);
    bottomLayout.addView(dateTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 16, 25, 50, 0));

    if (Build.VERSION.SDK_INT >= 16) {
        videoPlayerSeekbar = new SeekBar(containerView.getContext());
        videoPlayerSeekbar.setColors(0x66ffffff, 0xffffffff, 0xffffffff);
        videoPlayerSeekbar.setDelegate(new SeekBar.SeekBarDelegate() {
            @Override
            public void onSeekBarDrag(float progress) {
                if (videoPlayer != null) {
                    videoPlayer.getPlayerControl().seekTo((int) (progress * videoPlayer.getDuration()));
                }
            }
        });

        videoPlayerControlFrameLayout = new FrameLayout(containerView.getContext()) {

            @Override
            public boolean onTouchEvent(MotionEvent event) {
                int x = (int) event.getX();
                int y = (int) event.getY();
                if (videoPlayerSeekbar.onTouch(event.getAction(), event.getX() - AndroidUtilities.dp(48),
                        event.getY())) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                    invalidate();
                    return true;
                }
                return super.onTouchEvent(event);
            }

            @Override
            protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
                long duration;
                if (videoPlayer != null) {
                    duration = videoPlayer.getDuration();
                    if (duration == ExoPlayer.UNKNOWN_TIME) {
                        duration = 0;
                    }
                } else {
                    duration = 0;
                }
                duration /= 1000;
                int size = (int) Math
                        .ceil(videoPlayerTime.getPaint().measureText(String.format("%02d:%02d / %02d:%02d",
                                duration / 60, duration % 60, duration / 60, duration % 60)));
                videoPlayerSeekbar.setSize(getMeasuredWidth() - AndroidUtilities.dp(48 + 16) - size,
                        getMeasuredHeight());
            }

            @Override
            protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
                super.onLayout(changed, left, top, right, bottom);
                float progress = 0;
                if (videoPlayer != null) {
                    PlayerControl playerControl = videoPlayer.getPlayerControl();
                    progress = playerControl.getCurrentPosition() / (float) playerControl.getDuration();
                }
                videoPlayerSeekbar.setProgress(progress);
            }

            @Override
            protected void onDraw(Canvas canvas) {
                canvas.save();
                canvas.translate(AndroidUtilities.dp(48), 0);
                videoPlayerSeekbar.draw(canvas);
                canvas.restore();
            }
        };
        videoPlayerControlFrameLayout.setWillNotDraw(false);
        bottomLayout.addView(videoPlayerControlFrameLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
                LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));

        videoPlayButton = new ImageView(containerView.getContext());
        videoPlayButton.setScaleType(ImageView.ScaleType.CENTER);
        videoPlayerControlFrameLayout.addView(videoPlayButton,
                LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.TOP));
        videoPlayButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (videoPlayer != null) {
                    if (isPlaying) {
                        videoPlayer.getPlayerControl().pause();
                    } else {
                        videoPlayer.getPlayerControl().start();
                    }
                }
            }
        });

        videoPlayerTime = new TextView(containerView.getContext());
        videoPlayerTime.setTextColor(0xffffffff);
        videoPlayerTime.setGravity(Gravity.CENTER_VERTICAL);
        videoPlayerTime.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
        videoPlayerControlFrameLayout.addView(videoPlayerTime, LayoutHelper.createFrame(
                LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.RIGHT | Gravity.TOP, 0, 0, 8, 0));
    }

    pickerView = new PickerBottomLayoutViewer(actvityContext);
    pickerView.setBackgroundColor(0x7f000000);
    containerView.addView(pickerView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.BOTTOM | Gravity.LEFT));
    pickerView.cancelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (placeProvider instanceof EmptyPhotoViewerProvider) {
                closePhoto(false, false);
            } else if (placeProvider != null) {
                closePhoto(!placeProvider.cancelButtonPressed(), false);
            }
        }
    });
    pickerView.doneButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (placeProvider != null) {
                placeProvider.sendButtonPressed(currentIndex);
                closePhoto(false, false);
            }
        }
    });

    LinearLayout itemsLayout = new LinearLayout(parentActivity);
    itemsLayout.setOrientation(LinearLayout.HORIZONTAL);
    pickerView.addView(itemsLayout,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 48, Gravity.TOP | Gravity.CENTER_HORIZONTAL));

    tuneItem = new ImageView(parentActivity);
    tuneItem.setScaleType(ImageView.ScaleType.CENTER);
    tuneItem.setImageResource(kr.wdream.storyshop.R.drawable.photo_tools);
    tuneItem.setBackgroundDrawable(Theme.createBarSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    itemsLayout.addView(tuneItem, LayoutHelper.createLinear(56, 48));
    tuneItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switchToEditMode(2);
        }
    });

    paintItem = new ImageView(parentActivity);
    paintItem.setScaleType(ImageView.ScaleType.CENTER);
    paintItem.setImageResource(kr.wdream.storyshop.R.drawable.photo_paint);
    paintItem.setBackgroundDrawable(Theme.createBarSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    itemsLayout.addView(paintItem, LayoutHelper.createLinear(56, 48));
    paintItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switchToEditMode(3);
        }
    });

    cropItem = new ImageView(parentActivity);
    cropItem.setScaleType(ImageView.ScaleType.CENTER);
    cropItem.setImageResource(kr.wdream.storyshop.R.drawable.photo_crop);
    cropItem.setBackgroundDrawable(Theme.createBarSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    itemsLayout.addView(cropItem, LayoutHelper.createLinear(56, 48));
    cropItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switchToEditMode(1);
        }
    });

    editorDoneLayout = new PickerBottomLayoutViewer(actvityContext);
    editorDoneLayout.setBackgroundColor(0x7f000000);
    editorDoneLayout.updateSelectedCount(0, false);
    editorDoneLayout.setVisibility(View.GONE);
    containerView.addView(editorDoneLayout,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.BOTTOM));
    editorDoneLayout.cancelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (currentEditMode == 1) {
                photoCropView.cancelAnimationRunnable();
            }
            switchToEditMode(0);
        }
    });
    editorDoneLayout.doneButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (currentEditMode == 1) {
                photoCropView.cancelAnimationRunnable();
                if (imageMoveAnimation != null) {
                    return;
                }
            }
            applyCurrentEditMode();
            switchToEditMode(0);
        }
    });

    ImageView rotateButton = new ImageView(actvityContext);
    rotateButton.setScaleType(ImageView.ScaleType.CENTER);
    rotateButton.setImageResource(kr.wdream.storyshop.R.drawable.tool_rotate);
    rotateButton.setBackgroundDrawable(Theme.createBarSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
    editorDoneLayout.addView(rotateButton, LayoutHelper.createFrame(48, 48, Gravity.CENTER));
    rotateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            centerImage.setOrientation(centerImage.getOrientation() - 90, false);
            photoCropView.setOrientation(centerImage.getOrientation());
            containerView.invalidate();
        }
    });

    gestureDetector = new GestureDetector(containerView.getContext(), this);
    gestureDetector.setOnDoubleTapListener(this);

    ImageReceiver.ImageReceiverDelegate imageReceiverDelegate = new ImageReceiver.ImageReceiverDelegate() {
        @Override
        public void didSetImage(ImageReceiver imageReceiver, boolean set, boolean thumb) {
            if (imageReceiver == centerImage && set && placeProvider != null && placeProvider.scaleToFill()) {
                if (!wasLayout) {
                    dontResetZoomOnFirstLayout = true;
                } else {
                    setScaleToFill();
                }
            }
        }
    };

    centerImage.setParentView(containerView);
    centerImage.setCrossfadeAlpha((byte) 2);
    centerImage.setInvalidateAll(true);
    centerImage.setDelegate(imageReceiverDelegate);
    leftImage.setParentView(containerView);
    leftImage.setCrossfadeAlpha((byte) 2);
    leftImage.setInvalidateAll(true);
    leftImage.setDelegate(imageReceiverDelegate);
    rightImage.setParentView(containerView);
    rightImage.setCrossfadeAlpha((byte) 2);
    rightImage.setInvalidateAll(true);
    rightImage.setDelegate(imageReceiverDelegate);

    WindowManager manager = (WindowManager) ApplicationLoader.applicationContext
            .getSystemService(Activity.WINDOW_SERVICE);
    int rotation = manager.getDefaultDisplay().getRotation();

    checkImageView = new CheckBox(containerView.getContext(), kr.wdream.storyshop.R.drawable.selectphoto_large);
    checkImageView.setDrawBackground(true);
    checkImageView.setSize(45);
    checkImageView.setCheckOffset(AndroidUtilities.dp(1));
    checkImageView.setColor(0xff3ccaef);
    checkImageView.setVisibility(View.GONE);
    containerView.addView(checkImageView, LayoutHelper.createFrame(45, 45, Gravity.RIGHT | Gravity.TOP, 0,
            rotation == Surface.ROTATION_270 || rotation == Surface.ROTATION_90 ? 58 : 68, 10, 0));
    if (Build.VERSION.SDK_INT >= 21) {
        ((FrameLayout.LayoutParams) checkImageView
                .getLayoutParams()).topMargin += AndroidUtilities.statusBarHeight;
    }
    checkImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (placeProvider != null) {
                placeProvider.setPhotoChecked(currentIndex);
                checkImageView.setChecked(placeProvider.isPhotoChecked(currentIndex), true);
                updateSelectedCount();
            }
        }
    });

    captionEditText = new PhotoViewerCaptionEnterView(actvityContext, containerView, windowView);
    captionEditText.setDelegate(new PhotoViewerCaptionEnterView.PhotoViewerCaptionEnterViewDelegate() {
        @Override
        public void onCaptionEnter() {
            closeCaptionEnter(true);
        }

        @Override
        public void onTextChanged(CharSequence text) {
            if (mentionsAdapter != null && captionEditText != null && parentChatActivity != null
                    && text != null) {
                mentionsAdapter.searchUsernameOrHashtag(text.toString(), captionEditText.getCursorPosition(),
                        parentChatActivity.messages);
            }
        }

        @Override
        public void onWindowSizeChanged(int size) {
            int height = AndroidUtilities.dp(36 * Math.min(3, mentionsAdapter.getItemCount())
                    + (mentionsAdapter.getItemCount() > 3 ? 18 : 0));
            if (size - ActionBar.getCurrentActionBarHeight() * 2 < height) {
                allowMentions = false;
                if (mentionListView != null && mentionListView.getVisibility() == View.VISIBLE) {
                    mentionListView.setVisibility(View.INVISIBLE);
                }
            } else {
                allowMentions = true;
                if (mentionListView != null && mentionListView.getVisibility() == View.INVISIBLE) {
                    mentionListView.setVisibility(View.VISIBLE);
                }
            }
        }
    });
    containerView.addView(captionEditText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 0, 0, 0, -400));

    mentionListView = new RecyclerListView(actvityContext);
    mentionListView.setTag(5);
    mentionLayoutManager = new LinearLayoutManager(actvityContext) {
        @Override
        public boolean supportsPredictiveItemAnimations() {
            return false;
        }
    };
    mentionLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    mentionListView.setLayoutManager(mentionLayoutManager);
    mentionListView.setBackgroundColor(0x7f000000);
    mentionListView.setVisibility(View.GONE);
    mentionListView.setClipToPadding(true);
    mentionListView.setOverScrollMode(ListView.OVER_SCROLL_NEVER);
    containerView.addView(mentionListView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 110, Gravity.LEFT | Gravity.BOTTOM));

    mentionListView.setAdapter(mentionsAdapter = new MentionsAdapter(actvityContext, true, 0,
            new MentionsAdapter.MentionsAdapterDelegate() {
                @Override
                public void needChangePanelVisibility(boolean show) {
                    if (show) {
                        FrameLayout.LayoutParams layoutParams3 = (FrameLayout.LayoutParams) mentionListView
                                .getLayoutParams();
                        int height = 36 * Math.min(3, mentionsAdapter.getItemCount())
                                + (mentionsAdapter.getItemCount() > 3 ? 18 : 0);
                        layoutParams3.height = AndroidUtilities.dp(height);
                        layoutParams3.topMargin = -AndroidUtilities.dp(height);
                        mentionListView.setLayoutParams(layoutParams3);

                        if (mentionListAnimation != null) {
                            mentionListAnimation.cancel();
                            mentionListAnimation = null;
                        }

                        if (mentionListView.getVisibility() == View.VISIBLE) {
                            mentionListView.setAlpha(1.0f);
                            return;
                        } else {
                            mentionLayoutManager.scrollToPositionWithOffset(0, 10000);
                        }
                        if (allowMentions) {
                            mentionListView.setVisibility(View.VISIBLE);
                            mentionListAnimation = new AnimatorSet();
                            mentionListAnimation
                                    .playTogether(ObjectAnimator.ofFloat(mentionListView, "alpha", 0.0f, 1.0f));
                            mentionListAnimation.addListener(new AnimatorListenerAdapterProxy() {
                                @Override
                                public void onAnimationEnd(Animator animation) {
                                    if (mentionListAnimation != null
                                            && mentionListAnimation.equals(animation)) {
                                        mentionListAnimation = null;
                                    }
                                }
                            });
                            mentionListAnimation.setDuration(200);
                            mentionListAnimation.start();
                        } else {
                            mentionListView.setAlpha(1.0f);
                            mentionListView.setVisibility(View.INVISIBLE);
                        }
                    } else {
                        if (mentionListAnimation != null) {
                            mentionListAnimation.cancel();
                            mentionListAnimation = null;
                        }

                        if (mentionListView.getVisibility() == View.GONE) {
                            return;
                        }
                        if (allowMentions) {
                            mentionListAnimation = new AnimatorSet();
                            mentionListAnimation
                                    .playTogether(ObjectAnimator.ofFloat(mentionListView, "alpha", 0.0f));
                            mentionListAnimation.addListener(new AnimatorListenerAdapterProxy() {
                                @Override
                                public void onAnimationEnd(Animator animation) {
                                    if (mentionListAnimation != null
                                            && mentionListAnimation.equals(animation)) {
                                        mentionListView.setVisibility(View.GONE);
                                        mentionListAnimation = null;
                                    }
                                }
                            });
                            mentionListAnimation.setDuration(200);
                            mentionListAnimation.start();
                        } else {
                            mentionListView.setVisibility(View.GONE);
                        }
                    }
                }

                @Override
                public void onContextSearch(boolean searching) {

                }

                @Override
                public void onContextClick(TLRPC.BotInlineResult result) {

                }
            }));
    mentionsAdapter.setAllowNewMentions(false);

    mentionListView.setOnItemClickListener(new RecyclerListView.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {
            Object object = mentionsAdapter.getItem(position);
            int start = mentionsAdapter.getResultStartPosition();
            int len = mentionsAdapter.getResultLength();
            if (object instanceof TLRPC.User) {
                TLRPC.User user = (TLRPC.User) object;
                if (user != null) {
                    captionEditText.replaceWithText(start, len, "@" + user.username + " ");
                }
            } else if (object instanceof String) {
                captionEditText.replaceWithText(start, len, object + " ");
            }
        }
    });

    mentionListView.setOnItemLongClickListener(new RecyclerListView.OnItemLongClickListener() {
        @Override
        public boolean onItemClick(View view, int position) {
            Object object = mentionsAdapter.getItem(position);
            if (object instanceof String) {
                AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
                builder.setTitle(LocaleController.getString("AppName", kr.wdream.storyshop.R.string.AppName));
                builder.setMessage(
                        LocaleController.getString("ClearSearch", kr.wdream.storyshop.R.string.ClearSearch));
                builder.setPositiveButton(LocaleController
                        .getString("ClearButton", kr.wdream.storyshop.R.string.ClearButton).toUpperCase(),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                mentionsAdapter.clearRecentHashtags();
                            }
                        });
                builder.setNegativeButton(
                        LocaleController.getString("Cancel", kr.wdream.storyshop.R.string.Cancel), null);
                showAlertDialog(builder);
                return true;
            }
            return false;
        }
    });
}

From source file:org.telegram.ui.PassportActivity.java

private void createPasswordInterface(Context context) {
    TLRPC.User botUser = null;//from  ww  w  . j  a  va  2s. c  o  m
    if (currentForm != null) {
        for (int a = 0; a < currentForm.users.size(); a++) {
            TLRPC.User user = currentForm.users.get(a);
            if (user.id == currentBotId) {
                botUser = user;
                break;
            }
        }
    } else {
        botUser = UserConfig.getInstance(currentAccount).getCurrentUser();
    }

    FrameLayout frameLayout = (FrameLayout) fragmentView;

    actionBar.setTitle(LocaleController.getString("TelegramPassport", R.string.TelegramPassport));

    emptyView = new EmptyTextProgressView(context);
    emptyView.showProgress();
    frameLayout.addView(emptyView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));

    passwordAvatarContainer = new FrameLayout(context);
    linearLayout2.addView(passwordAvatarContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 100));

    BackupImageView avatarImageView = new BackupImageView(context);
    avatarImageView.setRoundRadius(AndroidUtilities.dp(32));
    passwordAvatarContainer.addView(avatarImageView,
            LayoutHelper.createFrame(64, 64, Gravity.CENTER, 0, 8, 0, 0));

    AvatarDrawable avatarDrawable = new AvatarDrawable(botUser);
    TLRPC.FileLocation photo = null;
    if (botUser.photo != null) {
        photo = botUser.photo.photo_small;
    }
    avatarImageView.setImage(photo, "50_50", avatarDrawable, botUser);

    passwordRequestTextView = new TextInfoPrivacyCell(context);
    passwordRequestTextView.getTextView().setGravity(Gravity.CENTER_HORIZONTAL);
    if (currentBotId == 0) {
        passwordRequestTextView
                .setText(LocaleController.getString("PassportSelfRequest", R.string.PassportSelfRequest));
    } else {
        passwordRequestTextView.setText(AndroidUtilities.replaceTags(LocaleController
                .formatString("PassportRequest", R.string.PassportRequest, UserObject.getFirstName(botUser))));
    }
    ((FrameLayout.LayoutParams) passwordRequestTextView.getTextView()
            .getLayoutParams()).gravity = Gravity.CENTER_HORIZONTAL;
    linearLayout2.addView(passwordRequestTextView,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT,
                    (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 21, 0, 21, 0));

    noPasswordImageView = new ImageView(context);
    noPasswordImageView.setImageResource(R.drawable.no_password);
    noPasswordImageView.setColorFilter(new PorterDuffColorFilter(
            Theme.getColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY));
    linearLayout2.addView(noPasswordImageView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 13, 0, 0));

    noPasswordTextView = new TextView(context);
    noPasswordTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    noPasswordTextView.setGravity(Gravity.CENTER_HORIZONTAL);
    noPasswordTextView.setPadding(AndroidUtilities.dp(21), AndroidUtilities.dp(10), AndroidUtilities.dp(21),
            AndroidUtilities.dp(17));
    noPasswordTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText4));
    noPasswordTextView.setText(LocaleController.getString("TelegramPassportCreatePasswordInfo",
            R.string.TelegramPassportCreatePasswordInfo));
    linearLayout2.addView(noPasswordTextView,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT,
                    (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 21, 10, 21, 0));

    noPasswordSetTextView = new TextView(context);
    noPasswordSetTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlueText5));
    noPasswordSetTextView.setGravity(Gravity.CENTER);
    noPasswordSetTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
    noPasswordSetTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    noPasswordSetTextView.setText(LocaleController.getString("TelegramPassportCreatePassword",
            R.string.TelegramPassportCreatePassword));
    linearLayout2.addView(noPasswordSetTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 24,
            (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 21, 9, 21, 0));
    noPasswordSetTextView.setOnClickListener(v -> {
        TwoStepVerificationActivity activity = new TwoStepVerificationActivity(currentAccount, 1);
        activity.setCloseAfterSet(true);
        activity.setCurrentPasswordInfo(new byte[0], currentPassword);
        presentFragment(activity);
    });

    inputFields = new EditTextBoldCursor[1];
    inputFieldContainers = new ViewGroup[1];
    for (int a = 0; a < 1; a++) {
        inputFieldContainers[a] = new FrameLayout(context);
        linearLayout2.addView(inputFieldContainers[a],
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 50));
        inputFieldContainers[a].setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));

        inputFields[a] = new EditTextBoldCursor(context);
        inputFields[a].setTag(a);
        inputFields[a].setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
        inputFields[a].setHintTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteHintText));
        inputFields[a].setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
        inputFields[a].setBackgroundDrawable(null);
        inputFields[a].setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
        inputFields[a].setCursorSize(AndroidUtilities.dp(20));
        inputFields[a].setCursorWidth(1.5f);
        inputFields[a].setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        inputFields[a].setMaxLines(1);
        inputFields[a].setLines(1);
        inputFields[a].setSingleLine(true);
        inputFields[a].setTransformationMethod(PasswordTransformationMethod.getInstance());
        inputFields[a].setTypeface(Typeface.DEFAULT);
        inputFields[a].setImeOptions(EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
        inputFields[a].setPadding(0, 0, 0, AndroidUtilities.dp(6));
        inputFields[a].setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
        inputFieldContainers[a].addView(inputFields[a], LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
                LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 21, 12, 21, 6));

        inputFields[a].setOnEditorActionListener((textView, i, keyEvent) -> {
            if (i == EditorInfo.IME_ACTION_NEXT || i == EditorInfo.IME_ACTION_DONE) {
                doneItem.callOnClick();
                return true;
            }
            return false;
        });
        inputFields[a].setCustomSelectionActionModeCallback(new ActionMode.Callback() {
            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            public void onDestroyActionMode(ActionMode mode) {
            }

            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                return false;
            }
        });
    }

    passwordInfoRequestTextView = new TextInfoPrivacyCell(context);
    passwordInfoRequestTextView.setBackgroundDrawable(Theme.getThemedDrawable(context,
            R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow));
    passwordInfoRequestTextView.setText(
            LocaleController.formatString("PassportRequestPasswordInfo", R.string.PassportRequestPasswordInfo));
    linearLayout2.addView(passwordInfoRequestTextView,
            LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

    passwordForgotButton = new TextView(context);
    passwordForgotButton.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlueText4));
    passwordForgotButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    passwordForgotButton.setText(LocaleController.getString("ForgotPassword", R.string.ForgotPassword));
    passwordForgotButton.setPadding(0, 0, 0, 0);
    linearLayout2.addView(passwordForgotButton, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, 30,
            (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 21, 0, 21, 0));
    passwordForgotButton.setOnClickListener(v -> {
        if (currentPassword.has_recovery) {
            needShowProgress();
            TLRPC.TL_auth_requestPasswordRecovery req = new TLRPC.TL_auth_requestPasswordRecovery();
            int reqId = ConnectionsManager.getInstance(currentAccount).sendRequest(req,
                    (response, error) -> AndroidUtilities.runOnUIThread(() -> {
                        needHideProgress();
                        if (error == null) {
                            final TLRPC.TL_auth_passwordRecovery res = (TLRPC.TL_auth_passwordRecovery) response;
                            AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                            builder.setMessage(LocaleController.formatString("RestoreEmailSent",
                                    R.string.RestoreEmailSent, res.email_pattern));
                            builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                            builder.setPositiveButton(LocaleController.getString("OK", R.string.OK),
                                    (dialogInterface, i) -> {
                                        TwoStepVerificationActivity fragment = new TwoStepVerificationActivity(
                                                currentAccount, 1);
                                        fragment.setRecoveryParams(currentPassword);
                                        currentPassword.email_unconfirmed_pattern = res.email_pattern;
                                        presentFragment(fragment);
                                    });
                            Dialog dialog = showDialog(builder.create());
                            if (dialog != null) {
                                dialog.setCanceledOnTouchOutside(false);
                                dialog.setCancelable(false);
                            }
                        } else {
                            if (error.text.startsWith("FLOOD_WAIT")) {
                                int time = Utilities.parseInt(error.text);
                                String timeString;
                                if (time < 60) {
                                    timeString = LocaleController.formatPluralString("Seconds", time);
                                } else {
                                    timeString = LocaleController.formatPluralString("Minutes", time / 60);
                                }
                                showAlertWithText(LocaleController.getString("AppName", R.string.AppName),
                                        LocaleController.formatString("FloodWaitTime", R.string.FloodWaitTime,
                                                timeString));
                            } else {
                                showAlertWithText(LocaleController.getString("AppName", R.string.AppName),
                                        error.text);
                            }
                        }
                    }), ConnectionsManager.RequestFlagFailOnServerErrors
                            | ConnectionsManager.RequestFlagWithoutLogin);
            ConnectionsManager.getInstance(currentAccount).bindRequestToGuid(reqId, classGuid);
        } else {
            if (getParentActivity() == null) {
                return;
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
            builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
            builder.setNegativeButton(
                    LocaleController.getString("RestorePasswordResetAccount",
                            R.string.RestorePasswordResetAccount),
                    (dialog, which) -> Browser.openUrl(getParentActivity(),
                            "https://telegram.org/deactivate?phone="
                                    + UserConfig.getInstance(currentAccount).getClientPhone()));
            builder.setTitle(LocaleController.getString("RestorePasswordNoEmailTitle",
                    R.string.RestorePasswordNoEmailTitle));
            builder.setMessage(LocaleController.getString("RestorePasswordNoEmailText",
                    R.string.RestorePasswordNoEmailText));
            showDialog(builder.create());
        }
    });

    updatePasswordInterface();
}

From source file:com.skytree.epubtest.BookViewActivity.java

public void makeControls() {
    this.removeControls();
    Theme theme = getCurrentTheme();//from   www .ja  v  a 2  s  .c  o m

    int bs = 38;
    if (this.isRotationLocked)
        rotationButton = this.makeImageButton(9000, R.drawable.rotationlocked2x, ps(42), ps(42));
    else
        rotationButton = this.makeImageButton(9000, R.drawable.rotation2x, ps(42), ps(42));
    listButton = this.makeImageButton(9001, R.drawable.list2x, getPS(bs), getPS(bs));
    fontButton = this.makeImageButton(9002, R.drawable.font2x, getPS(bs), getPS(bs));
    searchButton = this.makeImageButton(9003, R.drawable.search2x, getPS(bs), getPS(bs));
    rotationButton.setOnTouchListener(new ImageButtonHighlighterOnTouchListener(rotationButton));
    listButton.setOnTouchListener(new ImageButtonHighlighterOnTouchListener(listButton));
    fontButton.setOnTouchListener(new ImageButtonHighlighterOnTouchListener(fontButton));
    searchButton.setOnTouchListener(new ImageButtonHighlighterOnTouchListener(searchButton));

    titleLabel = this.makeLabel(3000, title, Gravity.CENTER_HORIZONTAL, 17, Color.argb(240, 94, 61, 35)); // setTextSize in android uses sp (Scaled Pixel) as default, they say that sp guarantees the device dependent size, but as usual in android it can't be 100% sure.    
    authorLabel = this.makeLabel(3000, author, Gravity.CENTER_HORIZONTAL, 17, Color.argb(240, 94, 61, 35));
    pageIndexLabel = this.makeLabel(3000, "......", Gravity.CENTER_HORIZONTAL, 13, Color.argb(240, 94, 61, 35));
    secondaryIndexLabel = this.makeLabel(3000, "......", Gravity.CENTER_HORIZONTAL, 13,
            Color.argb(240, 94, 61, 35));

    //      rv.customView.addView(rotationButton);
    //      rv.customView.addView(listButton);
    //      rv.customView.addView(fontButton);
    //      rv.customView.addView(searchButton);      
    rv.customView.addView(titleLabel);
    rv.customView.addView(authorLabel);

    ePubView.addView(rotationButton);
    ePubView.addView(listButton);
    ePubView.addView(fontButton);
    if (!rv.isScrollMode())
        ePubView.addView(searchButton);
    //      ePubView.addView(titleLabel);
    //      ePubView.addView(authorLabel);

    ePubView.addView(pageIndexLabel);
    ePubView.addView(secondaryIndexLabel);

    seekBar = new SkySeekBar(this);
    seekBar.setMax(999);
    seekBar.setId(999);
    RectShape rectShape = new RectShape();
    ShapeDrawable thumb = new ShapeDrawable(rectShape);

    thumb.getPaint().setColor(theme.seekThumbColor);
    thumb.setIntrinsicHeight(getPS(28));
    thumb.setIntrinsicWidth(getPS(28));
    seekBar.setThumb(thumb);
    seekBar.setBackgroundColor(Color.TRANSPARENT);
    seekBar.setOnSeekBarChangeListener(new SeekBarDelegate());
    seekBar.setProgressDrawable(new DottedDrawable(theme.seekBarColor));
    seekBar.setThumbOffset(-3);
    seekBar.setMinimumHeight(24);

    int filterColor = theme.controlColor;
    rotationButton.setColorFilter(filterColor);
    listButton.setColorFilter(filterColor);
    fontButton.setColorFilter(filterColor);
    searchButton.setColorFilter(filterColor);

    authorLabel.setTextColor(filterColor);
    titleLabel.setTextColor(filterColor);
    pageIndexLabel.setTextColor(filterColor);
    secondaryIndexLabel.setTextColor(filterColor);

    ePubView.addView(seekBar);
}

From source file:com.rfo.basic.Run.java

private Toast Toaster(CharSequence msg) { // default: short, high toast
    Toast toast = Toaster(msg, Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 50);
    return toast;
}

From source file:org.telegram.ui.PassportActivity.java

private void createRequestInterface(Context context) {
    TLRPC.User botUser = null;//  w  ww .  j  ava 2  s. c  o m
    if (currentForm != null) {
        for (int a = 0; a < currentForm.users.size(); a++) {
            TLRPC.User user = currentForm.users.get(a);
            if (user.id == currentBotId) {
                botUser = user;
                break;
            }
        }
    }

    FrameLayout frameLayout = (FrameLayout) fragmentView;

    actionBar.setTitle(LocaleController.getString("TelegramPassport", R.string.TelegramPassport));

    actionBar.createMenu().addItem(info_item, R.drawable.profile_info);

    if (botUser != null) {
        FrameLayout avatarContainer = new FrameLayout(context);
        linearLayout2.addView(avatarContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 100));

        BackupImageView avatarImageView = new BackupImageView(context);
        avatarImageView.setRoundRadius(AndroidUtilities.dp(32));
        avatarContainer.addView(avatarImageView, LayoutHelper.createFrame(64, 64, Gravity.CENTER, 0, 8, 0, 0));

        AvatarDrawable avatarDrawable = new AvatarDrawable(botUser);
        TLRPC.FileLocation photo = null;
        if (botUser.photo != null) {
            photo = botUser.photo.photo_small;
        }
        avatarImageView.setImage(photo, "50_50", avatarDrawable, botUser);

        bottomCell = new TextInfoPrivacyCell(context);
        bottomCell.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider_top,
                Theme.key_windowBackgroundGrayShadow));
        bottomCell.setText(AndroidUtilities.replaceTags(LocaleController.formatString("PassportRequest",
                R.string.PassportRequest, UserObject.getFirstName(botUser))));
        bottomCell.getTextView().setGravity(Gravity.CENTER_HORIZONTAL);
        ((FrameLayout.LayoutParams) bottomCell.getTextView()
                .getLayoutParams()).gravity = Gravity.CENTER_HORIZONTAL;
        linearLayout2.addView(bottomCell,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    }

    headerCell = new HeaderCell(context);
    headerCell.setText(
            LocaleController.getString("PassportRequestedInformation", R.string.PassportRequestedInformation));
    headerCell.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
    linearLayout2.addView(headerCell,
            LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

    if (currentForm != null) {
        int size = currentForm.required_types.size();
        ArrayList<TLRPC.TL_secureRequiredType> personalDocuments = new ArrayList<>();
        ArrayList<TLRPC.TL_secureRequiredType> addressDocuments = new ArrayList<>();
        int personalCount = 0;
        int addressCount = 0;
        boolean hasPersonalInfo = false;
        boolean hasAddressInfo = false;
        for (int a = 0; a < size; a++) {
            TLRPC.SecureRequiredType secureRequiredType = currentForm.required_types.get(a);
            if (secureRequiredType instanceof TLRPC.TL_secureRequiredType) {
                TLRPC.TL_secureRequiredType requiredType = (TLRPC.TL_secureRequiredType) secureRequiredType;
                if (isPersonalDocument(requiredType.type)) {
                    personalDocuments.add(requiredType);
                    personalCount++;
                } else if (isAddressDocument(requiredType.type)) {
                    addressDocuments.add(requiredType);
                    addressCount++;
                } else if (requiredType.type instanceof TLRPC.TL_secureValueTypePersonalDetails) {
                    hasPersonalInfo = true;
                } else if (requiredType.type instanceof TLRPC.TL_secureValueTypeAddress) {
                    hasAddressInfo = true;
                }
            } else if (secureRequiredType instanceof TLRPC.TL_secureRequiredTypeOneOf) {
                TLRPC.TL_secureRequiredTypeOneOf requiredTypeOneOf = (TLRPC.TL_secureRequiredTypeOneOf) secureRequiredType;
                if (requiredTypeOneOf.types.isEmpty()) {
                    continue;
                }
                TLRPC.SecureRequiredType innerType = requiredTypeOneOf.types.get(0);
                if (!(innerType instanceof TLRPC.TL_secureRequiredType)) {
                    continue;
                }
                TLRPC.TL_secureRequiredType requiredType = (TLRPC.TL_secureRequiredType) innerType;

                if (isPersonalDocument(requiredType.type)) {
                    for (int b = 0, size2 = requiredTypeOneOf.types.size(); b < size2; b++) {
                        innerType = requiredTypeOneOf.types.get(b);
                        if (!(innerType instanceof TLRPC.TL_secureRequiredType)) {
                            continue;
                        }
                        personalDocuments.add((TLRPC.TL_secureRequiredType) innerType);
                    }
                    personalCount++;
                } else if (isAddressDocument(requiredType.type)) {
                    for (int b = 0, size2 = requiredTypeOneOf.types.size(); b < size2; b++) {
                        innerType = requiredTypeOneOf.types.get(b);
                        if (!(innerType instanceof TLRPC.TL_secureRequiredType)) {
                            continue;
                        }
                        addressDocuments.add((TLRPC.TL_secureRequiredType) innerType);
                    }
                    addressCount++;
                }
            }
        }
        boolean separatePersonal = !hasPersonalInfo || personalCount > 1;
        boolean separateAddress = !hasAddressInfo || addressCount > 1;
        for (int a = 0; a < size; a++) {
            TLRPC.SecureRequiredType secureRequiredType = currentForm.required_types.get(a);
            ArrayList<TLRPC.TL_secureRequiredType> documentTypes;
            TLRPC.TL_secureRequiredType requiredType;
            boolean documentOnly;
            if (secureRequiredType instanceof TLRPC.TL_secureRequiredType) {
                requiredType = (TLRPC.TL_secureRequiredType) secureRequiredType;
                if (requiredType.type instanceof TLRPC.TL_secureValueTypePhone
                        || requiredType.type instanceof TLRPC.TL_secureValueTypeEmail) {
                    documentTypes = null;
                    documentOnly = false;
                } else if (requiredType.type instanceof TLRPC.TL_secureValueTypePersonalDetails) {
                    if (separatePersonal) {
                        documentTypes = null;
                    } else {
                        documentTypes = personalDocuments;
                    }
                    documentOnly = false;
                } else if (requiredType.type instanceof TLRPC.TL_secureValueTypeAddress) {
                    if (separateAddress) {
                        documentTypes = null;
                    } else {
                        documentTypes = addressDocuments;
                    }
                    documentOnly = false;
                } else if (separatePersonal && isPersonalDocument(requiredType.type)) {
                    documentTypes = new ArrayList<>();
                    documentTypes.add(requiredType);
                    requiredType = new TLRPC.TL_secureRequiredType();
                    requiredType.type = new TLRPC.TL_secureValueTypePersonalDetails();
                    documentOnly = true;
                } else if (separateAddress && isAddressDocument(requiredType.type)) {
                    documentTypes = new ArrayList<>();
                    documentTypes.add(requiredType);
                    requiredType = new TLRPC.TL_secureRequiredType();
                    requiredType.type = new TLRPC.TL_secureValueTypeAddress();
                    documentOnly = true;
                } else {
                    continue;
                }
            } else if (secureRequiredType instanceof TLRPC.TL_secureRequiredTypeOneOf) {
                TLRPC.TL_secureRequiredTypeOneOf requiredTypeOneOf = (TLRPC.TL_secureRequiredTypeOneOf) secureRequiredType;
                if (requiredTypeOneOf.types.isEmpty()) {
                    continue;
                }
                TLRPC.SecureRequiredType innerType = requiredTypeOneOf.types.get(0);
                if (!(innerType instanceof TLRPC.TL_secureRequiredType)) {
                    continue;
                }
                requiredType = (TLRPC.TL_secureRequiredType) innerType;

                if (separatePersonal && isPersonalDocument(requiredType.type)
                        || separateAddress && isAddressDocument(requiredType.type)) {
                    documentTypes = new ArrayList<>();
                    for (int b = 0, size2 = requiredTypeOneOf.types.size(); b < size2; b++) {
                        innerType = requiredTypeOneOf.types.get(b);
                        if (!(innerType instanceof TLRPC.TL_secureRequiredType)) {
                            continue;
                        }
                        documentTypes.add((TLRPC.TL_secureRequiredType) innerType);
                    }
                    if (isPersonalDocument(requiredType.type)) {
                        requiredType = new TLRPC.TL_secureRequiredType();
                        requiredType.type = new TLRPC.TL_secureValueTypePersonalDetails();
                    } else {
                        requiredType = new TLRPC.TL_secureRequiredType();
                        requiredType.type = new TLRPC.TL_secureValueTypeAddress();
                    }

                    documentOnly = true;
                } else {
                    continue;
                }
            } else {
                continue;
            }
            addField(context, requiredType, documentTypes, documentOnly, a == size - 1);
        }
    }

    if (botUser != null) {
        bottomCell = new TextInfoPrivacyCell(context);
        bottomCell.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider_bottom,
                Theme.key_windowBackgroundGrayShadow));
        bottomCell.setLinkTextColorKey(Theme.key_windowBackgroundWhiteGrayText4);
        if (!TextUtils.isEmpty(currentForm.privacy_policy_url)) {
            String str2 = LocaleController.formatString("PassportPolicy", R.string.PassportPolicy,
                    UserObject.getFirstName(botUser), botUser.username);
            SpannableStringBuilder text = new SpannableStringBuilder(str2);
            int index1 = str2.indexOf('*');
            int index2 = str2.lastIndexOf('*');
            if (index1 != -1 && index2 != -1) {
                bottomCell.getTextView().setMovementMethod(new AndroidUtilities.LinkMovementMethodMy());
                text.replace(index2, index2 + 1, "");
                text.replace(index1, index1 + 1, "");
                text.setSpan(new LinkSpan(), index1, index2 - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            bottomCell.setText(text);
        } else {
            bottomCell.setText(AndroidUtilities.replaceTags(LocaleController.formatString("PassportNoPolicy",
                    R.string.PassportNoPolicy, UserObject.getFirstName(botUser), botUser.username)));
        }
        bottomCell.getTextView().setHighlightColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText4));
        bottomCell.getTextView().setGravity(Gravity.CENTER_HORIZONTAL);
        linearLayout2.addView(bottomCell,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    }

    bottomLayout = new FrameLayout(context);
    bottomLayout.setBackgroundDrawable(
            Theme.createSelectorWithBackgroundDrawable(Theme.getColor(Theme.key_passport_authorizeBackground),
                    Theme.getColor(Theme.key_passport_authorizeBackgroundSelected)));
    frameLayout.addView(bottomLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.BOTTOM));
    bottomLayout.setOnClickListener(view -> {

        class ValueToSend {
            TLRPC.TL_secureValue value;
            boolean selfie_required;
            boolean translation_required;

            public ValueToSend(TLRPC.TL_secureValue v, boolean s, boolean t) {
                value = v;
                selfie_required = s;
                translation_required = t;
            }
        }

        ArrayList<ValueToSend> valuesToSend = new ArrayList<>();
        for (int a = 0, size = currentForm.required_types.size(); a < size; a++) {

            TLRPC.TL_secureRequiredType requiredType;

            TLRPC.SecureRequiredType secureRequiredType = currentForm.required_types.get(a);
            if (secureRequiredType instanceof TLRPC.TL_secureRequiredType) {
                requiredType = (TLRPC.TL_secureRequiredType) secureRequiredType;
            } else if (secureRequiredType instanceof TLRPC.TL_secureRequiredTypeOneOf) {
                TLRPC.TL_secureRequiredTypeOneOf requiredTypeOneOf = (TLRPC.TL_secureRequiredTypeOneOf) secureRequiredType;
                if (requiredTypeOneOf.types.isEmpty()) {
                    continue;
                }
                secureRequiredType = requiredTypeOneOf.types.get(0);
                if (!(secureRequiredType instanceof TLRPC.TL_secureRequiredType)) {
                    continue;
                }
                requiredType = (TLRPC.TL_secureRequiredType) secureRequiredType;

                for (int b = 0, size2 = requiredTypeOneOf.types.size(); b < size2; b++) {
                    secureRequiredType = requiredTypeOneOf.types.get(b);
                    if (!(secureRequiredType instanceof TLRPC.TL_secureRequiredType)) {
                        continue;
                    }
                    TLRPC.TL_secureRequiredType innerType = (TLRPC.TL_secureRequiredType) secureRequiredType;
                    if (getValueByType(innerType, true) != null) {
                        requiredType = innerType;
                        break;
                    }
                }
            } else {
                continue;
            }

            TLRPC.TL_secureValue value = getValueByType(requiredType, true);
            if (value == null) {
                Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE);
                if (v != null) {
                    v.vibrate(200);
                }
                AndroidUtilities.shakeView(getViewByType(requiredType), 2, 0);
                return;
            }
            String key = getNameForType(requiredType.type);
            HashMap<String, String> errors = errorsMap.get(key);
            if (errors != null && !errors.isEmpty()) {
                Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE);
                if (v != null) {
                    v.vibrate(200);
                }
                AndroidUtilities.shakeView(getViewByType(requiredType), 2, 0);
                return;
            }
            valuesToSend.add(
                    new ValueToSend(value, requiredType.selfie_required, requiredType.translation_required));
        }
        showEditDoneProgress(false, true);
        TLRPC.TL_account_acceptAuthorization req = new TLRPC.TL_account_acceptAuthorization();
        req.bot_id = currentBotId;
        req.scope = currentScope;
        req.public_key = currentPublicKey;
        JSONObject jsonObject = new JSONObject();
        for (int a = 0, size = valuesToSend.size(); a < size; a++) {
            ValueToSend valueToSend = valuesToSend.get(a);
            TLRPC.TL_secureValue secureValue = valueToSend.value;

            JSONObject data = new JSONObject();

            if (secureValue.plain_data != null) {
                if (secureValue.plain_data instanceof TLRPC.TL_securePlainEmail) {
                    TLRPC.TL_securePlainEmail securePlainEmail = (TLRPC.TL_securePlainEmail) secureValue.plain_data;
                } else if (secureValue.plain_data instanceof TLRPC.TL_securePlainPhone) {
                    TLRPC.TL_securePlainPhone securePlainPhone = (TLRPC.TL_securePlainPhone) secureValue.plain_data;
                }
            } else {
                try {
                    JSONObject result = new JSONObject();
                    if (secureValue.data != null) {
                        byte[] decryptedSecret = decryptValueSecret(secureValue.data.secret,
                                secureValue.data.data_hash);

                        data.put("data_hash",
                                Base64.encodeToString(secureValue.data.data_hash, Base64.NO_WRAP));
                        data.put("secret", Base64.encodeToString(decryptedSecret, Base64.NO_WRAP));

                        result.put("data", data);
                    }
                    if (!secureValue.files.isEmpty()) {
                        JSONArray files = new JSONArray();
                        for (int b = 0, size2 = secureValue.files.size(); b < size2; b++) {
                            TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) secureValue.files.get(b);
                            byte[] decryptedSecret = decryptValueSecret(secureFile.secret,
                                    secureFile.file_hash);

                            JSONObject file = new JSONObject();
                            file.put("file_hash", Base64.encodeToString(secureFile.file_hash, Base64.NO_WRAP));
                            file.put("secret", Base64.encodeToString(decryptedSecret, Base64.NO_WRAP));
                            files.put(file);
                        }
                        result.put("files", files);
                    }
                    if (secureValue.front_side instanceof TLRPC.TL_secureFile) {
                        TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) secureValue.front_side;
                        byte[] decryptedSecret = decryptValueSecret(secureFile.secret, secureFile.file_hash);

                        JSONObject front = new JSONObject();
                        front.put("file_hash", Base64.encodeToString(secureFile.file_hash, Base64.NO_WRAP));
                        front.put("secret", Base64.encodeToString(decryptedSecret, Base64.NO_WRAP));
                        result.put("front_side", front);
                    }
                    if (secureValue.reverse_side instanceof TLRPC.TL_secureFile) {
                        TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) secureValue.reverse_side;
                        byte[] decryptedSecret = decryptValueSecret(secureFile.secret, secureFile.file_hash);

                        JSONObject reverse = new JSONObject();
                        reverse.put("file_hash", Base64.encodeToString(secureFile.file_hash, Base64.NO_WRAP));
                        reverse.put("secret", Base64.encodeToString(decryptedSecret, Base64.NO_WRAP));
                        result.put("reverse_side", reverse);
                    }
                    if (valueToSend.selfie_required && secureValue.selfie instanceof TLRPC.TL_secureFile) {
                        TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) secureValue.selfie;
                        byte[] decryptedSecret = decryptValueSecret(secureFile.secret, secureFile.file_hash);

                        JSONObject selfie = new JSONObject();
                        selfie.put("file_hash", Base64.encodeToString(secureFile.file_hash, Base64.NO_WRAP));
                        selfie.put("secret", Base64.encodeToString(decryptedSecret, Base64.NO_WRAP));
                        result.put("selfie", selfie);
                    }
                    if (valueToSend.translation_required && !secureValue.translation.isEmpty()) {
                        JSONArray translation = new JSONArray();
                        for (int b = 0, size2 = secureValue.translation.size(); b < size2; b++) {
                            TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) secureValue.translation
                                    .get(b);
                            byte[] decryptedSecret = decryptValueSecret(secureFile.secret,
                                    secureFile.file_hash);

                            JSONObject file = new JSONObject();
                            file.put("file_hash", Base64.encodeToString(secureFile.file_hash, Base64.NO_WRAP));
                            file.put("secret", Base64.encodeToString(decryptedSecret, Base64.NO_WRAP));
                            translation.put(file);
                        }
                        result.put("translation", translation);
                    }
                    jsonObject.put(getNameForType(secureValue.type), result);
                } catch (Exception ignore) {

                }
            }

            TLRPC.TL_secureValueHash hash = new TLRPC.TL_secureValueHash();
            hash.type = secureValue.type;
            hash.hash = secureValue.hash;
            req.value_hashes.add(hash);
        }
        JSONObject result = new JSONObject();
        try {
            result.put("secure_data", jsonObject);
        } catch (Exception ignore) {

        }
        if (currentPayload != null) {
            try {
                result.put("payload", currentPayload);
            } catch (Exception ignore) {

            }
        }
        if (currentNonce != null) {
            try {
                result.put("nonce", currentNonce);
            } catch (Exception ignore) {

            }
        }
        String json = result.toString();

        EncryptionResult encryptionResult = encryptData(AndroidUtilities.getStringBytes(json));

        req.credentials = new TLRPC.TL_secureCredentialsEncrypted();
        req.credentials.hash = encryptionResult.fileHash;
        req.credentials.data = encryptionResult.encryptedData;
        try {
            String key = currentPublicKey.replaceAll("\\n", "").replace("-----BEGIN PUBLIC KEY-----", "")
                    .replace("-----END PUBLIC KEY-----", "");
            KeyFactory kf = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec keySpecX509 = new X509EncodedKeySpec(Base64.decode(key, Base64.DEFAULT));
            RSAPublicKey pubKey = (RSAPublicKey) kf.generatePublic(keySpecX509);

            Cipher c = Cipher.getInstance("RSA/NONE/OAEPWithSHA1AndMGF1Padding", "BC");
            c.init(Cipher.ENCRYPT_MODE, pubKey);
            req.credentials.secret = c.doFinal(encryptionResult.decrypyedFileSecret);
        } catch (Exception e) {
            FileLog.e(e);
        }
        int reqId = ConnectionsManager.getInstance(currentAccount).sendRequest(req,
                (response, error) -> AndroidUtilities.runOnUIThread(() -> {
                    if (error == null) {
                        ignoreOnFailure = true;
                        callCallback(true);
                        finishFragment();
                    } else {
                        showEditDoneProgress(false, false);
                        if ("APP_VERSION_OUTDATED".equals(error.text)) {
                            AlertsCreator.showUpdateAppAlert(getParentActivity(),
                                    LocaleController.getString("UpdateAppAlert", R.string.UpdateAppAlert),
                                    true);
                        } else {
                            showAlertWithText(LocaleController.getString("AppName", R.string.AppName),
                                    error.text);
                        }
                    }
                }));
        ConnectionsManager.getInstance(currentAccount).bindRequestToGuid(reqId, classGuid);
    });

    acceptTextView = new TextView(context);
    acceptTextView.setCompoundDrawablePadding(AndroidUtilities.dp(8));
    acceptTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.authorize, 0, 0, 0);
    acceptTextView.setTextColor(Theme.getColor(Theme.key_passport_authorizeText));
    acceptTextView.setText(LocaleController.getString("PassportAuthorize", R.string.PassportAuthorize));
    acceptTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    acceptTextView.setGravity(Gravity.CENTER);
    acceptTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    bottomLayout.addView(acceptTextView,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.CENTER));

    progressViewButton = new ContextProgressView(context, 0);
    progressViewButton.setVisibility(View.INVISIBLE);
    bottomLayout.addView(progressViewButton,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));

    View shadow = new View(context);
    shadow.setBackgroundResource(R.drawable.header_shadow_reverse);
    frameLayout.addView(shadow,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 3, Gravity.LEFT | Gravity.BOTTOM, 0, 0, 0, 48));
}