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