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