ConversationFragment.java

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