ConversationFragment.java

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