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