ConversationFragment.java

   1package eu.siacs.conversations.ui;
   2
   3import android.Manifest;
   4import android.annotation.SuppressLint;
   5import android.app.Activity;
   6import android.app.FragmentManager;
   7import android.content.SharedPreferences;
   8import android.content.pm.PackageManager;
   9import android.databinding.DataBindingUtil;
  10import android.net.Uri;
  11import android.os.Build;
  12import android.preference.PreferenceManager;
  13import android.provider.MediaStore;
  14import android.support.annotation.IdRes;
  15import android.support.annotation.NonNull;
  16import android.support.annotation.StringRes;
  17import android.support.v7.app.AlertDialog;
  18import android.app.Fragment;
  19import android.app.PendingIntent;
  20import android.content.Context;
  21import android.content.DialogInterface;
  22import android.content.Intent;
  23import android.content.IntentSender.SendIntentException;
  24import android.os.Bundle;
  25import android.os.Handler;
  26import android.os.SystemClock;
  27import android.support.v13.view.inputmethod.InputConnectionCompat;
  28import android.support.v13.view.inputmethod.InputContentInfoCompat;
  29import android.text.Editable;
  30import android.text.TextUtils;
  31import android.util.Log;
  32import android.view.ContextMenu;
  33import android.view.ContextMenu.ContextMenuInfo;
  34import android.view.Gravity;
  35import android.view.LayoutInflater;
  36import android.view.Menu;
  37import android.view.MenuInflater;
  38import android.view.MenuItem;
  39import android.view.MotionEvent;
  40import android.view.View;
  41import android.view.View.OnClickListener;
  42import android.view.ViewGroup;
  43import android.view.inputmethod.EditorInfo;
  44import android.view.inputmethod.InputMethodManager;
  45import android.widget.AbsListView;
  46import android.widget.AbsListView.OnScrollListener;
  47import android.widget.AdapterView;
  48import android.widget.AdapterView.AdapterContextMenuInfo;
  49import android.widget.CheckBox;
  50import android.widget.ListView;
  51import android.widget.PopupMenu;
  52import android.widget.TextView.OnEditorActionListener;
  53import android.widget.Toast;
  54
  55import com.google.common.base.Optional;
  56
  57import java.util.ArrayList;
  58import java.util.Arrays;
  59import java.util.Collections;
  60import java.util.HashSet;
  61import java.util.Iterator;
  62import java.util.List;
  63import java.util.Set;
  64import java.util.UUID;
  65import java.util.concurrent.atomic.AtomicBoolean;
  66
  67import eu.siacs.conversations.Config;
  68import eu.siacs.conversations.R;
  69import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  70import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
  71import eu.siacs.conversations.databinding.FragmentConversationBinding;
  72import eu.siacs.conversations.entities.Account;
  73import eu.siacs.conversations.entities.Blockable;
  74import eu.siacs.conversations.entities.Contact;
  75import eu.siacs.conversations.entities.Conversation;
  76import eu.siacs.conversations.entities.Conversational;
  77import eu.siacs.conversations.entities.DownloadableFile;
  78import eu.siacs.conversations.entities.Message;
  79import eu.siacs.conversations.entities.MucOptions;
  80import eu.siacs.conversations.entities.MucOptions.User;
  81import eu.siacs.conversations.entities.Presence;
  82import eu.siacs.conversations.entities.ReadByMarker;
  83import eu.siacs.conversations.entities.Transferable;
  84import eu.siacs.conversations.entities.TransferablePlaceholder;
  85import eu.siacs.conversations.http.HttpDownloadConnection;
  86import eu.siacs.conversations.persistance.FileBackend;
  87import eu.siacs.conversations.services.MessageArchiveService;
  88import eu.siacs.conversations.services.QuickConversationsService;
  89import eu.siacs.conversations.services.XmppConnectionService;
  90import eu.siacs.conversations.ui.adapter.MediaPreviewAdapter;
  91import eu.siacs.conversations.ui.adapter.MessageAdapter;
  92import eu.siacs.conversations.ui.util.ActivityResult;
  93import eu.siacs.conversations.ui.util.Attachment;
  94import eu.siacs.conversations.ui.util.ConversationMenuConfigurator;
  95import eu.siacs.conversations.ui.util.DateSeparator;
  96import eu.siacs.conversations.ui.util.EditMessageActionModeCallback;
  97import eu.siacs.conversations.ui.util.ListViewUtils;
  98import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
  99import eu.siacs.conversations.ui.util.MucDetailsContextMenuHelper;
 100import eu.siacs.conversations.ui.util.PendingItem;
 101import eu.siacs.conversations.ui.util.PresenceSelector;
 102import eu.siacs.conversations.ui.util.ScrollState;
 103import eu.siacs.conversations.ui.util.SendButtonAction;
 104import eu.siacs.conversations.ui.util.SendButtonTool;
 105import eu.siacs.conversations.ui.util.ShareUtil;
 106import eu.siacs.conversations.ui.util.ViewUtil;
 107import eu.siacs.conversations.ui.widget.EditMessage;
 108import eu.siacs.conversations.utils.AccountUtils;
 109import eu.siacs.conversations.utils.Compatibility;
 110import eu.siacs.conversations.utils.GeoHelper;
 111import eu.siacs.conversations.utils.MessageUtils;
 112import eu.siacs.conversations.utils.NickValidityChecker;
 113import eu.siacs.conversations.utils.Patterns;
 114import eu.siacs.conversations.utils.QuickLoader;
 115import eu.siacs.conversations.utils.StylingHelper;
 116import eu.siacs.conversations.utils.TimeFrameUtils;
 117import eu.siacs.conversations.utils.UIHelper;
 118import eu.siacs.conversations.xmpp.XmppConnection;
 119import eu.siacs.conversations.xmpp.chatstate.ChatState;
 120import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection;
 121import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
 122import eu.siacs.conversations.xmpp.jingle.JingleFileTransferConnection;
 123import eu.siacs.conversations.xmpp.jingle.Media;
 124import eu.siacs.conversations.xmpp.jingle.OngoingRtpSession;
 125import eu.siacs.conversations.xmpp.jingle.RtpCapability;
 126import eu.siacs.conversations.xmpp.Jid;
 127
 128import static eu.siacs.conversations.ui.XmppActivity.EXTRA_ACCOUNT;
 129import static eu.siacs.conversations.ui.XmppActivity.REQUEST_INVITE_TO_CONVERSATION;
 130import static eu.siacs.conversations.ui.util.SoftKeyboardUtils.hideSoftKeyboard;
 131import static eu.siacs.conversations.utils.PermissionUtils.allGranted;
 132import static eu.siacs.conversations.utils.PermissionUtils.getFirstDenied;
 133import static eu.siacs.conversations.utils.PermissionUtils.writeGranted;
 134
 135
 136public class ConversationFragment extends XmppFragment implements EditMessage.KeyboardListener, MessageAdapter.OnContactPictureLongClicked, MessageAdapter.OnContactPictureClicked {
 137
 138
 139    public static final int REQUEST_SEND_MESSAGE = 0x0201;
 140    public static final int REQUEST_DECRYPT_PGP = 0x0202;
 141    public static final int REQUEST_ENCRYPT_MESSAGE = 0x0207;
 142    public static final int REQUEST_TRUST_KEYS_TEXT = 0x0208;
 143    public static final int REQUEST_TRUST_KEYS_ATTACHMENTS = 0x0209;
 144    public static final int REQUEST_START_DOWNLOAD = 0x0210;
 145    public static final int REQUEST_ADD_EDITOR_CONTENT = 0x0211;
 146    public static final int REQUEST_COMMIT_ATTACHMENTS = 0x0212;
 147    public static final int REQUEST_START_AUDIO_CALL = 0x213;
 148    public static final int REQUEST_START_VIDEO_CALL = 0x214;
 149    public static final int ATTACHMENT_CHOICE_CHOOSE_IMAGE = 0x0301;
 150    public static final int ATTACHMENT_CHOICE_TAKE_PHOTO = 0x0302;
 151    public static final int ATTACHMENT_CHOICE_CHOOSE_FILE = 0x0303;
 152    public static final int ATTACHMENT_CHOICE_RECORD_VOICE = 0x0304;
 153    public static final int ATTACHMENT_CHOICE_LOCATION = 0x0305;
 154    public static final int ATTACHMENT_CHOICE_INVALID = 0x0306;
 155    public static final int ATTACHMENT_CHOICE_RECORD_VIDEO = 0x0307;
 156
 157    public static final String RECENTLY_USED_QUICK_ACTION = "recently_used_quick_action";
 158    public static final String STATE_CONVERSATION_UUID = ConversationFragment.class.getName() + ".uuid";
 159    public static final String STATE_SCROLL_POSITION = ConversationFragment.class.getName() + ".scroll_position";
 160    public static final String STATE_PHOTO_URI = ConversationFragment.class.getName() + ".media_previews";
 161    public static final String STATE_MEDIA_PREVIEWS = ConversationFragment.class.getName() + ".take_photo_uri";
 162    private static final String STATE_LAST_MESSAGE_UUID = "state_last_message_uuid";
 163
 164    private final List<Message> messageList = new ArrayList<>();
 165    private final PendingItem<ActivityResult> postponedActivityResult = new PendingItem<>();
 166    private final PendingItem<String> pendingConversationsUuid = new PendingItem<>();
 167    private final PendingItem<ArrayList<Attachment>> pendingMediaPreviews = new PendingItem<>();
 168    private final PendingItem<Bundle> pendingExtras = new PendingItem<>();
 169    private final PendingItem<Uri> pendingTakePhotoUri = new PendingItem<>();
 170    private final PendingItem<ScrollState> pendingScrollState = new PendingItem<>();
 171    private final PendingItem<String> pendingLastMessageUuid = new PendingItem<>();
 172    private final PendingItem<Message> pendingMessage = new PendingItem<>();
 173    public Uri mPendingEditorContent = null;
 174    protected MessageAdapter messageListAdapter;
 175    private MediaPreviewAdapter mediaPreviewAdapter;
 176    private String lastMessageUuid = null;
 177    private Conversation conversation;
 178    private FragmentConversationBinding binding;
 179    private Toast messageLoaderToast;
 180    private ConversationsActivity activity;
 181    private boolean reInitRequiredOnStart = true;
 182    private OnClickListener clickToMuc = new OnClickListener() {
 183
 184        @Override
 185        public void onClick(View v) {
 186            Intent intent = new Intent(getActivity(), ConferenceDetailsActivity.class);
 187            intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
 188            intent.putExtra("uuid", conversation.getUuid());
 189            startActivity(intent);
 190        }
 191    };
 192    private OnClickListener leaveMuc = new OnClickListener() {
 193
 194        @Override
 195        public void onClick(View v) {
 196            activity.xmppConnectionService.archiveConversation(conversation);
 197        }
 198    };
 199    private OnClickListener joinMuc = new OnClickListener() {
 200
 201        @Override
 202        public void onClick(View v) {
 203            activity.xmppConnectionService.joinMuc(conversation);
 204        }
 205    };
 206
 207    private OnClickListener acceptJoin = new OnClickListener() {
 208        @Override
 209        public void onClick(View v) {
 210            conversation.setAttribute("accept_non_anonymous", true);
 211            activity.xmppConnectionService.updateConversation(conversation);
 212            activity.xmppConnectionService.joinMuc(conversation);
 213        }
 214    };
 215
 216    private OnClickListener enterPassword = new OnClickListener() {
 217
 218        @Override
 219        public void onClick(View v) {
 220            MucOptions muc = conversation.getMucOptions();
 221            String password = muc.getPassword();
 222            if (password == null) {
 223                password = "";
 224            }
 225            activity.quickPasswordEdit(password, value -> {
 226                activity.xmppConnectionService.providePasswordForMuc(conversation, value);
 227                return null;
 228            });
 229        }
 230    };
 231    private OnScrollListener mOnScrollListener = new OnScrollListener() {
 232
 233        @Override
 234        public void onScrollStateChanged(AbsListView view, int scrollState) {
 235            if (AbsListView.OnScrollListener.SCROLL_STATE_IDLE == scrollState) {
 236                fireReadEvent();
 237            }
 238        }
 239
 240        @Override
 241        public void onScroll(final AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
 242            toggleScrollDownButton(view);
 243            synchronized (ConversationFragment.this.messageList) {
 244                if (firstVisibleItem < 5 && conversation != null && conversation.messagesLoaded.compareAndSet(true, false) && messageList.size() > 0) {
 245                    long timestamp;
 246                    if (messageList.get(0).getType() == Message.TYPE_STATUS && messageList.size() >= 2) {
 247                        timestamp = messageList.get(1).getTimeSent();
 248                    } else {
 249                        timestamp = messageList.get(0).getTimeSent();
 250                    }
 251                    activity.xmppConnectionService.loadMoreMessages(conversation, timestamp, new XmppConnectionService.OnMoreMessagesLoaded() {
 252                        @Override
 253                        public void onMoreMessagesLoaded(final int c, final Conversation conversation) {
 254                            if (ConversationFragment.this.conversation != conversation) {
 255                                conversation.messagesLoaded.set(true);
 256                                return;
 257                            }
 258                            runOnUiThread(() -> {
 259                                synchronized (messageList) {
 260                                    final int oldPosition = binding.messagesView.getFirstVisiblePosition();
 261                                    Message message = null;
 262                                    int childPos;
 263                                    for (childPos = 0; childPos + oldPosition < messageList.size(); ++childPos) {
 264                                        message = messageList.get(oldPosition + childPos);
 265                                        if (message.getType() != Message.TYPE_STATUS) {
 266                                            break;
 267                                        }
 268                                    }
 269                                    final String uuid = message != null ? message.getUuid() : null;
 270                                    View v = binding.messagesView.getChildAt(childPos);
 271                                    final int pxOffset = (v == null) ? 0 : v.getTop();
 272                                    ConversationFragment.this.conversation.populateWithMessages(ConversationFragment.this.messageList);
 273                                    try {
 274                                        updateStatusMessages();
 275                                    } catch (IllegalStateException e) {
 276                                        Log.d(Config.LOGTAG, "caught illegal state exception while updating status messages");
 277                                    }
 278                                    messageListAdapter.notifyDataSetChanged();
 279                                    int pos = Math.max(getIndexOf(uuid, messageList), 0);
 280                                    binding.messagesView.setSelectionFromTop(pos, pxOffset);
 281                                    if (messageLoaderToast != null) {
 282                                        messageLoaderToast.cancel();
 283                                    }
 284                                    conversation.messagesLoaded.set(true);
 285                                }
 286                            });
 287                        }
 288
 289                        @Override
 290                        public void informUser(final int resId) {
 291
 292                            runOnUiThread(() -> {
 293                                if (messageLoaderToast != null) {
 294                                    messageLoaderToast.cancel();
 295                                }
 296                                if (ConversationFragment.this.conversation != conversation) {
 297                                    return;
 298                                }
 299                                messageLoaderToast = Toast.makeText(view.getContext(), resId, Toast.LENGTH_LONG);
 300                                messageLoaderToast.show();
 301                            });
 302
 303                        }
 304                    });
 305
 306                }
 307            }
 308        }
 309    };
 310    private EditMessage.OnCommitContentListener mEditorContentListener = new EditMessage.OnCommitContentListener() {
 311        @Override
 312        public boolean onCommitContent(InputContentInfoCompat inputContentInfo, int flags, Bundle opts, String[] contentMimeTypes) {
 313            // try to get permission to read the image, if applicable
 314            if ((flags & InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION) != 0) {
 315                try {
 316                    inputContentInfo.requestPermission();
 317                } catch (Exception e) {
 318                    Log.e(Config.LOGTAG, "InputContentInfoCompat#requestPermission() failed.", e);
 319                    Toast.makeText(getActivity(), activity.getString(R.string.no_permission_to_access_x, inputContentInfo.getDescription()), Toast.LENGTH_LONG
 320                    ).show();
 321                    return false;
 322                }
 323            }
 324            if (hasPermissions(REQUEST_ADD_EDITOR_CONTENT, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
 325                attachEditorContentToConversation(inputContentInfo.getContentUri());
 326            } else {
 327                mPendingEditorContent = inputContentInfo.getContentUri();
 328            }
 329            return true;
 330        }
 331    };
 332    private Message selectedMessage;
 333    private OnClickListener mEnableAccountListener = new OnClickListener() {
 334        @Override
 335        public void onClick(View v) {
 336            final Account account = conversation == null ? null : conversation.getAccount();
 337            if (account != null) {
 338                account.setOption(Account.OPTION_DISABLED, false);
 339                activity.xmppConnectionService.updateAccount(account);
 340            }
 341        }
 342    };
 343    private OnClickListener mUnblockClickListener = new OnClickListener() {
 344        @Override
 345        public void onClick(final View v) {
 346            v.post(() -> v.setVisibility(View.INVISIBLE));
 347            if (conversation.isDomainBlocked()) {
 348                BlockContactDialog.show(activity, conversation);
 349            } else {
 350                unblockConversation(conversation);
 351            }
 352        }
 353    };
 354    private OnClickListener mBlockClickListener = this::showBlockSubmenu;
 355    private OnClickListener mAddBackClickListener = new OnClickListener() {
 356
 357        @Override
 358        public void onClick(View v) {
 359            final Contact contact = conversation == null ? null : conversation.getContact();
 360            if (contact != null) {
 361                activity.xmppConnectionService.createContact(contact, true);
 362                activity.switchToContactDetails(contact);
 363            }
 364        }
 365    };
 366    private View.OnLongClickListener mLongPressBlockListener = this::showBlockSubmenu;
 367    private OnClickListener mAllowPresenceSubscription = new OnClickListener() {
 368        @Override
 369        public void onClick(View v) {
 370            final Contact contact = conversation == null ? null : conversation.getContact();
 371            if (contact != null) {
 372                activity.xmppConnectionService.sendPresencePacket(contact.getAccount(),
 373                        activity.xmppConnectionService.getPresenceGenerator()
 374                                .sendPresenceUpdatesTo(contact));
 375                hideSnackbar();
 376            }
 377        }
 378    };
 379    protected OnClickListener clickToDecryptListener = new OnClickListener() {
 380
 381        @Override
 382        public void onClick(View v) {
 383            PendingIntent pendingIntent = conversation.getAccount().getPgpDecryptionService().getPendingIntent();
 384            if (pendingIntent != null) {
 385                try {
 386                    getActivity().startIntentSenderForResult(pendingIntent.getIntentSender(),
 387                            REQUEST_DECRYPT_PGP,
 388                            null,
 389                            0,
 390                            0,
 391                            0);
 392                } catch (SendIntentException e) {
 393                    Toast.makeText(getActivity(), R.string.unable_to_connect_to_keychain, Toast.LENGTH_SHORT).show();
 394                    conversation.getAccount().getPgpDecryptionService().continueDecryption(true);
 395                }
 396            }
 397            updateSnackBar(conversation);
 398        }
 399    };
 400    private AtomicBoolean mSendingPgpMessage = new AtomicBoolean(false);
 401    private OnEditorActionListener mEditorActionListener = (v, actionId, event) -> {
 402        if (actionId == EditorInfo.IME_ACTION_SEND) {
 403            InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
 404            if (imm != null && imm.isFullscreenMode()) {
 405                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
 406            }
 407            sendMessage();
 408            return true;
 409        } else {
 410            return false;
 411        }
 412    };
 413    private OnClickListener mScrollButtonListener = new OnClickListener() {
 414
 415        @Override
 416        public void onClick(View v) {
 417            stopScrolling();
 418            setSelection(binding.messagesView.getCount() - 1, true);
 419        }
 420    };
 421    private OnClickListener mSendButtonListener = new OnClickListener() {
 422
 423        @Override
 424        public void onClick(View v) {
 425            Object tag = v.getTag();
 426            if (tag instanceof SendButtonAction) {
 427                SendButtonAction action = (SendButtonAction) tag;
 428                switch (action) {
 429                    case TAKE_PHOTO:
 430                    case RECORD_VIDEO:
 431                    case SEND_LOCATION:
 432                    case RECORD_VOICE:
 433                    case CHOOSE_PICTURE:
 434                        attachFile(action.toChoice());
 435                        break;
 436                    case CANCEL:
 437                        if (conversation != null) {
 438                            if (conversation.setCorrectingMessage(null)) {
 439                                binding.textinput.setText("");
 440                                binding.textinput.append(conversation.getDraftMessage());
 441                                conversation.setDraftMessage(null);
 442                            } else if (conversation.getMode() == Conversation.MODE_MULTI) {
 443                                conversation.setNextCounterpart(null);
 444                                binding.textinput.setText("");
 445                            } else {
 446                                binding.textinput.setText("");
 447                            }
 448                            updateChatMsgHint();
 449                            updateSendButton();
 450                            updateEditablity();
 451                        }
 452                        break;
 453                    default:
 454                        sendMessage();
 455                }
 456            } else {
 457                sendMessage();
 458            }
 459        }
 460    };
 461    private int completionIndex = 0;
 462    private int lastCompletionLength = 0;
 463    private String incomplete;
 464    private int lastCompletionCursor;
 465    private boolean firstWord = false;
 466    private Message mPendingDownloadableMessage;
 467
 468    private static ConversationFragment findConversationFragment(Activity activity) {
 469        Fragment fragment = activity.getFragmentManager().findFragmentById(R.id.main_fragment);
 470        if (fragment instanceof ConversationFragment) {
 471            return (ConversationFragment) fragment;
 472        }
 473        fragment = activity.getFragmentManager().findFragmentById(R.id.secondary_fragment);
 474        if (fragment instanceof ConversationFragment) {
 475            return (ConversationFragment) fragment;
 476        }
 477        return null;
 478    }
 479
 480    public static void startStopPending(Activity activity) {
 481        ConversationFragment fragment = findConversationFragment(activity);
 482        if (fragment != null) {
 483            fragment.messageListAdapter.startStopPending();
 484        }
 485    }
 486
 487    public static void downloadFile(Activity activity, Message message) {
 488        ConversationFragment fragment = findConversationFragment(activity);
 489        if (fragment != null) {
 490            fragment.startDownloadable(message);
 491        }
 492    }
 493
 494    public static void registerPendingMessage(Activity activity, Message message) {
 495        ConversationFragment fragment = findConversationFragment(activity);
 496        if (fragment != null) {
 497            fragment.pendingMessage.push(message);
 498        }
 499    }
 500
 501    public static void openPendingMessage(Activity activity) {
 502        ConversationFragment fragment = findConversationFragment(activity);
 503        if (fragment != null) {
 504            Message message = fragment.pendingMessage.pop();
 505            if (message != null) {
 506                fragment.messageListAdapter.openDownloadable(message);
 507            }
 508        }
 509    }
 510
 511    public static Conversation getConversation(Activity activity) {
 512        return getConversation(activity, R.id.secondary_fragment);
 513    }
 514
 515    private static Conversation getConversation(Activity activity, @IdRes int res) {
 516        final Fragment fragment = activity.getFragmentManager().findFragmentById(res);
 517        if (fragment != null && fragment instanceof ConversationFragment) {
 518            return ((ConversationFragment) fragment).getConversation();
 519        } else {
 520            return null;
 521        }
 522    }
 523
 524    public static ConversationFragment get(Activity activity) {
 525        FragmentManager fragmentManager = activity.getFragmentManager();
 526        Fragment fragment = fragmentManager.findFragmentById(R.id.main_fragment);
 527        if (fragment != null && fragment instanceof ConversationFragment) {
 528            return (ConversationFragment) fragment;
 529        } else {
 530            fragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
 531            return fragment != null && fragment instanceof ConversationFragment ? (ConversationFragment) fragment : null;
 532        }
 533    }
 534
 535    public static Conversation getConversationReliable(Activity activity) {
 536        final Conversation conversation = getConversation(activity, R.id.secondary_fragment);
 537        if (conversation != null) {
 538            return conversation;
 539        }
 540        return getConversation(activity, R.id.main_fragment);
 541    }
 542
 543    private static boolean scrolledToBottom(AbsListView listView) {
 544        final int count = listView.getCount();
 545        if (count == 0) {
 546            return true;
 547        } else if (listView.getLastVisiblePosition() == count - 1) {
 548            final View lastChild = listView.getChildAt(listView.getChildCount() - 1);
 549            return lastChild != null && lastChild.getBottom() <= listView.getHeight();
 550        } else {
 551            return false;
 552        }
 553    }
 554
 555    private void toggleScrollDownButton() {
 556        toggleScrollDownButton(binding.messagesView);
 557    }
 558
 559    private void toggleScrollDownButton(AbsListView listView) {
 560        if (conversation == null) {
 561            return;
 562        }
 563        if (scrolledToBottom(listView)) {
 564            lastMessageUuid = null;
 565            hideUnreadMessagesCount();
 566        } else {
 567            binding.scrollToBottomButton.setEnabled(true);
 568            binding.scrollToBottomButton.show();
 569            if (lastMessageUuid == null) {
 570                lastMessageUuid = conversation.getLatestMessage().getUuid();
 571            }
 572            if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) > 0) {
 573                binding.unreadCountCustomView.setVisibility(View.VISIBLE);
 574            }
 575        }
 576    }
 577
 578    private int getIndexOf(String uuid, List<Message> messages) {
 579        if (uuid == null) {
 580            return messages.size() - 1;
 581        }
 582        for (int i = 0; i < messages.size(); ++i) {
 583            if (uuid.equals(messages.get(i).getUuid())) {
 584                return i;
 585            } else {
 586                Message next = messages.get(i);
 587                while (next != null && next.wasMergedIntoPrevious()) {
 588                    if (uuid.equals(next.getUuid())) {
 589                        return i;
 590                    }
 591                    next = next.next();
 592                }
 593
 594            }
 595        }
 596        return -1;
 597    }
 598
 599    private ScrollState getScrollPosition() {
 600        final ListView listView = this.binding == null ? null : this.binding.messagesView;
 601        if (listView == null || listView.getCount() == 0 || listView.getLastVisiblePosition() == listView.getCount() - 1) {
 602            return null;
 603        } else {
 604            final int pos = listView.getFirstVisiblePosition();
 605            final View view = listView.getChildAt(0);
 606            if (view == null) {
 607                return null;
 608            } else {
 609                return new ScrollState(pos, view.getTop());
 610            }
 611        }
 612    }
 613
 614    private void setScrollPosition(ScrollState scrollPosition, String lastMessageUuid) {
 615        if (scrollPosition != null) {
 616
 617            this.lastMessageUuid = lastMessageUuid;
 618            if (lastMessageUuid != null) {
 619                binding.unreadCountCustomView.setUnreadCount(conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
 620            }
 621            //TODO maybe this needs a 'post'
 622            this.binding.messagesView.setSelectionFromTop(scrollPosition.position, scrollPosition.offset);
 623            toggleScrollDownButton();
 624        }
 625    }
 626
 627    private void attachLocationToConversation(Conversation conversation, Uri uri) {
 628        if (conversation == null) {
 629            return;
 630        }
 631        activity.xmppConnectionService.attachLocationToConversation(conversation, uri, new UiCallback<Message>() {
 632
 633            @Override
 634            public void success(Message message) {
 635
 636            }
 637
 638            @Override
 639            public void error(int errorCode, Message object) {
 640                //TODO show possible pgp error
 641            }
 642
 643            @Override
 644            public void userInputRequired(PendingIntent pi, Message object) {
 645
 646            }
 647        });
 648    }
 649
 650    private void attachFileToConversation(Conversation conversation, Uri uri, String type) {
 651        if (conversation == null) {
 652            return;
 653        }
 654        final Toast prepareFileToast = Toast.makeText(getActivity(), getText(R.string.preparing_file), Toast.LENGTH_LONG);
 655        prepareFileToast.show();
 656        activity.delegateUriPermissionsToService(uri);
 657        activity.xmppConnectionService.attachFileToConversation(conversation, uri, type, new UiInformableCallback<Message>() {
 658            @Override
 659            public void inform(final String text) {
 660                hidePrepareFileToast(prepareFileToast);
 661                runOnUiThread(() -> activity.replaceToast(text));
 662            }
 663
 664            @Override
 665            public void success(Message message) {
 666                runOnUiThread(() -> activity.hideToast());
 667                hidePrepareFileToast(prepareFileToast);
 668            }
 669
 670            @Override
 671            public void error(final int errorCode, Message message) {
 672                hidePrepareFileToast(prepareFileToast);
 673                runOnUiThread(() -> activity.replaceToast(getString(errorCode)));
 674
 675            }
 676
 677            @Override
 678            public void userInputRequired(PendingIntent pi, Message message) {
 679                hidePrepareFileToast(prepareFileToast);
 680            }
 681        });
 682    }
 683
 684    public void attachEditorContentToConversation(Uri uri) {
 685        mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), uri, Attachment.Type.FILE));
 686        toggleInputMethod();
 687    }
 688
 689    private void attachImageToConversation(Conversation conversation, Uri uri) {
 690        if (conversation == null) {
 691            return;
 692        }
 693        final Toast prepareFileToast = Toast.makeText(getActivity(), getText(R.string.preparing_image), Toast.LENGTH_LONG);
 694        prepareFileToast.show();
 695        activity.delegateUriPermissionsToService(uri);
 696        activity.xmppConnectionService.attachImageToConversation(conversation, uri,
 697                new UiCallback<Message>() {
 698
 699                    @Override
 700                    public void userInputRequired(PendingIntent pi, Message object) {
 701                        hidePrepareFileToast(prepareFileToast);
 702                    }
 703
 704                    @Override
 705                    public void success(Message message) {
 706                        hidePrepareFileToast(prepareFileToast);
 707                    }
 708
 709                    @Override
 710                    public void error(final int error, Message message) {
 711                        hidePrepareFileToast(prepareFileToast);
 712                        activity.runOnUiThread(() -> activity.replaceToast(getString(error)));
 713                    }
 714                });
 715    }
 716
 717    private void hidePrepareFileToast(final Toast prepareFileToast) {
 718        if (prepareFileToast != null && activity != null) {
 719            activity.runOnUiThread(prepareFileToast::cancel);
 720        }
 721    }
 722
 723    private void sendMessage() {
 724        if (mediaPreviewAdapter.hasAttachments()) {
 725            commitAttachments();
 726            return;
 727        }
 728        final Editable text = this.binding.textinput.getText();
 729        final String body = text == null ? "" : text.toString();
 730        final Conversation conversation = this.conversation;
 731        if (body.length() == 0 || conversation == null) {
 732            return;
 733        }
 734        if (conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL && trustKeysIfNeeded(REQUEST_TRUST_KEYS_TEXT)) {
 735            return;
 736        }
 737        final Message message;
 738        if (conversation.getCorrectingMessage() == null) {
 739            message = new Message(conversation, body, conversation.getNextEncryption());
 740            Message.configurePrivateMessage(message);
 741        } else {
 742            message = conversation.getCorrectingMessage();
 743            message.setBody(body);
 744            message.putEdited(message.getUuid(), message.getServerMsgId());
 745            message.setServerMsgId(null);
 746            message.setUuid(UUID.randomUUID().toString());
 747        }
 748        switch (conversation.getNextEncryption()) {
 749            case Message.ENCRYPTION_PGP:
 750                sendPgpMessage(message);
 751                break;
 752            default:
 753                sendMessage(message);
 754        }
 755    }
 756
 757    protected boolean trustKeysIfNeeded(int requestCode) {
 758        AxolotlService axolotlService = conversation.getAccount().getAxolotlService();
 759        final List<Jid> targets = axolotlService.getCryptoTargets(conversation);
 760        boolean hasUnaccepted = !conversation.getAcceptedCryptoTargets().containsAll(targets);
 761        boolean hasUndecidedOwn = !axolotlService.getKeysWithTrust(FingerprintStatus.createActiveUndecided()).isEmpty();
 762        boolean hasUndecidedContacts = !axolotlService.getKeysWithTrust(FingerprintStatus.createActiveUndecided(), targets).isEmpty();
 763        boolean hasPendingKeys = !axolotlService.findDevicesWithoutSession(conversation).isEmpty();
 764        boolean hasNoTrustedKeys = axolotlService.anyTargetHasNoTrustedKeys(targets);
 765        boolean downloadInProgress = axolotlService.hasPendingKeyFetches(targets);
 766        if (hasUndecidedOwn || hasUndecidedContacts || hasPendingKeys || hasNoTrustedKeys || hasUnaccepted || downloadInProgress) {
 767            axolotlService.createSessionsIfNeeded(conversation);
 768            Intent intent = new Intent(getActivity(), TrustKeysActivity.class);
 769            String[] contacts = new String[targets.size()];
 770            for (int i = 0; i < contacts.length; ++i) {
 771                contacts[i] = targets.get(i).toString();
 772            }
 773            intent.putExtra("contacts", contacts);
 774            intent.putExtra(EXTRA_ACCOUNT, conversation.getAccount().getJid().asBareJid().toString());
 775            intent.putExtra("conversation", conversation.getUuid());
 776            startActivityForResult(intent, requestCode);
 777            return true;
 778        } else {
 779            return false;
 780        }
 781    }
 782
 783    public void updateChatMsgHint() {
 784        final boolean multi = conversation.getMode() == Conversation.MODE_MULTI;
 785        if (conversation.getCorrectingMessage() != null) {
 786            this.binding.textInputHint.setVisibility(View.GONE);
 787            this.binding.textinput.setHint(R.string.send_corrected_message);
 788        } else if (multi && conversation.getNextCounterpart() != null) {
 789            this.binding.textinput.setHint(R.string.send_unencrypted_message);
 790            this.binding.textInputHint.setVisibility(View.VISIBLE);
 791            this.binding.textInputHint.setText(getString(
 792                    R.string.send_private_message_to,
 793                    conversation.getNextCounterpart().getResource()));
 794        } else if (multi && !conversation.getMucOptions().participating()) {
 795            this.binding.textInputHint.setVisibility(View.GONE);
 796            this.binding.textinput.setHint(R.string.you_are_not_participating);
 797        } else {
 798            this.binding.textInputHint.setVisibility(View.GONE);
 799            this.binding.textinput.setHint(UIHelper.getMessageHint(getActivity(), conversation));
 800            getActivity().invalidateOptionsMenu();
 801        }
 802    }
 803
 804    public void setupIme() {
 805        this.binding.textinput.refreshIme();
 806    }
 807
 808    private void handleActivityResult(ActivityResult activityResult) {
 809        if (activityResult.resultCode == Activity.RESULT_OK) {
 810            handlePositiveActivityResult(activityResult.requestCode, activityResult.data);
 811        } else {
 812            handleNegativeActivityResult(activityResult.requestCode);
 813        }
 814    }
 815
 816    private void handlePositiveActivityResult(int requestCode, final Intent data) {
 817        switch (requestCode) {
 818            case REQUEST_TRUST_KEYS_TEXT:
 819                sendMessage();
 820                break;
 821            case REQUEST_TRUST_KEYS_ATTACHMENTS:
 822                commitAttachments();
 823                break;
 824            case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
 825                final List<Attachment> imageUris = Attachment.extractAttachments(getActivity(), data, Attachment.Type.IMAGE);
 826                mediaPreviewAdapter.addMediaPreviews(imageUris);
 827                toggleInputMethod();
 828                break;
 829            case ATTACHMENT_CHOICE_TAKE_PHOTO:
 830                final Uri takePhotoUri = pendingTakePhotoUri.pop();
 831                if (takePhotoUri != null) {
 832                    mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), takePhotoUri, Attachment.Type.IMAGE));
 833                    toggleInputMethod();
 834                } else {
 835                    Log.d(Config.LOGTAG, "lost take photo uri. unable to to attach");
 836                }
 837                break;
 838            case ATTACHMENT_CHOICE_CHOOSE_FILE:
 839            case ATTACHMENT_CHOICE_RECORD_VIDEO:
 840            case ATTACHMENT_CHOICE_RECORD_VOICE:
 841                final Attachment.Type type = requestCode == ATTACHMENT_CHOICE_RECORD_VOICE ? Attachment.Type.RECORDING : Attachment.Type.FILE;
 842                final List<Attachment> fileUris = Attachment.extractAttachments(getActivity(), data, type);
 843                mediaPreviewAdapter.addMediaPreviews(fileUris);
 844                toggleInputMethod();
 845                break;
 846            case ATTACHMENT_CHOICE_LOCATION:
 847                double latitude = data.getDoubleExtra("latitude", 0);
 848                double longitude = data.getDoubleExtra("longitude", 0);
 849                Uri geo = Uri.parse("geo:" + String.valueOf(latitude) + "," + String.valueOf(longitude));
 850                mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), geo, Attachment.Type.LOCATION));
 851                toggleInputMethod();
 852                break;
 853            case REQUEST_INVITE_TO_CONVERSATION:
 854                XmppActivity.ConferenceInvite invite = XmppActivity.ConferenceInvite.parse(data);
 855                if (invite != null) {
 856                    if (invite.execute(activity)) {
 857                        activity.mToast = Toast.makeText(activity, R.string.creating_conference, Toast.LENGTH_LONG);
 858                        activity.mToast.show();
 859                    }
 860                }
 861                break;
 862        }
 863    }
 864
 865    private void commitAttachments() {
 866        if (!hasPermissions(REQUEST_COMMIT_ATTACHMENTS, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
 867            return;
 868        }
 869        if (conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL && trustKeysIfNeeded(REQUEST_TRUST_KEYS_ATTACHMENTS)) {
 870            return;
 871        }
 872        final List<Attachment> attachments = mediaPreviewAdapter.getAttachments();
 873        final PresenceSelector.OnPresenceSelected callback = () -> {
 874            for (Iterator<Attachment> i = attachments.iterator(); i.hasNext(); i.remove()) {
 875                final Attachment attachment = i.next();
 876                if (attachment.getType() == Attachment.Type.LOCATION) {
 877                    attachLocationToConversation(conversation, attachment.getUri());
 878                } else if (attachment.getType() == Attachment.Type.IMAGE) {
 879                    Log.d(Config.LOGTAG, "ConversationsActivity.commitAttachments() - attaching image to conversations. CHOOSE_IMAGE");
 880                    attachImageToConversation(conversation, attachment.getUri());
 881                } else {
 882                    Log.d(Config.LOGTAG, "ConversationsActivity.commitAttachments() - attaching file to conversations. CHOOSE_FILE/RECORD_VOICE/RECORD_VIDEO");
 883                    attachFileToConversation(conversation, attachment.getUri(), attachment.getMime());
 884                }
 885            }
 886            mediaPreviewAdapter.notifyDataSetChanged();
 887            toggleInputMethod();
 888        };
 889        if (conversation == null
 890                || conversation.getMode() == Conversation.MODE_MULTI
 891                || Attachment.canBeSendInband(attachments)
 892                || (conversation.getAccount().httpUploadAvailable() && FileBackend.allFilesUnderSize(getActivity(), attachments, getMaxHttpUploadSize(conversation)))) {
 893            callback.onPresenceSelected();
 894        } else {
 895            activity.selectPresence(conversation, callback);
 896        }
 897    }
 898
 899    public void toggleInputMethod() {
 900        boolean hasAttachments = mediaPreviewAdapter.hasAttachments();
 901        binding.textinput.setVisibility(hasAttachments ? View.GONE : View.VISIBLE);
 902        binding.mediaPreview.setVisibility(hasAttachments ? View.VISIBLE : View.GONE);
 903        updateSendButton();
 904    }
 905
 906    private void handleNegativeActivityResult(int requestCode) {
 907        switch (requestCode) {
 908            case ATTACHMENT_CHOICE_TAKE_PHOTO:
 909                if (pendingTakePhotoUri.clear()) {
 910                    Log.d(Config.LOGTAG, "cleared pending photo uri after negative activity result");
 911                }
 912                break;
 913        }
 914    }
 915
 916    @Override
 917    public void onActivityResult(int requestCode, int resultCode, final Intent data) {
 918        super.onActivityResult(requestCode, resultCode, data);
 919        ActivityResult activityResult = ActivityResult.of(requestCode, resultCode, data);
 920        if (activity != null && activity.xmppConnectionService != null) {
 921            handleActivityResult(activityResult);
 922        } else {
 923            this.postponedActivityResult.push(activityResult);
 924        }
 925    }
 926
 927    public void unblockConversation(final Blockable conversation) {
 928        activity.xmppConnectionService.sendUnblockRequest(conversation);
 929    }
 930
 931    @Override
 932    public void onAttach(Activity activity) {
 933        super.onAttach(activity);
 934        Log.d(Config.LOGTAG, "ConversationFragment.onAttach()");
 935        if (activity instanceof ConversationsActivity) {
 936            this.activity = (ConversationsActivity) activity;
 937        } else {
 938            throw new IllegalStateException("Trying to attach fragment to activity that is not the ConversationsActivity");
 939        }
 940    }
 941
 942    @Override
 943    public void onDetach() {
 944        super.onDetach();
 945        this.activity = null; //TODO maybe not a good idea since some callbacks really need it
 946    }
 947
 948    @Override
 949    public void onCreate(Bundle savedInstanceState) {
 950        super.onCreate(savedInstanceState);
 951        setHasOptionsMenu(true);
 952    }
 953
 954    @Override
 955    public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
 956        menuInflater.inflate(R.menu.fragment_conversation, menu);
 957        final MenuItem menuMucDetails = menu.findItem(R.id.action_muc_details);
 958        final MenuItem menuContactDetails = menu.findItem(R.id.action_contact_details);
 959        final MenuItem menuInviteContact = menu.findItem(R.id.action_invite);
 960        final MenuItem menuMute = menu.findItem(R.id.action_mute);
 961        final MenuItem menuUnmute = menu.findItem(R.id.action_unmute);
 962        final MenuItem menuCall = menu.findItem(R.id.action_call);
 963        final MenuItem menuOngoingCall = menu.findItem(R.id.action_ongoing_call);
 964        final MenuItem menuVideoCall = menu.findItem(R.id.action_video_call);
 965        final MenuItem menuTogglePinned = menu.findItem(R.id.action_toggle_pinned);
 966
 967
 968        if (conversation != null) {
 969            if (conversation.getMode() == Conversation.MODE_MULTI) {
 970                menuContactDetails.setVisible(false);
 971                menuInviteContact.setVisible(conversation.getMucOptions().canInvite());
 972                menuMucDetails.setTitle(conversation.getMucOptions().isPrivateAndNonAnonymous() ? R.string.action_muc_details : R.string.channel_details);
 973                menuCall.setVisible(false);
 974                menuOngoingCall.setVisible(false);
 975            } else {
 976                final Optional<OngoingRtpSession> ongoingRtpSession = activity.xmppConnectionService.getJingleConnectionManager().getOngoingRtpConnection(conversation.getContact());
 977                if (ongoingRtpSession.isPresent()) {
 978                    menuOngoingCall.setVisible(true);
 979                    menuCall.setVisible(false);
 980                } else {
 981                    menuOngoingCall.setVisible(false);
 982                    final RtpCapability.Capability rtpCapability = RtpCapability.check(conversation.getContact());
 983                    menuCall.setVisible(rtpCapability != RtpCapability.Capability.NONE);
 984                    menuVideoCall.setVisible(rtpCapability == RtpCapability.Capability.VIDEO);
 985                }
 986                menuContactDetails.setVisible(!this.conversation.withSelf());
 987                menuMucDetails.setVisible(false);
 988                final XmppConnectionService service = activity.xmppConnectionService;
 989                menuInviteContact.setVisible(service != null && service.findConferenceServer(conversation.getAccount()) != null);
 990            }
 991            if (conversation.isMuted()) {
 992                menuMute.setVisible(false);
 993            } else {
 994                menuUnmute.setVisible(false);
 995            }
 996            ConversationMenuConfigurator.configureAttachmentMenu(conversation, menu);
 997            ConversationMenuConfigurator.configureEncryptionMenu(conversation, menu);
 998            if (conversation.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false)) {
 999                menuTogglePinned.setTitle(R.string.remove_from_favorites);
1000            } else {
1001                menuTogglePinned.setTitle(R.string.add_to_favorites);
1002            }
1003        }
1004        super.onCreateOptionsMenu(menu, menuInflater);
1005    }
1006
1007    @Override
1008    public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
1009        this.binding = DataBindingUtil.inflate(inflater, R.layout.fragment_conversation, container, false);
1010        binding.getRoot().setOnClickListener(null); //TODO why the fuck did we do this?
1011
1012        binding.textinput.addTextChangedListener(new StylingHelper.MessageEditorStyler(binding.textinput));
1013
1014        binding.textinput.setOnEditorActionListener(mEditorActionListener);
1015        binding.textinput.setRichContentListener(new String[]{"image/*"}, mEditorContentListener);
1016
1017        binding.textSendButton.setOnClickListener(this.mSendButtonListener);
1018
1019        binding.scrollToBottomButton.setOnClickListener(this.mScrollButtonListener);
1020        binding.messagesView.setOnScrollListener(mOnScrollListener);
1021        binding.messagesView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
1022        mediaPreviewAdapter = new MediaPreviewAdapter(this);
1023        binding.mediaPreview.setAdapter(mediaPreviewAdapter);
1024        messageListAdapter = new MessageAdapter((XmppActivity) getActivity(), this.messageList);
1025        messageListAdapter.setOnContactPictureClicked(this);
1026        messageListAdapter.setOnContactPictureLongClicked(this);
1027        messageListAdapter.setOnQuoteListener(this::quoteText);
1028        binding.messagesView.setAdapter(messageListAdapter);
1029
1030        registerForContextMenu(binding.messagesView);
1031
1032        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1033            this.binding.textinput.setCustomInsertionActionModeCallback(new EditMessageActionModeCallback(this.binding.textinput));
1034        }
1035
1036        return binding.getRoot();
1037    }
1038
1039    private void quoteText(String text) {
1040        if (binding.textinput.isEnabled()) {
1041            binding.textinput.insertAsQuote(text);
1042            binding.textinput.requestFocus();
1043            InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
1044            if (inputMethodManager != null) {
1045                inputMethodManager.showSoftInput(binding.textinput, InputMethodManager.SHOW_IMPLICIT);
1046            }
1047        }
1048    }
1049
1050    private void quoteMessage(Message message) {
1051        quoteText(MessageUtils.prepareQuote(message));
1052    }
1053
1054    @Override
1055    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1056        synchronized (this.messageList) {
1057            super.onCreateContextMenu(menu, v, menuInfo);
1058            AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
1059            this.selectedMessage = this.messageList.get(acmi.position);
1060            populateContextMenu(menu);
1061        }
1062    }
1063
1064    private void populateContextMenu(ContextMenu menu) {
1065        final Message m = this.selectedMessage;
1066        final Transferable t = m.getTransferable();
1067        Message relevantForCorrection = m;
1068        while (relevantForCorrection.mergeable(relevantForCorrection.next())) {
1069            relevantForCorrection = relevantForCorrection.next();
1070        }
1071        if (m.getType() != Message.TYPE_STATUS && m.getType() != Message.TYPE_RTP_SESSION) {
1072
1073            if (m.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE || m.getEncryption() == Message.ENCRYPTION_AXOLOTL_FAILED) {
1074                return;
1075            }
1076
1077            if (m.getStatus() == Message.STATUS_RECEIVED && t != null && (t.getStatus() == Transferable.STATUS_CANCELLED || t.getStatus() == Transferable.STATUS_FAILED)) {
1078                return;
1079            }
1080
1081            final boolean deleted = m.isDeleted();
1082            final boolean encrypted = m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED
1083                    || m.getEncryption() == Message.ENCRYPTION_PGP;
1084            final boolean receiving = m.getStatus() == Message.STATUS_RECEIVED && (t instanceof JingleFileTransferConnection || t instanceof HttpDownloadConnection);
1085            activity.getMenuInflater().inflate(R.menu.message_context, menu);
1086            menu.setHeaderTitle(R.string.message_options);
1087            MenuItem openWith = menu.findItem(R.id.open_with);
1088            MenuItem copyMessage = menu.findItem(R.id.copy_message);
1089            MenuItem copyLink = menu.findItem(R.id.copy_link);
1090            MenuItem quoteMessage = menu.findItem(R.id.quote_message);
1091            MenuItem retryDecryption = menu.findItem(R.id.retry_decryption);
1092            MenuItem correctMessage = menu.findItem(R.id.correct_message);
1093            MenuItem shareWith = menu.findItem(R.id.share_with);
1094            MenuItem sendAgain = menu.findItem(R.id.send_again);
1095            MenuItem copyUrl = menu.findItem(R.id.copy_url);
1096            MenuItem downloadFile = menu.findItem(R.id.download_file);
1097            MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
1098            MenuItem deleteFile = menu.findItem(R.id.delete_file);
1099            MenuItem showErrorMessage = menu.findItem(R.id.show_error_message);
1100            final boolean showError = m.getStatus() == Message.STATUS_SEND_FAILED && m.getErrorMessage() != null && !Message.ERROR_MESSAGE_CANCELLED.equals(m.getErrorMessage());
1101            if (!m.isFileOrImage() && !encrypted && !m.isGeoUri() && !m.treatAsDownloadable()) {
1102                copyMessage.setVisible(true);
1103                quoteMessage.setVisible(!showError && MessageUtils.prepareQuote(m).length() > 0);
1104                String body = m.getMergedBody().toString();
1105                if (ShareUtil.containsXmppUri(body)) {
1106                    copyLink.setTitle(R.string.copy_jabber_id);
1107                    copyLink.setVisible(true);
1108                } else if (Patterns.AUTOLINK_WEB_URL.matcher(body).find()) {
1109                    copyLink.setVisible(true);
1110                }
1111            }
1112            if (m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED && !deleted) {
1113                retryDecryption.setVisible(true);
1114            }
1115            if (!showError
1116                    && relevantForCorrection.getType() == Message.TYPE_TEXT
1117                    && !m.isGeoUri()
1118                    && relevantForCorrection.isLastCorrectableMessage()
1119                    && m.getConversation() instanceof Conversation) {
1120                correctMessage.setVisible(true);
1121            }
1122            if ((m.isFileOrImage() && !deleted && !receiving) || (m.getType() == Message.TYPE_TEXT && !m.treatAsDownloadable())) {
1123                shareWith.setVisible(true);
1124            }
1125            if (m.getStatus() == Message.STATUS_SEND_FAILED) {
1126                sendAgain.setVisible(true);
1127            }
1128            if (m.hasFileOnRemoteHost()
1129                    || m.isGeoUri()
1130                    || m.treatAsDownloadable()
1131                    || t instanceof HttpDownloadConnection) {
1132                copyUrl.setVisible(true);
1133            }
1134            if (m.isFileOrImage() && deleted && m.hasFileOnRemoteHost()) {
1135                downloadFile.setVisible(true);
1136                downloadFile.setTitle(activity.getString(R.string.download_x_file, UIHelper.getFileDescriptionString(activity, m)));
1137            }
1138            final boolean waitingOfferedSending = m.getStatus() == Message.STATUS_WAITING
1139                    || m.getStatus() == Message.STATUS_UNSEND
1140                    || m.getStatus() == Message.STATUS_OFFERED;
1141            final boolean cancelable = (t != null && !deleted) || waitingOfferedSending && m.needsUploading();
1142            if (cancelable) {
1143                cancelTransmission.setVisible(true);
1144            }
1145            if (m.isFileOrImage() && !deleted && !cancelable) {
1146                String path = m.getRelativeFilePath();
1147                if (path == null || !path.startsWith("/") || FileBackend.isInDirectoryThatShouldNotBeScanned(getActivity(), path)) {
1148                    deleteFile.setVisible(true);
1149                    deleteFile.setTitle(activity.getString(R.string.delete_x_file, UIHelper.getFileDescriptionString(activity, m)));
1150                }
1151            }
1152            if (showError) {
1153                showErrorMessage.setVisible(true);
1154            }
1155            final String mime = m.isFileOrImage() ? m.getMimeType() : null;
1156            if ((m.isGeoUri() && GeoHelper.openInOsmAnd(getActivity(), m)) || (mime != null && mime.startsWith("audio/"))) {
1157                openWith.setVisible(true);
1158            }
1159        }
1160    }
1161
1162    @Override
1163    public boolean onContextItemSelected(MenuItem item) {
1164        switch (item.getItemId()) {
1165            case R.id.share_with:
1166                ShareUtil.share(activity, selectedMessage);
1167                return true;
1168            case R.id.correct_message:
1169                correctMessage(selectedMessage);
1170                return true;
1171            case R.id.copy_message:
1172                ShareUtil.copyToClipboard(activity, selectedMessage);
1173                return true;
1174            case R.id.copy_link:
1175                ShareUtil.copyLinkToClipboard(activity, selectedMessage);
1176                return true;
1177            case R.id.quote_message:
1178                quoteMessage(selectedMessage);
1179                return true;
1180            case R.id.send_again:
1181                resendMessage(selectedMessage);
1182                return true;
1183            case R.id.copy_url:
1184                ShareUtil.copyUrlToClipboard(activity, selectedMessage);
1185                return true;
1186            case R.id.download_file:
1187                startDownloadable(selectedMessage);
1188                return true;
1189            case R.id.cancel_transmission:
1190                cancelTransmission(selectedMessage);
1191                return true;
1192            case R.id.retry_decryption:
1193                retryDecryption(selectedMessage);
1194                return true;
1195            case R.id.delete_file:
1196                deleteFile(selectedMessage);
1197                return true;
1198            case R.id.show_error_message:
1199                showErrorMessage(selectedMessage);
1200                return true;
1201            case R.id.open_with:
1202                openWith(selectedMessage);
1203                return true;
1204            default:
1205                return super.onContextItemSelected(item);
1206        }
1207    }
1208
1209    @Override
1210    public boolean onOptionsItemSelected(final MenuItem item) {
1211        if (MenuDoubleTabUtil.shouldIgnoreTap()) {
1212            return false;
1213        } else if (conversation == null) {
1214            return super.onOptionsItemSelected(item);
1215        }
1216        switch (item.getItemId()) {
1217            case R.id.encryption_choice_axolotl:
1218            case R.id.encryption_choice_pgp:
1219            case R.id.encryption_choice_none:
1220                handleEncryptionSelection(item);
1221                break;
1222            case R.id.attach_choose_picture:
1223            case R.id.attach_take_picture:
1224            case R.id.attach_record_video:
1225            case R.id.attach_choose_file:
1226            case R.id.attach_record_voice:
1227            case R.id.attach_location:
1228                handleAttachmentSelection(item);
1229                break;
1230            case R.id.action_archive:
1231                activity.xmppConnectionService.archiveConversation(conversation);
1232                break;
1233            case R.id.action_contact_details:
1234                activity.switchToContactDetails(conversation.getContact());
1235                break;
1236            case R.id.action_muc_details:
1237                Intent intent = new Intent(getActivity(), ConferenceDetailsActivity.class);
1238                intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
1239                intent.putExtra("uuid", conversation.getUuid());
1240                startActivity(intent);
1241                break;
1242            case R.id.action_invite:
1243                startActivityForResult(ChooseContactActivity.create(activity, conversation), REQUEST_INVITE_TO_CONVERSATION);
1244                break;
1245            case R.id.action_clear_history:
1246                clearHistoryDialog(conversation);
1247                break;
1248            case R.id.action_mute:
1249                muteConversationDialog(conversation);
1250                break;
1251            case R.id.action_unmute:
1252                unmuteConversation(conversation);
1253                break;
1254            case R.id.action_block:
1255            case R.id.action_unblock:
1256                final Activity activity = getActivity();
1257                if (activity instanceof XmppActivity) {
1258                    BlockContactDialog.show((XmppActivity) activity, conversation);
1259                }
1260                break;
1261            case R.id.action_audio_call:
1262                checkPermissionAndTriggerAudioCall();
1263                break;
1264            case R.id.action_video_call:
1265                checkPermissionAndTriggerVideoCall();
1266                break;
1267            case R.id.action_ongoing_call:
1268                returnToOngoingCall();
1269                break;
1270            case R.id.action_toggle_pinned:
1271                togglePinned();
1272                break;
1273            default:
1274                break;
1275        }
1276        return super.onOptionsItemSelected(item);
1277    }
1278
1279    private void returnToOngoingCall() {
1280        final Optional<OngoingRtpSession> ongoingRtpSession = activity.xmppConnectionService.getJingleConnectionManager().getOngoingRtpConnection(conversation.getContact());
1281        if (ongoingRtpSession.isPresent()) {
1282            final OngoingRtpSession id = ongoingRtpSession.get();
1283            final Intent intent = new Intent(getActivity(), RtpSessionActivity.class);
1284            intent.putExtra(RtpSessionActivity.EXTRA_ACCOUNT, id.getAccount().getJid().asBareJid().toEscapedString());
1285            intent.putExtra(RtpSessionActivity.EXTRA_WITH, id.getWith().toEscapedString());
1286            if (id instanceof AbstractJingleConnection.Id) {
1287                intent.setAction(Intent.ACTION_VIEW);
1288                intent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.getSessionId());
1289            } else if (id instanceof JingleConnectionManager.RtpSessionProposal) {
1290                if (((JingleConnectionManager.RtpSessionProposal) id).media.contains(Media.VIDEO)) {
1291                    intent.setAction(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
1292                } else {
1293                    intent.setAction(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
1294                }
1295            }
1296            startActivity(intent);
1297        }
1298
1299    }
1300
1301    private void togglePinned() {
1302        final boolean pinned = conversation.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false);
1303        conversation.setAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, !pinned);
1304        activity.xmppConnectionService.updateConversation(conversation);
1305    }
1306
1307    private void checkPermissionAndTriggerAudioCall() {
1308        if (activity.mUseTor || conversation.getAccount().isOnion()) {
1309            Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
1310            return;
1311        }
1312        if (hasPermissions(REQUEST_START_AUDIO_CALL, Manifest.permission.RECORD_AUDIO)) {
1313            triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
1314        }
1315    }
1316
1317    private void checkPermissionAndTriggerVideoCall() {
1318        if (activity.mUseTor || conversation.getAccount().isOnion()) {
1319            Toast.makeText(activity, R.string.disable_tor_to_make_call, Toast.LENGTH_SHORT).show();
1320            return;
1321        }
1322        if (hasPermissions(REQUEST_START_VIDEO_CALL, Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA)) {
1323            triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
1324        }
1325    }
1326
1327
1328    private void triggerRtpSession(final String action) {
1329        if (activity.xmppConnectionService.getJingleConnectionManager().isBusy()) {
1330            Toast.makeText(getActivity(), R.string.only_one_call_at_a_time, Toast.LENGTH_LONG).show();
1331            return;
1332        }
1333        final Contact contact = conversation.getContact();
1334        final Intent intent = new Intent(activity, RtpSessionActivity.class);
1335        intent.setAction(action);
1336        intent.putExtra(RtpSessionActivity.EXTRA_ACCOUNT, contact.getAccount().getJid().toEscapedString());
1337        intent.putExtra(RtpSessionActivity.EXTRA_WITH, contact.getJid().asBareJid().toEscapedString());
1338        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1339        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
1340        startActivity(intent);
1341    }
1342
1343    private void handleAttachmentSelection(MenuItem item) {
1344        switch (item.getItemId()) {
1345            case R.id.attach_choose_picture:
1346                attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
1347                break;
1348            case R.id.attach_take_picture:
1349                attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
1350                break;
1351            case R.id.attach_record_video:
1352                attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO);
1353                break;
1354            case R.id.attach_choose_file:
1355                attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
1356                break;
1357            case R.id.attach_record_voice:
1358                attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
1359                break;
1360            case R.id.attach_location:
1361                attachFile(ATTACHMENT_CHOICE_LOCATION);
1362                break;
1363        }
1364    }
1365
1366    private void handleEncryptionSelection(MenuItem item) {
1367        if (conversation == null) {
1368            return;
1369        }
1370        final boolean updated;
1371        switch (item.getItemId()) {
1372            case R.id.encryption_choice_none:
1373                updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1374                item.setChecked(true);
1375                break;
1376            case R.id.encryption_choice_pgp:
1377                if (activity.hasPgp()) {
1378                    if (conversation.getAccount().getPgpSignature() != null) {
1379                        updated = conversation.setNextEncryption(Message.ENCRYPTION_PGP);
1380                        item.setChecked(true);
1381                    } else {
1382                        updated = false;
1383                        activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
1384                    }
1385                } else {
1386                    activity.showInstallPgpDialog();
1387                    updated = false;
1388                }
1389                break;
1390            case R.id.encryption_choice_axolotl:
1391                Log.d(Config.LOGTAG, AxolotlService.getLogprefix(conversation.getAccount())
1392                        + "Enabled axolotl for Contact " + conversation.getContact().getJid());
1393                updated = conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
1394                item.setChecked(true);
1395                break;
1396            default:
1397                updated = conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1398                break;
1399        }
1400        if (updated) {
1401            activity.xmppConnectionService.updateConversation(conversation);
1402        }
1403        updateChatMsgHint();
1404        getActivity().invalidateOptionsMenu();
1405        activity.refreshUi();
1406    }
1407
1408    public void attachFile(final int attachmentChoice) {
1409        if (attachmentChoice == ATTACHMENT_CHOICE_RECORD_VOICE) {
1410            if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO)) {
1411                return;
1412            }
1413        } else if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO || attachmentChoice == ATTACHMENT_CHOICE_RECORD_VIDEO) {
1414            if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)) {
1415                return;
1416            }
1417        } else if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
1418            if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
1419                return;
1420            }
1421        }
1422        try {
1423            activity.getPreferences().edit()
1424                    .putString(RECENTLY_USED_QUICK_ACTION, SendButtonAction.of(attachmentChoice).toString())
1425                    .apply();
1426        } catch (IllegalArgumentException e) {
1427            //just do not save
1428        }
1429        final int encryption = conversation.getNextEncryption();
1430        final int mode = conversation.getMode();
1431        if (encryption == Message.ENCRYPTION_PGP) {
1432            if (activity.hasPgp()) {
1433                if (mode == Conversation.MODE_SINGLE && conversation.getContact().getPgpKeyId() != 0) {
1434                    activity.xmppConnectionService.getPgpEngine().hasKey(
1435                            conversation.getContact(),
1436                            new UiCallback<Contact>() {
1437
1438                                @Override
1439                                public void userInputRequired(PendingIntent pi, Contact contact) {
1440                                    startPendingIntent(pi, attachmentChoice);
1441                                }
1442
1443                                @Override
1444                                public void success(Contact contact) {
1445                                    invokeAttachFileIntent(attachmentChoice);
1446                                }
1447
1448                                @Override
1449                                public void error(int error, Contact contact) {
1450                                    activity.replaceToast(getString(error));
1451                                }
1452                            });
1453                } else if (mode == Conversation.MODE_MULTI && conversation.getMucOptions().pgpKeysInUse()) {
1454                    if (!conversation.getMucOptions().everybodyHasKeys()) {
1455                        Toast warning = Toast.makeText(getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
1456                        warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
1457                        warning.show();
1458                    }
1459                    invokeAttachFileIntent(attachmentChoice);
1460                } else {
1461                    showNoPGPKeyDialog(false, (dialog, which) -> {
1462                        conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1463                        activity.xmppConnectionService.updateConversation(conversation);
1464                        invokeAttachFileIntent(attachmentChoice);
1465                    });
1466                }
1467            } else {
1468                activity.showInstallPgpDialog();
1469            }
1470        } else {
1471            invokeAttachFileIntent(attachmentChoice);
1472        }
1473    }
1474
1475    @Override
1476    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
1477        if (grantResults.length > 0) {
1478            if (allGranted(grantResults)) {
1479                switch (requestCode) {
1480                    case REQUEST_START_DOWNLOAD:
1481                        if (this.mPendingDownloadableMessage != null) {
1482                            startDownloadable(this.mPendingDownloadableMessage);
1483                        }
1484                        break;
1485                    case REQUEST_ADD_EDITOR_CONTENT:
1486                        if (this.mPendingEditorContent != null) {
1487                            attachEditorContentToConversation(this.mPendingEditorContent);
1488                        }
1489                        break;
1490                    case REQUEST_COMMIT_ATTACHMENTS:
1491                        commitAttachments();
1492                        break;
1493                    case REQUEST_START_AUDIO_CALL:
1494                        triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
1495                        break;
1496                    case REQUEST_START_VIDEO_CALL:
1497                        triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
1498                        break;
1499                    default:
1500                        attachFile(requestCode);
1501                        break;
1502                }
1503            } else {
1504                @StringRes int res;
1505                String firstDenied = getFirstDenied(grantResults, permissions);
1506                if (Manifest.permission.RECORD_AUDIO.equals(firstDenied)) {
1507                    res = R.string.no_microphone_permission;
1508                } else if (Manifest.permission.CAMERA.equals(firstDenied)) {
1509                    res = R.string.no_camera_permission;
1510                } else {
1511                    res = R.string.no_storage_permission;
1512                }
1513                Toast.makeText(getActivity(), res, Toast.LENGTH_SHORT).show();
1514            }
1515        }
1516        if (writeGranted(grantResults, permissions)) {
1517            if (activity != null && activity.xmppConnectionService != null) {
1518                activity.xmppConnectionService.restartFileObserver();
1519            }
1520            refresh();
1521        }
1522    }
1523
1524    public void startDownloadable(Message message) {
1525        if (!hasPermissions(REQUEST_START_DOWNLOAD, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
1526            this.mPendingDownloadableMessage = message;
1527            return;
1528        }
1529        Transferable transferable = message.getTransferable();
1530        if (transferable != null) {
1531            if (transferable instanceof TransferablePlaceholder && message.hasFileOnRemoteHost()) {
1532                createNewConnection(message);
1533                return;
1534            }
1535            if (!transferable.start()) {
1536                Log.d(Config.LOGTAG, "type: " + transferable.getClass().getName());
1537                Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT).show();
1538            }
1539        } else if (message.treatAsDownloadable() || message.hasFileOnRemoteHost() || MessageUtils.unInitiatedButKnownSize(message)) {
1540            createNewConnection(message);
1541        } else {
1542            Log.d(Config.LOGTAG, message.getConversation().getAccount() + ": unable to start downloadable");
1543        }
1544    }
1545
1546    private void createNewConnection(final Message message) {
1547        if (!activity.xmppConnectionService.getHttpConnectionManager().checkConnection(message)) {
1548            Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT).show();
1549            return;
1550        }
1551        activity.xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message, true);
1552    }
1553
1554    @SuppressLint("InflateParams")
1555    protected void clearHistoryDialog(final Conversation conversation) {
1556        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1557        builder.setTitle(getString(R.string.clear_conversation_history));
1558        final View dialogView = getActivity().getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
1559        final CheckBox endConversationCheckBox = dialogView.findViewById(R.id.end_conversation_checkbox);
1560        builder.setView(dialogView);
1561        builder.setNegativeButton(getString(R.string.cancel), null);
1562        builder.setPositiveButton(getString(R.string.confirm), (dialog, which) -> {
1563            this.activity.xmppConnectionService.clearConversationHistory(conversation);
1564            if (endConversationCheckBox.isChecked()) {
1565                this.activity.xmppConnectionService.archiveConversation(conversation);
1566                this.activity.onConversationArchived(conversation);
1567            } else {
1568                activity.onConversationsListItemUpdated();
1569                refresh();
1570            }
1571        });
1572        builder.create().show();
1573    }
1574
1575    protected void muteConversationDialog(final Conversation conversation) {
1576        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1577        builder.setTitle(R.string.disable_notifications);
1578        final int[] durations = getResources().getIntArray(R.array.mute_options_durations);
1579        final CharSequence[] labels = new CharSequence[durations.length];
1580        for (int i = 0; i < durations.length; ++i) {
1581            if (durations[i] == -1) {
1582                labels[i] = getString(R.string.until_further_notice);
1583            } else {
1584                labels[i] = TimeFrameUtils.resolve(activity, 1000L * durations[i]);
1585            }
1586        }
1587        builder.setItems(labels, (dialog, which) -> {
1588            final long till;
1589            if (durations[which] == -1) {
1590                till = Long.MAX_VALUE;
1591            } else {
1592                till = System.currentTimeMillis() + (durations[which] * 1000);
1593            }
1594            conversation.setMutedTill(till);
1595            activity.xmppConnectionService.updateConversation(conversation);
1596            activity.onConversationsListItemUpdated();
1597            refresh();
1598            getActivity().invalidateOptionsMenu();
1599        });
1600        builder.create().show();
1601    }
1602
1603    private boolean hasPermissions(int requestCode, String... permissions) {
1604        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1605            final List<String> missingPermissions = new ArrayList<>();
1606            for (String permission : permissions) {
1607                if (Config.ONLY_INTERNAL_STORAGE && permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
1608                    continue;
1609                }
1610                if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
1611                    missingPermissions.add(permission);
1612                }
1613            }
1614            if (missingPermissions.size() == 0) {
1615                return true;
1616            } else {
1617                requestPermissions(missingPermissions.toArray(new String[missingPermissions.size()]), requestCode);
1618                return false;
1619            }
1620        } else {
1621            return true;
1622        }
1623    }
1624
1625    public void unmuteConversation(final Conversation conversation) {
1626        conversation.setMutedTill(0);
1627        this.activity.xmppConnectionService.updateConversation(conversation);
1628        this.activity.onConversationsListItemUpdated();
1629        refresh();
1630        getActivity().invalidateOptionsMenu();
1631    }
1632
1633
1634    protected void invokeAttachFileIntent(final int attachmentChoice) {
1635        Intent intent = new Intent();
1636        boolean chooser = false;
1637        switch (attachmentChoice) {
1638            case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
1639                intent.setAction(Intent.ACTION_GET_CONTENT);
1640                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1641                    intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
1642                }
1643                intent.setType("image/*");
1644                chooser = true;
1645                break;
1646            case ATTACHMENT_CHOICE_RECORD_VIDEO:
1647                intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
1648                break;
1649            case ATTACHMENT_CHOICE_TAKE_PHOTO:
1650                final Uri uri = activity.xmppConnectionService.getFileBackend().getTakePhotoUri();
1651                pendingTakePhotoUri.push(uri);
1652                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
1653                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
1654                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1655                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
1656                break;
1657            case ATTACHMENT_CHOICE_CHOOSE_FILE:
1658                chooser = true;
1659                intent.setType("*/*");
1660                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1661                    intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
1662                }
1663                intent.addCategory(Intent.CATEGORY_OPENABLE);
1664                intent.setAction(Intent.ACTION_GET_CONTENT);
1665                break;
1666            case ATTACHMENT_CHOICE_RECORD_VOICE:
1667                intent = new Intent(getActivity(), RecordingActivity.class);
1668                break;
1669            case ATTACHMENT_CHOICE_LOCATION:
1670                intent = GeoHelper.getFetchIntent(activity);
1671                break;
1672        }
1673        final Context context = getActivity();
1674        if (context != null && intent.resolveActivity(context.getPackageManager()) != null) {
1675            if (chooser) {
1676                startActivityForResult(
1677                        Intent.createChooser(intent, getString(R.string.perform_action_with)),
1678                        attachmentChoice);
1679            } else {
1680                startActivityForResult(intent, attachmentChoice);
1681            }
1682        }
1683    }
1684
1685    @Override
1686    public void onResume() {
1687        super.onResume();
1688        binding.messagesView.post(this::fireReadEvent);
1689    }
1690
1691    private void fireReadEvent() {
1692        if (activity != null && this.conversation != null) {
1693            String uuid = getLastVisibleMessageUuid();
1694            if (uuid != null) {
1695                activity.onConversationRead(this.conversation, uuid);
1696            }
1697        }
1698    }
1699
1700    private String getLastVisibleMessageUuid() {
1701        if (binding == null) {
1702            return null;
1703        }
1704        synchronized (this.messageList) {
1705            int pos = binding.messagesView.getLastVisiblePosition();
1706            if (pos >= 0) {
1707                Message message = null;
1708                for (int i = pos; i >= 0; --i) {
1709                    try {
1710                        message = (Message) binding.messagesView.getItemAtPosition(i);
1711                    } catch (IndexOutOfBoundsException e) {
1712                        //should not happen if we synchronize properly. however if that fails we just gonna try item -1
1713                        continue;
1714                    }
1715                    if (message.getType() != Message.TYPE_STATUS) {
1716                        break;
1717                    }
1718                }
1719                if (message != null) {
1720                    while (message.next() != null && message.next().wasMergedIntoPrevious()) {
1721                        message = message.next();
1722                    }
1723                    return message.getUuid();
1724                }
1725            }
1726        }
1727        return null;
1728    }
1729
1730    private void openWith(final Message message) {
1731        if (message.isGeoUri()) {
1732            GeoHelper.view(getActivity(), message);
1733        } else {
1734            final DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
1735            ViewUtil.view(activity, file);
1736        }
1737    }
1738
1739    private void showErrorMessage(final Message message) {
1740        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1741        builder.setTitle(R.string.error_message);
1742        final String errorMessage = message.getErrorMessage();
1743        final String[] errorMessageParts = errorMessage == null ? new String[0] : errorMessage.split("\\u001f");
1744        final String displayError;
1745        if (errorMessageParts.length == 2) {
1746            displayError = errorMessageParts[1];
1747        } else {
1748            displayError = errorMessage;
1749        }
1750        builder.setMessage(displayError);
1751        builder.setNegativeButton(R.string.copy_to_clipboard, (dialog, which) -> {
1752            activity.copyTextToClipboard(displayError, R.string.error_message);
1753            Toast.makeText(activity, R.string.error_message_copied_to_clipboard, Toast.LENGTH_SHORT).show();
1754        });
1755        builder.setPositiveButton(R.string.confirm, null);
1756        builder.create().show();
1757    }
1758
1759
1760    private void deleteFile(final Message message) {
1761        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1762        builder.setNegativeButton(R.string.cancel, null);
1763        builder.setTitle(R.string.delete_file_dialog);
1764        builder.setMessage(R.string.delete_file_dialog_msg);
1765        builder.setPositiveButton(R.string.confirm, (dialog, which) -> {
1766            if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
1767                message.setDeleted(true);
1768                activity.xmppConnectionService.evictPreview(message.getUuid());
1769                activity.xmppConnectionService.updateMessage(message, false);
1770                activity.onConversationsListItemUpdated();
1771                refresh();
1772            }
1773        });
1774        builder.create().show();
1775
1776    }
1777
1778    private void resendMessage(final Message message) {
1779        if (message.isFileOrImage()) {
1780            if (!(message.getConversation() instanceof Conversation)) {
1781                return;
1782            }
1783            final Conversation conversation = (Conversation) message.getConversation();
1784            final DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
1785            if ((file.exists() && file.canRead()) || message.hasFileOnRemoteHost()) {
1786                final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
1787                if (!message.hasFileOnRemoteHost()
1788                        && xmppConnection != null
1789                        && conversation.getMode() == Conversational.MODE_SINGLE
1790                        && !xmppConnection.getFeatures().httpUpload(message.getFileParams().size)) {
1791                    activity.selectPresence(conversation, () -> {
1792                        message.setCounterpart(conversation.getNextCounterpart());
1793                        activity.xmppConnectionService.resendFailedMessages(message);
1794                        new Handler().post(() -> {
1795                            int size = messageList.size();
1796                            this.binding.messagesView.setSelection(size - 1);
1797                        });
1798                    });
1799                    return;
1800                }
1801            } else if (!Compatibility.hasStoragePermission(getActivity())) {
1802                Toast.makeText(activity, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
1803                return;
1804            } else {
1805                Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
1806                message.setDeleted(true);
1807                activity.xmppConnectionService.updateMessage(message, false);
1808                activity.onConversationsListItemUpdated();
1809                refresh();
1810                return;
1811            }
1812        }
1813        activity.xmppConnectionService.resendFailedMessages(message);
1814        new Handler().post(() -> {
1815            int size = messageList.size();
1816            this.binding.messagesView.setSelection(size - 1);
1817        });
1818    }
1819
1820    private void cancelTransmission(Message message) {
1821        Transferable transferable = message.getTransferable();
1822        if (transferable != null) {
1823            transferable.cancel();
1824        } else if (message.getStatus() != Message.STATUS_RECEIVED) {
1825            activity.xmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED, Message.ERROR_MESSAGE_CANCELLED);
1826        }
1827    }
1828
1829    private void retryDecryption(Message message) {
1830        message.setEncryption(Message.ENCRYPTION_PGP);
1831        activity.onConversationsListItemUpdated();
1832        refresh();
1833        conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
1834    }
1835
1836    public void privateMessageWith(final Jid counterpart) {
1837        if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
1838            activity.xmppConnectionService.sendChatState(conversation);
1839        }
1840        this.binding.textinput.setText("");
1841        this.conversation.setNextCounterpart(counterpart);
1842        updateChatMsgHint();
1843        updateSendButton();
1844        updateEditablity();
1845    }
1846
1847    private void correctMessage(Message message) {
1848        while (message.mergeable(message.next())) {
1849            message = message.next();
1850        }
1851        this.conversation.setCorrectingMessage(message);
1852        final Editable editable = binding.textinput.getText();
1853        this.conversation.setDraftMessage(editable.toString());
1854        this.binding.textinput.setText("");
1855        this.binding.textinput.append(message.getBody());
1856
1857    }
1858
1859    private void highlightInConference(String nick) {
1860        final Editable editable = this.binding.textinput.getText();
1861        String oldString = editable.toString().trim();
1862        final int pos = this.binding.textinput.getSelectionStart();
1863        if (oldString.isEmpty() || pos == 0) {
1864            editable.insert(0, nick + ": ");
1865        } else {
1866            final char before = editable.charAt(pos - 1);
1867            final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
1868            if (before == '\n') {
1869                editable.insert(pos, nick + ": ");
1870            } else {
1871                if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
1872                    if (NickValidityChecker.check(conversation, Arrays.asList(editable.subSequence(0, pos - 2).toString().split(", ")))) {
1873                        editable.insert(pos - 2, ", " + nick);
1874                        return;
1875                    }
1876                }
1877                editable.insert(pos, (Character.isWhitespace(before) ? "" : " ") + nick + (Character.isWhitespace(after) ? "" : " "));
1878                if (Character.isWhitespace(after)) {
1879                    this.binding.textinput.setSelection(this.binding.textinput.getSelectionStart() + 1);
1880                }
1881            }
1882        }
1883    }
1884
1885    @Override
1886    public void startActivityForResult(Intent intent, int requestCode) {
1887        final Activity activity = getActivity();
1888        if (activity instanceof ConversationsActivity) {
1889            ((ConversationsActivity) activity).clearPendingViewIntent();
1890        }
1891        super.startActivityForResult(intent, requestCode);
1892    }
1893
1894    @Override
1895    public void onSaveInstanceState(Bundle outState) {
1896        super.onSaveInstanceState(outState);
1897        if (conversation != null) {
1898            outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
1899            outState.putString(STATE_LAST_MESSAGE_UUID, lastMessageUuid);
1900            final Uri uri = pendingTakePhotoUri.peek();
1901            if (uri != null) {
1902                outState.putString(STATE_PHOTO_URI, uri.toString());
1903            }
1904            final ScrollState scrollState = getScrollPosition();
1905            if (scrollState != null) {
1906                outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
1907            }
1908            final ArrayList<Attachment> attachments = mediaPreviewAdapter == null ? new ArrayList<>() : mediaPreviewAdapter.getAttachments();
1909            if (attachments.size() > 0) {
1910                outState.putParcelableArrayList(STATE_MEDIA_PREVIEWS, attachments);
1911            }
1912        }
1913    }
1914
1915    @Override
1916    public void onActivityCreated(Bundle savedInstanceState) {
1917        super.onActivityCreated(savedInstanceState);
1918        if (savedInstanceState == null) {
1919            return;
1920        }
1921        String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
1922        ArrayList<Attachment> attachments = savedInstanceState.getParcelableArrayList(STATE_MEDIA_PREVIEWS);
1923        pendingLastMessageUuid.push(savedInstanceState.getString(STATE_LAST_MESSAGE_UUID, null));
1924        if (uuid != null) {
1925            QuickLoader.set(uuid);
1926            this.pendingConversationsUuid.push(uuid);
1927            if (attachments != null && attachments.size() > 0) {
1928                this.pendingMediaPreviews.push(attachments);
1929            }
1930            String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
1931            if (takePhotoUri != null) {
1932                pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
1933            }
1934            pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
1935        }
1936    }
1937
1938    @Override
1939    public void onStart() {
1940        super.onStart();
1941        if (this.reInitRequiredOnStart && this.conversation != null) {
1942            final Bundle extras = pendingExtras.pop();
1943            reInit(this.conversation, extras != null);
1944            if (extras != null) {
1945                processExtras(extras);
1946            }
1947        } else if (conversation == null && activity != null && activity.xmppConnectionService != null) {
1948            final String uuid = pendingConversationsUuid.pop();
1949            Log.d(Config.LOGTAG, "ConversationFragment.onStart() - activity was bound but no conversation loaded. uuid=" + uuid);
1950            if (uuid != null) {
1951                findAndReInitByUuidOrArchive(uuid);
1952            }
1953        }
1954    }
1955
1956    @Override
1957    public void onStop() {
1958        super.onStop();
1959        final Activity activity = getActivity();
1960        messageListAdapter.unregisterListenerInAudioPlayer();
1961        if (activity == null || !activity.isChangingConfigurations()) {
1962            hideSoftKeyboard(activity);
1963            messageListAdapter.stopAudioPlayer();
1964        }
1965        if (this.conversation != null) {
1966            final String msg = this.binding.textinput.getText().toString();
1967            storeNextMessage(msg);
1968            updateChatState(this.conversation, msg);
1969            this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
1970        }
1971        this.reInitRequiredOnStart = true;
1972    }
1973
1974    private void updateChatState(final Conversation conversation, final String msg) {
1975        ChatState state = msg.length() == 0 ? Config.DEFAULT_CHAT_STATE : ChatState.PAUSED;
1976        Account.State status = conversation.getAccount().getStatus();
1977        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
1978            activity.xmppConnectionService.sendChatState(conversation);
1979        }
1980    }
1981
1982    private void saveMessageDraftStopAudioPlayer() {
1983        final Conversation previousConversation = this.conversation;
1984        if (this.activity == null || this.binding == null || previousConversation == null) {
1985            return;
1986        }
1987        Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
1988        final String msg = this.binding.textinput.getText().toString();
1989        storeNextMessage(msg);
1990        updateChatState(this.conversation, msg);
1991        messageListAdapter.stopAudioPlayer();
1992        mediaPreviewAdapter.clearPreviews();
1993        toggleInputMethod();
1994    }
1995
1996    public void reInit(Conversation conversation, Bundle extras) {
1997        QuickLoader.set(conversation.getUuid());
1998        this.saveMessageDraftStopAudioPlayer();
1999        this.clearPending();
2000        if (this.reInit(conversation, extras != null)) {
2001            if (extras != null) {
2002                processExtras(extras);
2003            }
2004            this.reInitRequiredOnStart = false;
2005        } else {
2006            this.reInitRequiredOnStart = true;
2007            pendingExtras.push(extras);
2008        }
2009        resetUnreadMessagesCount();
2010    }
2011
2012    private void reInit(Conversation conversation) {
2013        reInit(conversation, false);
2014    }
2015
2016    private boolean reInit(final Conversation conversation, final boolean hasExtras) {
2017        if (conversation == null) {
2018            return false;
2019        }
2020        this.conversation = conversation;
2021        //once we set the conversation all is good and it will automatically do the right thing in onStart()
2022        if (this.activity == null || this.binding == null) {
2023            return false;
2024        }
2025
2026        if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
2027            activity.onConversationArchived(this.conversation);
2028            return false;
2029        }
2030
2031        stopScrolling();
2032        Log.d(Config.LOGTAG, "reInit(hasExtras=" + Boolean.toString(hasExtras) + ")");
2033
2034        if (this.conversation.isRead() && hasExtras) {
2035            Log.d(Config.LOGTAG, "trimming conversation");
2036            this.conversation.trim();
2037        }
2038
2039        setupIme();
2040
2041        final boolean scrolledToBottomAndNoPending = this.scrolledToBottom() && pendingScrollState.peek() == null;
2042
2043        this.binding.textSendButton.setContentDescription(activity.getString(R.string.send_message_to_x, conversation.getName()));
2044        this.binding.textinput.setKeyboardListener(null);
2045        this.binding.textinput.setText("");
2046        final boolean participating = conversation.getMode() == Conversational.MODE_SINGLE || conversation.getMucOptions().participating();
2047        if (participating) {
2048            this.binding.textinput.append(this.conversation.getNextMessage());
2049        }
2050        this.binding.textinput.setKeyboardListener(this);
2051        messageListAdapter.updatePreferences();
2052        refresh(false);
2053        this.conversation.messagesLoaded.set(true);
2054        Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + Boolean.toString(scrolledToBottomAndNoPending));
2055
2056        if (hasExtras || scrolledToBottomAndNoPending) {
2057            resetUnreadMessagesCount();
2058            synchronized (this.messageList) {
2059                Log.d(Config.LOGTAG, "jump to first unread message");
2060                final Message first = conversation.getFirstUnreadMessage();
2061                final int bottom = Math.max(0, this.messageList.size() - 1);
2062                final int pos;
2063                final boolean jumpToBottom;
2064                if (first == null) {
2065                    pos = bottom;
2066                    jumpToBottom = true;
2067                } else {
2068                    int i = getIndexOf(first.getUuid(), this.messageList);
2069                    pos = i < 0 ? bottom : i;
2070                    jumpToBottom = false;
2071                }
2072                setSelection(pos, jumpToBottom);
2073            }
2074        }
2075
2076
2077        this.binding.messagesView.post(this::fireReadEvent);
2078        //TODO if we only do this when this fragment is running on main it won't *bing* in tablet layout which might be unnecessary since we can *see* it
2079        activity.xmppConnectionService.getNotificationService().setOpenConversation(this.conversation);
2080        return true;
2081    }
2082
2083    private void resetUnreadMessagesCount() {
2084        lastMessageUuid = null;
2085        hideUnreadMessagesCount();
2086    }
2087
2088    private void hideUnreadMessagesCount() {
2089        if (this.binding == null) {
2090            return;
2091        }
2092        this.binding.scrollToBottomButton.setEnabled(false);
2093        this.binding.scrollToBottomButton.hide();
2094        this.binding.unreadCountCustomView.setVisibility(View.GONE);
2095    }
2096
2097    private void setSelection(int pos, boolean jumpToBottom) {
2098        ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom);
2099        this.binding.messagesView.post(() -> ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom));
2100        this.binding.messagesView.post(this::fireReadEvent);
2101    }
2102
2103
2104    private boolean scrolledToBottom() {
2105        return this.binding != null && scrolledToBottom(this.binding.messagesView);
2106    }
2107
2108    private void processExtras(Bundle extras) {
2109        final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
2110        final String text = extras.getString(Intent.EXTRA_TEXT);
2111        final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
2112        final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE);
2113        final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
2114        final boolean doNotAppend = extras.getBoolean(ConversationsActivity.EXTRA_DO_NOT_APPEND, false);
2115        final List<Uri> uris = extractUris(extras);
2116        if (uris != null && uris.size() > 0) {
2117            if (uris.size() == 1 && "geo".equals(uris.get(0).getScheme())) {
2118                mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), uris.get(0), Attachment.Type.LOCATION));
2119            } else {
2120                final List<Uri> cleanedUris = cleanUris(new ArrayList<>(uris));
2121                mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), cleanedUris));
2122            }
2123            toggleInputMethod();
2124            return;
2125        }
2126        if (nick != null) {
2127            if (pm) {
2128                Jid jid = conversation.getJid();
2129                try {
2130                    Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
2131                    privateMessageWith(next);
2132                } catch (final IllegalArgumentException ignored) {
2133                    //do nothing
2134                }
2135            } else {
2136                final MucOptions mucOptions = conversation.getMucOptions();
2137                if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
2138                    highlightInConference(nick);
2139                }
2140            }
2141        } else {
2142            if (text != null && GeoHelper.GEO_URI.matcher(text).matches()) {
2143                mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), Uri.parse(text), Attachment.Type.LOCATION));
2144                toggleInputMethod();
2145                return;
2146            } else if (text != null && asQuote) {
2147                quoteText(text);
2148            } else {
2149                appendText(text, doNotAppend);
2150            }
2151        }
2152        final Message message = downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
2153        if (message != null) {
2154            startDownloadable(message);
2155        }
2156    }
2157
2158    private List<Uri> extractUris(Bundle extras) {
2159        final List<Uri> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
2160        if (uris != null) {
2161            return uris;
2162        }
2163        final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
2164        if (uri != null) {
2165            return Collections.singletonList(uri);
2166        } else {
2167            return null;
2168        }
2169    }
2170
2171    private List<Uri> cleanUris(List<Uri> uris) {
2172        Iterator<Uri> iterator = uris.iterator();
2173        while (iterator.hasNext()) {
2174            final Uri uri = iterator.next();
2175            if (FileBackend.weOwnFile(getActivity(), uri)) {
2176                iterator.remove();
2177                Toast.makeText(getActivity(), R.string.security_violation_not_attaching_file, Toast.LENGTH_SHORT).show();
2178            }
2179        }
2180        return uris;
2181    }
2182
2183    private boolean showBlockSubmenu(View view) {
2184        final Jid jid = conversation.getJid();
2185        final boolean showReject = !conversation.isWithStranger() && conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
2186        PopupMenu popupMenu = new PopupMenu(getActivity(), view);
2187        popupMenu.inflate(R.menu.block);
2188        popupMenu.getMenu().findItem(R.id.block_contact).setVisible(jid.getLocal() != null);
2189        popupMenu.getMenu().findItem(R.id.reject).setVisible(showReject);
2190        popupMenu.setOnMenuItemClickListener(menuItem -> {
2191            Blockable blockable;
2192            switch (menuItem.getItemId()) {
2193                case R.id.reject:
2194                    activity.xmppConnectionService.stopPresenceUpdatesTo(conversation.getContact());
2195                    updateSnackBar(conversation);
2196                    return true;
2197                case R.id.block_domain:
2198                    blockable = conversation.getAccount().getRoster().getContact(Jid.ofDomain(jid.getDomain()));
2199                    break;
2200                default:
2201                    blockable = conversation;
2202            }
2203            BlockContactDialog.show(activity, blockable);
2204            return true;
2205        });
2206        popupMenu.show();
2207        return true;
2208    }
2209
2210    private void updateSnackBar(final Conversation conversation) {
2211        final Account account = conversation.getAccount();
2212        final XmppConnection connection = account.getXmppConnection();
2213        final int mode = conversation.getMode();
2214        final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
2215        if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2216            return;
2217        }
2218        if (account.getStatus() == Account.State.DISABLED) {
2219            showSnackbar(R.string.this_account_is_disabled, R.string.enable, this.mEnableAccountListener);
2220        } else if (conversation.isBlocked()) {
2221            showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
2222        } else if (contact != null && !contact.showInRoster() && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2223            showSnackbar(R.string.contact_added_you, R.string.add_back, this.mAddBackClickListener, this.mLongPressBlockListener);
2224        } else if (contact != null && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2225            showSnackbar(R.string.contact_asks_for_presence_subscription, R.string.allow, this.mAllowPresenceSubscription, this.mLongPressBlockListener);
2226        } else if (mode == Conversation.MODE_MULTI
2227                && !conversation.getMucOptions().online()
2228                && account.getStatus() == Account.State.ONLINE) {
2229            switch (conversation.getMucOptions().getError()) {
2230                case NICK_IN_USE:
2231                    showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
2232                    break;
2233                case NO_RESPONSE:
2234                    showSnackbar(R.string.joining_conference, 0, null);
2235                    break;
2236                case SERVER_NOT_FOUND:
2237                    if (conversation.receivedMessagesCount() > 0) {
2238                        showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
2239                    } else {
2240                        showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
2241                    }
2242                    break;
2243                case REMOTE_SERVER_TIMEOUT:
2244                    if (conversation.receivedMessagesCount() > 0) {
2245                        showSnackbar(R.string.remote_server_timeout, R.string.try_again, joinMuc);
2246                    } else {
2247                        showSnackbar(R.string.remote_server_timeout, R.string.leave, leaveMuc);
2248                    }
2249                    break;
2250                case PASSWORD_REQUIRED:
2251                    showSnackbar(R.string.conference_requires_password, R.string.enter_password, enterPassword);
2252                    break;
2253                case BANNED:
2254                    showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
2255                    break;
2256                case MEMBERS_ONLY:
2257                    showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
2258                    break;
2259                case RESOURCE_CONSTRAINT:
2260                    showSnackbar(R.string.conference_resource_constraint, R.string.try_again, joinMuc);
2261                    break;
2262                case KICKED:
2263                    showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
2264                    break;
2265                case UNKNOWN:
2266                    showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
2267                    break;
2268                case INVALID_NICK:
2269                    showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
2270                case SHUTDOWN:
2271                    showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
2272                    break;
2273                case DESTROYED:
2274                    showSnackbar(R.string.conference_destroyed, R.string.leave, leaveMuc);
2275                    break;
2276                case NON_ANONYMOUS:
2277                    showSnackbar(R.string.group_chat_will_make_your_jabber_id_public, R.string.join, acceptJoin);
2278                    break;
2279                default:
2280                    hideSnackbar();
2281                    break;
2282            }
2283        } else if (account.hasPendingPgpIntent(conversation)) {
2284            showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
2285        } else if (connection != null
2286                && connection.getFeatures().blocking()
2287                && conversation.countMessages() != 0
2288                && !conversation.isBlocked()
2289                && conversation.isWithStranger()) {
2290            showSnackbar(R.string.received_message_from_stranger, R.string.block, mBlockClickListener);
2291        } else {
2292            hideSnackbar();
2293        }
2294    }
2295
2296    @Override
2297    public void refresh() {
2298        if (this.binding == null) {
2299            Log.d(Config.LOGTAG, "ConversationFragment.refresh() skipped updated because view binding was null");
2300            return;
2301        }
2302        if (this.conversation != null && this.activity != null && this.activity.xmppConnectionService != null) {
2303            if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) {
2304                activity.onConversationArchived(this.conversation);
2305                return;
2306            }
2307        }
2308        this.refresh(true);
2309    }
2310
2311    private void refresh(boolean notifyConversationRead) {
2312        synchronized (this.messageList) {
2313            if (this.conversation != null) {
2314                conversation.populateWithMessages(this.messageList);
2315                updateSnackBar(conversation);
2316                updateStatusMessages();
2317                if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) != 0) {
2318                    binding.unreadCountCustomView.setVisibility(View.VISIBLE);
2319                    binding.unreadCountCustomView.setUnreadCount(conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid));
2320                }
2321                this.messageListAdapter.notifyDataSetChanged();
2322                updateChatMsgHint();
2323                if (notifyConversationRead && activity != null) {
2324                    binding.messagesView.post(this::fireReadEvent);
2325                }
2326                updateSendButton();
2327                updateEditablity();
2328                activity.invalidateOptionsMenu();
2329            }
2330        }
2331    }
2332
2333    protected void messageSent() {
2334        mSendingPgpMessage.set(false);
2335        this.binding.textinput.setText("");
2336        if (conversation.setCorrectingMessage(null)) {
2337            this.binding.textinput.append(conversation.getDraftMessage());
2338            conversation.setDraftMessage(null);
2339        }
2340        storeNextMessage();
2341        updateChatMsgHint();
2342        SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
2343        final boolean prefScrollToBottom = p.getBoolean("scroll_to_bottom", activity.getResources().getBoolean(R.bool.scroll_to_bottom));
2344        if (prefScrollToBottom || scrolledToBottom()) {
2345            new Handler().post(() -> {
2346                int size = messageList.size();
2347                this.binding.messagesView.setSelection(size - 1);
2348            });
2349        }
2350    }
2351
2352    private boolean storeNextMessage() {
2353        return storeNextMessage(this.binding.textinput.getText().toString());
2354    }
2355
2356    private boolean storeNextMessage(String msg) {
2357        final boolean participating = conversation.getMode() == Conversational.MODE_SINGLE || conversation.getMucOptions().participating();
2358        if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED && participating && this.conversation.setNextMessage(msg)) {
2359            this.activity.xmppConnectionService.updateConversation(this.conversation);
2360            return true;
2361        }
2362        return false;
2363    }
2364
2365    public void doneSendingPgpMessage() {
2366        mSendingPgpMessage.set(false);
2367    }
2368
2369    public long getMaxHttpUploadSize(Conversation conversation) {
2370        final XmppConnection connection = conversation.getAccount().getXmppConnection();
2371        return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
2372    }
2373
2374    private void updateEditablity() {
2375        boolean canWrite = this.conversation.getMode() == Conversation.MODE_SINGLE || this.conversation.getMucOptions().participating() || this.conversation.getNextCounterpart() != null;
2376        this.binding.textinput.setFocusable(canWrite);
2377        this.binding.textinput.setFocusableInTouchMode(canWrite);
2378        this.binding.textSendButton.setEnabled(canWrite);
2379        this.binding.textinput.setCursorVisible(canWrite);
2380        this.binding.textinput.setEnabled(canWrite);
2381    }
2382
2383    public void updateSendButton() {
2384        boolean hasAttachments = mediaPreviewAdapter != null && mediaPreviewAdapter.hasAttachments();
2385        final Conversation c = this.conversation;
2386        final Presence.Status status;
2387        final String text = this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
2388        final SendButtonAction action;
2389        if (hasAttachments) {
2390            action = SendButtonAction.TEXT;
2391        } else {
2392            action = SendButtonTool.getAction(getActivity(), c, text);
2393        }
2394        if (c.getAccount().getStatus() == Account.State.ONLINE) {
2395            if (activity != null && activity.xmppConnectionService != null && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
2396                status = Presence.Status.OFFLINE;
2397            } else if (c.getMode() == Conversation.MODE_SINGLE) {
2398                status = c.getContact().getShownStatus();
2399            } else {
2400                status = c.getMucOptions().online() ? Presence.Status.ONLINE : Presence.Status.OFFLINE;
2401            }
2402        } else {
2403            status = Presence.Status.OFFLINE;
2404        }
2405        this.binding.textSendButton.setTag(action);
2406        final Activity activity = getActivity();
2407        if (activity != null) {
2408            this.binding.textSendButton.setImageResource(SendButtonTool.getSendButtonImageResource(activity, action, status));
2409        }
2410    }
2411
2412    protected void updateStatusMessages() {
2413        DateSeparator.addAll(this.messageList);
2414        if (showLoadMoreMessages(conversation)) {
2415            this.messageList.add(0, Message.createLoadMoreMessage(conversation));
2416        }
2417        if (conversation.getMode() == Conversation.MODE_SINGLE) {
2418            ChatState state = conversation.getIncomingChatState();
2419            if (state == ChatState.COMPOSING) {
2420                this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_is_typing, conversation.getName())));
2421            } else if (state == ChatState.PAUSED) {
2422                this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_has_stopped_typing, conversation.getName())));
2423            } else {
2424                for (int i = this.messageList.size() - 1; i >= 0; --i) {
2425                    final Message message = this.messageList.get(i);
2426                    if (message.getType() != Message.TYPE_STATUS) {
2427                        if (message.getStatus() == Message.STATUS_RECEIVED) {
2428                            return;
2429                        } else {
2430                            if (message.getStatus() == Message.STATUS_SEND_DISPLAYED) {
2431                                this.messageList.add(i + 1,
2432                                        Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, conversation.getName())));
2433                                return;
2434                            }
2435                        }
2436                    }
2437                }
2438            }
2439        } else {
2440            final MucOptions mucOptions = conversation.getMucOptions();
2441            final List<MucOptions.User> allUsers = mucOptions.getUsers();
2442            final Set<ReadByMarker> addedMarkers = new HashSet<>();
2443            ChatState state = ChatState.COMPOSING;
2444            List<MucOptions.User> users = conversation.getMucOptions().getUsersWithChatState(state, 5);
2445            if (users.size() == 0) {
2446                state = ChatState.PAUSED;
2447                users = conversation.getMucOptions().getUsersWithChatState(state, 5);
2448            }
2449            if (mucOptions.isPrivateAndNonAnonymous()) {
2450                for (int i = this.messageList.size() - 1; i >= 0; --i) {
2451                    final Set<ReadByMarker> markersForMessage = messageList.get(i).getReadByMarkers();
2452                    final List<MucOptions.User> shownMarkers = new ArrayList<>();
2453                    for (ReadByMarker marker : markersForMessage) {
2454                        if (!ReadByMarker.contains(marker, addedMarkers)) {
2455                            addedMarkers.add(marker); //may be put outside this condition. set should do dedup anyway
2456                            MucOptions.User user = mucOptions.findUser(marker);
2457                            if (user != null && !users.contains(user)) {
2458                                shownMarkers.add(user);
2459                            }
2460                        }
2461                    }
2462                    final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
2463                    final Message statusMessage;
2464                    final int size = shownMarkers.size();
2465                    if (size > 1) {
2466                        final String body;
2467                        if (size <= 4) {
2468                            body = getString(R.string.contacts_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers));
2469                        } else if (ReadByMarker.allUsersRepresented(allUsers, markersForMessage, markerForSender)) {
2470                            body = getString(R.string.everyone_has_read_up_to_this_point);
2471                        } else {
2472                            body = getString(R.string.contacts_and_n_more_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers, 3), size - 3);
2473                        }
2474                        statusMessage = Message.createStatusMessage(conversation, body);
2475                        statusMessage.setCounterparts(shownMarkers);
2476                    } else if (size == 1) {
2477                        statusMessage = Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, UIHelper.getDisplayName(shownMarkers.get(0))));
2478                        statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
2479                        statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
2480                    } else {
2481                        statusMessage = null;
2482                    }
2483                    if (statusMessage != null) {
2484                        this.messageList.add(i + 1, statusMessage);
2485                    }
2486                    addedMarkers.add(markerForSender);
2487                    if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
2488                        break;
2489                    }
2490                }
2491            }
2492            if (users.size() > 0) {
2493                Message statusMessage;
2494                if (users.size() == 1) {
2495                    MucOptions.User user = users.get(0);
2496                    int id = state == ChatState.COMPOSING ? R.string.contact_is_typing : R.string.contact_has_stopped_typing;
2497                    statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.getDisplayName(user)));
2498                    statusMessage.setTrueCounterpart(user.getRealJid());
2499                    statusMessage.setCounterpart(user.getFullJid());
2500                } else {
2501                    int id = state == ChatState.COMPOSING ? R.string.contacts_are_typing : R.string.contacts_have_stopped_typing;
2502                    statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.concatNames(users)));
2503                    statusMessage.setCounterparts(users);
2504                }
2505                this.messageList.add(statusMessage);
2506            }
2507
2508        }
2509    }
2510
2511    private void stopScrolling() {
2512        long now = SystemClock.uptimeMillis();
2513        MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
2514        binding.messagesView.dispatchTouchEvent(cancel);
2515    }
2516
2517    private boolean showLoadMoreMessages(final Conversation c) {
2518        if (activity == null || activity.xmppConnectionService == null) {
2519            return false;
2520        }
2521        final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
2522        final MessageArchiveService service = activity.xmppConnectionService.getMessageArchiveService();
2523        return mam && (c.getLastClearHistory().getTimestamp() != 0 || (c.countMessages() == 0 && c.messagesLoaded.get() && c.hasMessagesLeftOnServer() && !service.queryInProgress(c)));
2524    }
2525
2526    private boolean hasMamSupport(final Conversation c) {
2527        if (c.getMode() == Conversation.MODE_SINGLE) {
2528            final XmppConnection connection = c.getAccount().getXmppConnection();
2529            return connection != null && connection.getFeatures().mam();
2530        } else {
2531            return c.getMucOptions().mamSupport();
2532        }
2533    }
2534
2535    protected void showSnackbar(final int message, final int action, final OnClickListener clickListener) {
2536        showSnackbar(message, action, clickListener, null);
2537    }
2538
2539    protected void showSnackbar(final int message, final int action, final OnClickListener clickListener, final View.OnLongClickListener longClickListener) {
2540        this.binding.snackbar.setVisibility(View.VISIBLE);
2541        this.binding.snackbar.setOnClickListener(null);
2542        this.binding.snackbarMessage.setText(message);
2543        this.binding.snackbarMessage.setOnClickListener(null);
2544        this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
2545        if (action != 0) {
2546            this.binding.snackbarAction.setText(action);
2547        }
2548        this.binding.snackbarAction.setOnClickListener(clickListener);
2549        this.binding.snackbarAction.setOnLongClickListener(longClickListener);
2550    }
2551
2552    protected void hideSnackbar() {
2553        this.binding.snackbar.setVisibility(View.GONE);
2554    }
2555
2556    protected void sendMessage(Message message) {
2557        activity.xmppConnectionService.sendMessage(message);
2558        messageSent();
2559    }
2560
2561    protected void sendPgpMessage(final Message message) {
2562        final XmppConnectionService xmppService = activity.xmppConnectionService;
2563        final Contact contact = message.getConversation().getContact();
2564        if (!activity.hasPgp()) {
2565            activity.showInstallPgpDialog();
2566            return;
2567        }
2568        if (conversation.getAccount().getPgpSignature() == null) {
2569            activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
2570            return;
2571        }
2572        if (!mSendingPgpMessage.compareAndSet(false, true)) {
2573            Log.d(Config.LOGTAG, "sending pgp message already in progress");
2574        }
2575        if (conversation.getMode() == Conversation.MODE_SINGLE) {
2576            if (contact.getPgpKeyId() != 0) {
2577                xmppService.getPgpEngine().hasKey(contact,
2578                        new UiCallback<Contact>() {
2579
2580                            @Override
2581                            public void userInputRequired(PendingIntent pi, Contact contact) {
2582                                startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
2583                            }
2584
2585                            @Override
2586                            public void success(Contact contact) {
2587                                encryptTextMessage(message);
2588                            }
2589
2590                            @Override
2591                            public void error(int error, Contact contact) {
2592                                activity.runOnUiThread(() -> Toast.makeText(activity,
2593                                        R.string.unable_to_connect_to_keychain,
2594                                        Toast.LENGTH_SHORT
2595                                ).show());
2596                                mSendingPgpMessage.set(false);
2597                            }
2598                        });
2599
2600            } else {
2601                showNoPGPKeyDialog(false, (dialog, which) -> {
2602                    conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2603                    xmppService.updateConversation(conversation);
2604                    message.setEncryption(Message.ENCRYPTION_NONE);
2605                    xmppService.sendMessage(message);
2606                    messageSent();
2607                });
2608            }
2609        } else {
2610            if (conversation.getMucOptions().pgpKeysInUse()) {
2611                if (!conversation.getMucOptions().everybodyHasKeys()) {
2612                    Toast warning = Toast
2613                            .makeText(getActivity(),
2614                                    R.string.missing_public_keys,
2615                                    Toast.LENGTH_LONG);
2616                    warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
2617                    warning.show();
2618                }
2619                encryptTextMessage(message);
2620            } else {
2621                showNoPGPKeyDialog(true, (dialog, which) -> {
2622                    conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2623                    message.setEncryption(Message.ENCRYPTION_NONE);
2624                    xmppService.updateConversation(conversation);
2625                    xmppService.sendMessage(message);
2626                    messageSent();
2627                });
2628            }
2629        }
2630    }
2631
2632    public void encryptTextMessage(Message message) {
2633        activity.xmppConnectionService.getPgpEngine().encrypt(message,
2634                new UiCallback<Message>() {
2635
2636                    @Override
2637                    public void userInputRequired(PendingIntent pi, Message message) {
2638                        startPendingIntent(pi, REQUEST_SEND_MESSAGE);
2639                    }
2640
2641                    @Override
2642                    public void success(Message message) {
2643                        //TODO the following two call can be made before the callback
2644                        getActivity().runOnUiThread(() -> messageSent());
2645                    }
2646
2647                    @Override
2648                    public void error(final int error, Message message) {
2649                        getActivity().runOnUiThread(() -> {
2650                            doneSendingPgpMessage();
2651                            Toast.makeText(getActivity(), error == 0 ? R.string.unable_to_connect_to_keychain : error, Toast.LENGTH_SHORT).show();
2652                        });
2653
2654                    }
2655                });
2656    }
2657
2658    public void showNoPGPKeyDialog(boolean plural, DialogInterface.OnClickListener listener) {
2659        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
2660        builder.setIconAttribute(android.R.attr.alertDialogIcon);
2661        if (plural) {
2662            builder.setTitle(getString(R.string.no_pgp_keys));
2663            builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
2664        } else {
2665            builder.setTitle(getString(R.string.no_pgp_key));
2666            builder.setMessage(getText(R.string.contact_has_no_pgp_key));
2667        }
2668        builder.setNegativeButton(getString(R.string.cancel), null);
2669        builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
2670        builder.create().show();
2671    }
2672
2673    public void appendText(String text, final boolean doNotAppend) {
2674        if (text == null) {
2675            return;
2676        }
2677        final Editable editable = this.binding.textinput.getText();
2678        String previous = editable == null ? "" : editable.toString();
2679        if (doNotAppend && !TextUtils.isEmpty(previous)) {
2680            Toast.makeText(getActivity(), R.string.already_drafting_message, Toast.LENGTH_LONG).show();
2681            return;
2682        }
2683        if (UIHelper.isLastLineQuote(previous)) {
2684            text = '\n' + text;
2685        } else if (previous.length() != 0 && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {
2686            text = " " + text;
2687        }
2688        this.binding.textinput.append(text);
2689    }
2690
2691    @Override
2692    public boolean onEnterPressed() {
2693        SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
2694        final boolean enterIsSend = p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
2695        if (enterIsSend) {
2696            sendMessage();
2697            return true;
2698        } else {
2699            return false;
2700        }
2701    }
2702
2703    @Override
2704    public void onTypingStarted() {
2705        final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2706        if (service == null) {
2707            return;
2708        }
2709        Account.State status = conversation.getAccount().getStatus();
2710        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
2711            service.sendChatState(conversation);
2712        }
2713        runOnUiThread(this::updateSendButton);
2714    }
2715
2716    @Override
2717    public void onTypingStopped() {
2718        final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2719        if (service == null) {
2720            return;
2721        }
2722        Account.State status = conversation.getAccount().getStatus();
2723        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
2724            service.sendChatState(conversation);
2725        }
2726    }
2727
2728    @Override
2729    public void onTextDeleted() {
2730        final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2731        if (service == null) {
2732            return;
2733        }
2734        Account.State status = conversation.getAccount().getStatus();
2735        if (status == Account.State.ONLINE && conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
2736            service.sendChatState(conversation);
2737        }
2738        if (storeNextMessage()) {
2739            runOnUiThread(() -> {
2740                if (activity == null) {
2741                    return;
2742                }
2743                activity.onConversationsListItemUpdated();
2744            });
2745        }
2746        runOnUiThread(this::updateSendButton);
2747    }
2748
2749    @Override
2750    public void onTextChanged() {
2751        if (conversation != null && conversation.getCorrectingMessage() != null) {
2752            runOnUiThread(this::updateSendButton);
2753        }
2754    }
2755
2756    @Override
2757    public boolean onTabPressed(boolean repeated) {
2758        if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
2759            return false;
2760        }
2761        if (repeated) {
2762            completionIndex++;
2763        } else {
2764            lastCompletionLength = 0;
2765            completionIndex = 0;
2766            final String content = this.binding.textinput.getText().toString();
2767            lastCompletionCursor = this.binding.textinput.getSelectionEnd();
2768            int start = lastCompletionCursor > 0 ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1 : 0;
2769            firstWord = start == 0;
2770            incomplete = content.substring(start, lastCompletionCursor);
2771        }
2772        List<String> completions = new ArrayList<>();
2773        for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
2774            String name = user.getName();
2775            if (name != null && name.startsWith(incomplete)) {
2776                completions.add(name + (firstWord ? ": " : " "));
2777            }
2778        }
2779        Collections.sort(completions);
2780        if (completions.size() > completionIndex) {
2781            String completion = completions.get(completionIndex).substring(incomplete.length());
2782            this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
2783            this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
2784            lastCompletionLength = completion.length();
2785        } else {
2786            completionIndex = -1;
2787            this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
2788            lastCompletionLength = 0;
2789        }
2790        return true;
2791    }
2792
2793    private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
2794        try {
2795            getActivity().startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0);
2796        } catch (final SendIntentException ignored) {
2797        }
2798    }
2799
2800    @Override
2801    public void onBackendConnected() {
2802        Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
2803        String uuid = pendingConversationsUuid.pop();
2804        if (uuid != null) {
2805            if (!findAndReInitByUuidOrArchive(uuid)) {
2806                return;
2807            }
2808        } else {
2809            if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) {
2810                clearPending();
2811                activity.onConversationArchived(conversation);
2812                return;
2813            }
2814        }
2815        ActivityResult activityResult = postponedActivityResult.pop();
2816        if (activityResult != null) {
2817            handleActivityResult(activityResult);
2818        }
2819        clearPending();
2820    }
2821
2822    private boolean findAndReInitByUuidOrArchive(@NonNull final String uuid) {
2823        Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
2824        if (conversation == null) {
2825            clearPending();
2826            activity.onConversationArchived(null);
2827            return false;
2828        }
2829        reInit(conversation);
2830        ScrollState scrollState = pendingScrollState.pop();
2831        String lastMessageUuid = pendingLastMessageUuid.pop();
2832        List<Attachment> attachments = pendingMediaPreviews.pop();
2833        if (scrollState != null) {
2834            setScrollPosition(scrollState, lastMessageUuid);
2835        }
2836        if (attachments != null && attachments.size() > 0) {
2837            Log.d(Config.LOGTAG, "had attachments on restore");
2838            mediaPreviewAdapter.addMediaPreviews(attachments);
2839            toggleInputMethod();
2840        }
2841        return true;
2842    }
2843
2844    private void clearPending() {
2845        if (postponedActivityResult.clear()) {
2846            Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
2847        }
2848        if (pendingScrollState.clear()) {
2849            Log.e(Config.LOGTAG, "cleared scroll state");
2850        }
2851        if (pendingTakePhotoUri.clear()) {
2852            Log.e(Config.LOGTAG, "cleared pending photo uri");
2853        }
2854        if (pendingConversationsUuid.clear()) {
2855            Log.e(Config.LOGTAG, "cleared pending conversations uuid");
2856        }
2857        if (pendingMediaPreviews.clear()) {
2858            Log.e(Config.LOGTAG, "cleared pending media previews");
2859        }
2860    }
2861
2862    public Conversation getConversation() {
2863        return conversation;
2864    }
2865
2866    @Override
2867    public void onContactPictureLongClicked(View v, final Message message) {
2868        final String fingerprint;
2869        if (message.getEncryption() == Message.ENCRYPTION_PGP || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
2870            fingerprint = "pgp";
2871        } else {
2872            fingerprint = message.getFingerprint();
2873        }
2874        final PopupMenu popupMenu = new PopupMenu(getActivity(), v);
2875        final Contact contact = message.getContact();
2876        if (message.getStatus() <= Message.STATUS_RECEIVED && (contact == null || !contact.isSelf())) {
2877            if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
2878                final Jid cp = message.getCounterpart();
2879                if (cp == null || cp.isBareJid()) {
2880                    return;
2881                }
2882                final Jid tcp = message.getTrueCounterpart();
2883                final User userByRealJid = tcp != null ? conversation.getMucOptions().findOrCreateUserByRealJid(tcp, cp) : null;
2884                final User user = userByRealJid != null ? userByRealJid : conversation.getMucOptions().findUserByFullJid(cp);
2885                popupMenu.inflate(R.menu.muc_details_context);
2886                final Menu menu = popupMenu.getMenu();
2887                MucDetailsContextMenuHelper.configureMucDetailsContextMenu(activity, menu, conversation, user);
2888                popupMenu.setOnMenuItemClickListener(menuItem -> MucDetailsContextMenuHelper.onContextItemSelected(menuItem, user, activity, fingerprint));
2889            } else {
2890                popupMenu.inflate(R.menu.one_on_one_context);
2891                popupMenu.setOnMenuItemClickListener(item -> {
2892                    switch (item.getItemId()) {
2893                        case R.id.action_contact_details:
2894                            activity.switchToContactDetails(message.getContact(), fingerprint);
2895                            break;
2896                        case R.id.action_show_qr_code:
2897                            activity.showQrCode("xmpp:" + message.getContact().getJid().asBareJid().toEscapedString());
2898                            break;
2899                    }
2900                    return true;
2901                });
2902            }
2903        } else {
2904            popupMenu.inflate(R.menu.account_context);
2905            final Menu menu = popupMenu.getMenu();
2906            menu.findItem(R.id.action_manage_accounts).setVisible(QuickConversationsService.isConversations());
2907            popupMenu.setOnMenuItemClickListener(item -> {
2908                switch (item.getItemId()) {
2909                    case R.id.action_show_qr_code:
2910                        activity.showQrCode(conversation.getAccount().getShareableUri());
2911                        break;
2912                    case R.id.action_account_details:
2913                        activity.switchToAccount(message.getConversation().getAccount(), fingerprint);
2914                        break;
2915                    case R.id.action_manage_accounts:
2916                        AccountUtils.launchManageAccounts(activity);
2917                        break;
2918                }
2919                return true;
2920            });
2921        }
2922        popupMenu.show();
2923    }
2924
2925    @Override
2926    public void onContactPictureClicked(Message message) {
2927        String fingerprint;
2928        if (message.getEncryption() == Message.ENCRYPTION_PGP || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
2929            fingerprint = "pgp";
2930        } else {
2931            fingerprint = message.getFingerprint();
2932        }
2933        final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
2934        if (received) {
2935            if (message.getConversation() instanceof Conversation && message.getConversation().getMode() == Conversation.MODE_MULTI) {
2936                Jid tcp = message.getTrueCounterpart();
2937                Jid user = message.getCounterpart();
2938                if (user != null && !user.isBareJid()) {
2939                    final MucOptions mucOptions = ((Conversation) message.getConversation()).getMucOptions();
2940                    if (mucOptions.participating() || ((Conversation) message.getConversation()).getNextCounterpart() != null) {
2941                        if (!mucOptions.isUserInRoom(user) && mucOptions.findUserByRealJid(tcp == null ? null : tcp.asBareJid()) == null) {
2942                            Toast.makeText(getActivity(), activity.getString(R.string.user_has_left_conference, user.getResource()), Toast.LENGTH_SHORT).show();
2943                        }
2944                        highlightInConference(user.getResource());
2945                    } else {
2946                        Toast.makeText(getActivity(), R.string.you_are_not_participating, Toast.LENGTH_SHORT).show();
2947                    }
2948                }
2949                return;
2950            } else {
2951                if (!message.getContact().isSelf()) {
2952                    activity.switchToContactDetails(message.getContact(), fingerprint);
2953                    return;
2954                }
2955            }
2956        }
2957        activity.switchToAccount(message.getConversation().getAccount(), fingerprint);
2958    }
2959}