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