ConversationFragment.java

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