ConversationFragment.java

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