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