ConversationFragment.java

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