ConversationFragment.java

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