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