ConversationFragment.java

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