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