ConversationFragment.java

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