ConversationFragment.java

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