ConversationFragment.java

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