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						final MucOptions mucOptions = message.getConversation().getMucOptions();
 880						if (mucOptions.participating() || message.getConversation().getNextCounterpart() != null) {
 881							if (!mucOptions.isUserInRoom(user)) {
 882								Toast.makeText(getActivity(), activity.getString(R.string.user_has_left_conference, user.getResource()), Toast.LENGTH_SHORT).show();
 883							}
 884							highlightInConference(user.getResource());
 885						} else {
 886							Toast.makeText(getActivity(),R.string.you_are_not_participating, Toast.LENGTH_SHORT).show();
 887						}
 888					}
 889					return;
 890				} else {
 891					if (!message.getContact().isSelf()) {
 892						String fingerprint;
 893						if (message.getEncryption() == Message.ENCRYPTION_PGP
 894								|| message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 895							fingerprint = "pgp";
 896						} else {
 897							fingerprint = message.getFingerprint();
 898						}
 899						activity.switchToContactDetails(message.getContact(), fingerprint);
 900						return;
 901					}
 902				}
 903			}
 904			Account account = message.getConversation().getAccount();
 905			Intent intent = new Intent(activity, EditAccountActivity.class);
 906			intent.putExtra("jid", account.getJid().asBareJid().toString());
 907			String fingerprint;
 908			if (message.getEncryption() == Message.ENCRYPTION_PGP
 909					|| message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 910				fingerprint = "pgp";
 911			} else {
 912				fingerprint = message.getFingerprint();
 913			}
 914			intent.putExtra("fingerprint", fingerprint);
 915			startActivity(intent);
 916		});
 917		messageListAdapter.setOnContactPictureLongClicked(message -> {
 918			if (message.getStatus() <= Message.STATUS_RECEIVED) {
 919				if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
 920					final MucOptions mucOptions = conversation.getMucOptions();
 921					if (!mucOptions.allowPm()) {
 922						Toast.makeText(getActivity(), R.string.private_messages_are_disabled, Toast.LENGTH_SHORT).show();
 923						return;
 924					}
 925					Jid user = message.getCounterpart();
 926					if (user != null && !user.isBareJid()) {
 927						if (mucOptions.isUserInRoom(user)) {
 928							privateMessageWith(user);
 929						} else {
 930							Toast.makeText(getActivity(), activity.getString(R.string.user_has_left_conference, user.getResource()), Toast.LENGTH_SHORT).show();
 931						}
 932					}
 933				}
 934			} else {
 935				activity.showQrCode(conversation.getAccount().getShareableUri());
 936			}
 937		});
 938		messageListAdapter.setOnQuoteListener(this::quoteText);
 939		binding.messagesView.setAdapter(messageListAdapter);
 940
 941		registerForContextMenu(binding.messagesView);
 942
 943		return binding.getRoot();
 944	}
 945
 946	private void quoteText(String text) {
 947		if (binding.textinput.isEnabled()) {
 948			text = text.replaceAll("(\n *){2,}", "\n").replaceAll("(^|\n)", "$1> ").replaceAll("\n$", "");
 949			Editable editable = binding.textinput.getEditableText();
 950			int position = binding.textinput.getSelectionEnd();
 951			if (position == -1) position = editable.length();
 952			if (position > 0 && editable.charAt(position - 1) != '\n') {
 953				editable.insert(position++, "\n");
 954			}
 955			editable.insert(position, text);
 956			position += text.length();
 957			editable.insert(position++, "\n");
 958			if (position < editable.length() && editable.charAt(position) != '\n') {
 959				editable.insert(position, "\n");
 960			}
 961			binding.textinput.setSelection(position);
 962			binding.textinput.requestFocus();
 963			InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
 964			if (inputMethodManager != null) {
 965				inputMethodManager.showSoftInput(binding.textinput, InputMethodManager.SHOW_IMPLICIT);
 966			}
 967		}
 968	}
 969
 970	private static void hideSoftKeyboard(final Activity activity) {
 971		InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
 972		View view = activity.getCurrentFocus();
 973		if (view != null && imm != null) {
 974			imm.hideSoftInputFromWindow(view.getWindowToken(),0);
 975		}
 976	}
 977
 978	private void quoteMessage(Message message) {
 979		quoteText(MessageUtils.prepareQuote(message));
 980	}
 981
 982	@Override
 983	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
 984		synchronized (this.messageList) {
 985			super.onCreateContextMenu(menu, v, menuInfo);
 986			AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
 987			this.selectedMessage = this.messageList.get(acmi.position);
 988			populateContextMenu(menu);
 989		}
 990	}
 991
 992	private void populateContextMenu(ContextMenu menu) {
 993		final Message m = this.selectedMessage;
 994		final Transferable t = m.getTransferable();
 995		Message relevantForCorrection = m;
 996		while (relevantForCorrection.mergeable(relevantForCorrection.next())) {
 997			relevantForCorrection = relevantForCorrection.next();
 998		}
 999		if (m.getType() != Message.TYPE_STATUS) {
1000			final boolean treatAsFile = m.getType() != Message.TYPE_TEXT
1001					&& m.getType() != Message.TYPE_PRIVATE
1002					&& t == null;
1003			final boolean encrypted = m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED
1004					|| m.getEncryption() == Message.ENCRYPTION_PGP;
1005			activity.getMenuInflater().inflate(R.menu.message_context, menu);
1006			menu.setHeaderTitle(R.string.message_options);
1007			MenuItem copyMessage = menu.findItem(R.id.copy_message);
1008			MenuItem quoteMessage = menu.findItem(R.id.quote_message);
1009			MenuItem retryDecryption = menu.findItem(R.id.retry_decryption);
1010			MenuItem correctMessage = menu.findItem(R.id.correct_message);
1011			MenuItem shareWith = menu.findItem(R.id.share_with);
1012			MenuItem sendAgain = menu.findItem(R.id.send_again);
1013			MenuItem copyUrl = menu.findItem(R.id.copy_url);
1014			MenuItem downloadFile = menu.findItem(R.id.download_file);
1015			MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
1016			MenuItem deleteFile = menu.findItem(R.id.delete_file);
1017			MenuItem showErrorMessage = menu.findItem(R.id.show_error_message);
1018			if (!treatAsFile && !encrypted && !m.isGeoUri() && !m.treatAsDownloadable()) {
1019				copyMessage.setVisible(true);
1020				quoteMessage.setVisible(MessageUtils.prepareQuote(m).length() > 0);
1021			}
1022			if (m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED) {
1023				retryDecryption.setVisible(true);
1024			}
1025			if (relevantForCorrection.getType() == Message.TYPE_TEXT
1026					&& relevantForCorrection.isLastCorrectableMessage()
1027					&& (m.getConversation().getMucOptions().nonanonymous() || m.getConversation().getMode() == Conversation.MODE_SINGLE)) {
1028				correctMessage.setVisible(true);
1029			}
1030			if (treatAsFile || (m.getType() == Message.TYPE_TEXT && !m.treatAsDownloadable())) {
1031				shareWith.setVisible(true);
1032			}
1033			if (m.getStatus() == Message.STATUS_SEND_FAILED) {
1034				sendAgain.setVisible(true);
1035			}
1036			if (m.hasFileOnRemoteHost()
1037					|| m.isGeoUri()
1038					|| m.treatAsDownloadable()
1039					|| (t != null && t instanceof HttpDownloadConnection)) {
1040				copyUrl.setVisible(true);
1041			}
1042			if ((m.isFileOrImage() && t instanceof TransferablePlaceholder && m.hasFileOnRemoteHost())) {
1043				downloadFile.setVisible(true);
1044				downloadFile.setTitle(activity.getString(R.string.download_x_file, UIHelper.getFileDescriptionString(activity, m)));
1045			}
1046			boolean waitingOfferedSending = m.getStatus() == Message.STATUS_WAITING
1047					|| m.getStatus() == Message.STATUS_UNSEND
1048					|| m.getStatus() == Message.STATUS_OFFERED;
1049			if ((t != null && !(t instanceof TransferablePlaceholder)) || waitingOfferedSending && m.needsUploading()) {
1050				cancelTransmission.setVisible(true);
1051			}
1052			if (treatAsFile) {
1053				String path = m.getRelativeFilePath();
1054				if (path == null || !path.startsWith("/")) {
1055					deleteFile.setVisible(true);
1056					deleteFile.setTitle(activity.getString(R.string.delete_x_file, UIHelper.getFileDescriptionString(activity, m)));
1057				}
1058			}
1059			if (m.getStatus() == Message.STATUS_SEND_FAILED && m.getErrorMessage() != null) {
1060				showErrorMessage.setVisible(true);
1061			}
1062		}
1063	}
1064
1065	@Override
1066	public boolean onContextItemSelected(MenuItem item) {
1067		switch (item.getItemId()) {
1068			case R.id.share_with:
1069				shareWith(selectedMessage);
1070				return true;
1071			case R.id.correct_message:
1072				correctMessage(selectedMessage);
1073				return true;
1074			case R.id.copy_message:
1075				copyMessage(selectedMessage);
1076				return true;
1077			case R.id.quote_message:
1078				quoteMessage(selectedMessage);
1079				return true;
1080			case R.id.send_again:
1081				resendMessage(selectedMessage);
1082				return true;
1083			case R.id.copy_url:
1084				copyUrl(selectedMessage);
1085				return true;
1086			case R.id.download_file:
1087				startDownloadable(selectedMessage);
1088				return true;
1089			case R.id.cancel_transmission:
1090				cancelTransmission(selectedMessage);
1091				return true;
1092			case R.id.retry_decryption:
1093				retryDecryption(selectedMessage);
1094				return true;
1095			case R.id.delete_file:
1096				deleteFile(selectedMessage);
1097				return true;
1098			case R.id.show_error_message:
1099				showErrorMessage(selectedMessage);
1100				return true;
1101			default:
1102				return super.onContextItemSelected(item);
1103		}
1104	}
1105
1106	@Override
1107	public boolean onOptionsItemSelected(final MenuItem item) {
1108		if (conversation == null) {
1109			return super.onOptionsItemSelected(item);
1110		}
1111		switch (item.getItemId()) {
1112			case R.id.encryption_choice_axolotl:
1113			case R.id.encryption_choice_pgp:
1114			case R.id.encryption_choice_none:
1115				handleEncryptionSelection(item);
1116				break;
1117			case R.id.attach_choose_picture:
1118			case R.id.attach_take_picture:
1119			case R.id.attach_record_video:
1120			case R.id.attach_choose_file:
1121			case R.id.attach_record_voice:
1122			case R.id.attach_location:
1123				handleAttachmentSelection(item);
1124				break;
1125			case R.id.action_archive:
1126				activity.xmppConnectionService.archiveConversation(conversation);
1127				activity.onConversationArchived(conversation);
1128				break;
1129			case R.id.action_contact_details:
1130				activity.switchToContactDetails(conversation.getContact());
1131				break;
1132			case R.id.action_muc_details:
1133				Intent intent = new Intent(getActivity(), ConferenceDetailsActivity.class);
1134				intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
1135				intent.putExtra("uuid", conversation.getUuid());
1136				startActivity(intent);
1137				break;
1138			case R.id.action_invite:
1139				startActivityForResult(ChooseContactActivity.create(activity, conversation), REQUEST_INVITE_TO_CONVERSATION);
1140				break;
1141			case R.id.action_clear_history:
1142				clearHistoryDialog(conversation);
1143				break;
1144			case R.id.action_mute:
1145				muteConversationDialog(conversation);
1146				break;
1147			case R.id.action_unmute:
1148				unmuteConversation(conversation);
1149				break;
1150			case R.id.action_block:
1151			case R.id.action_unblock:
1152				final Activity activity = getActivity();
1153				if (activity instanceof XmppActivity) {
1154					BlockContactDialog.show((XmppActivity) activity, conversation);
1155				}
1156				break;
1157			default:
1158				break;
1159		}
1160		return super.onOptionsItemSelected(item);
1161	}
1162
1163	private void handleAttachmentSelection(MenuItem item) {
1164		switch (item.getItemId()) {
1165			case R.id.attach_choose_picture:
1166				attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
1167				break;
1168			case R.id.attach_take_picture:
1169				attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
1170				break;
1171			case R.id.attach_record_video:
1172				attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO);
1173				break;
1174			case R.id.attach_choose_file:
1175				attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
1176				break;
1177			case R.id.attach_record_voice:
1178				attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
1179				break;
1180			case R.id.attach_location:
1181				attachFile(ATTACHMENT_CHOICE_LOCATION);
1182				break;
1183		}
1184	}
1185
1186	private void handleEncryptionSelection(MenuItem item) {
1187		if (conversation == null) {
1188			return;
1189		}
1190		switch (item.getItemId()) {
1191			case R.id.encryption_choice_none:
1192				conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1193				item.setChecked(true);
1194				break;
1195			case R.id.encryption_choice_pgp:
1196				if (activity.hasPgp()) {
1197					if (conversation.getAccount().getPgpSignature() != null) {
1198						conversation.setNextEncryption(Message.ENCRYPTION_PGP);
1199						item.setChecked(true);
1200					} else {
1201						activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
1202					}
1203				} else {
1204					activity.showInstallPgpDialog();
1205				}
1206				break;
1207			case R.id.encryption_choice_axolotl:
1208				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(conversation.getAccount())
1209						+ "Enabled axolotl for Contact " + conversation.getContact().getJid());
1210				conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
1211				item.setChecked(true);
1212				break;
1213			default:
1214				conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1215				break;
1216		}
1217		activity.xmppConnectionService.updateConversation(conversation);
1218		updateChatMsgHint();
1219		getActivity().invalidateOptionsMenu();
1220		activity.refreshUi();
1221	}
1222
1223	public void attachFile(final int attachmentChoice) {
1224		if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO || attachmentChoice == ATTACHMENT_CHOICE_RECORD_VIDEO) {
1225			if (!hasStorageAndCameraPermission(attachmentChoice)) {
1226				return;
1227			}
1228		} else if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
1229			if (!Config.ONLY_INTERNAL_STORAGE && !hasStoragePermission(attachmentChoice)) {
1230				return;
1231			}
1232		}
1233		try {
1234			activity.getPreferences().edit()
1235					.putString(RECENTLY_USED_QUICK_ACTION, SendButtonAction.of(attachmentChoice).toString())
1236					.apply();
1237		} catch (IllegalArgumentException e) {
1238			//just do not save
1239		}
1240		final int encryption = conversation.getNextEncryption();
1241		final int mode = conversation.getMode();
1242		if (encryption == Message.ENCRYPTION_PGP) {
1243			if (activity.hasPgp()) {
1244				if (mode == Conversation.MODE_SINGLE && conversation.getContact().getPgpKeyId() != 0) {
1245					activity.xmppConnectionService.getPgpEngine().hasKey(
1246							conversation.getContact(),
1247							new UiCallback<Contact>() {
1248
1249								@Override
1250								public void userInputRequried(PendingIntent pi, Contact contact) {
1251									startPendingIntent(pi, attachmentChoice);
1252								}
1253
1254								@Override
1255								public void success(Contact contact) {
1256									selectPresenceToAttachFile(attachmentChoice);
1257								}
1258
1259								@Override
1260								public void error(int error, Contact contact) {
1261									activity.replaceToast(getString(error));
1262								}
1263							});
1264				} else if (mode == Conversation.MODE_MULTI && conversation.getMucOptions().pgpKeysInUse()) {
1265					if (!conversation.getMucOptions().everybodyHasKeys()) {
1266						Toast warning = Toast.makeText(getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
1267						warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
1268						warning.show();
1269					}
1270					selectPresenceToAttachFile(attachmentChoice);
1271				} else {
1272					final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
1273							.findFragmentByTag("conversation");
1274					if (fragment != null) {
1275						fragment.showNoPGPKeyDialog(false, (dialog, which) -> {
1276							conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1277							activity.xmppConnectionService.updateConversation(conversation);
1278							selectPresenceToAttachFile(attachmentChoice);
1279						});
1280					}
1281				}
1282			} else {
1283				activity.showInstallPgpDialog();
1284			}
1285		} else {
1286			if (encryption != Message.ENCRYPTION_AXOLOTL || !trustKeysIfNeeded(REQUEST_TRUST_KEYS_MENU, attachmentChoice)) {
1287				selectPresenceToAttachFile(attachmentChoice);
1288			}
1289		}
1290	}
1291
1292	@Override
1293	public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
1294		if (grantResults.length > 0)
1295			if (allGranted(grantResults)) {
1296				if (requestCode == REQUEST_START_DOWNLOAD) {
1297					if (this.mPendingDownloadableMessage != null) {
1298						startDownloadable(this.mPendingDownloadableMessage);
1299					}
1300				} else if (requestCode == REQUEST_ADD_EDITOR_CONTENT) {
1301					if (this.mPendingEditorContent != null) {
1302						attachImageToConversation(this.mPendingEditorContent);
1303					}
1304				} else {
1305					attachFile(requestCode);
1306				}
1307			} else {
1308				@StringRes int res;
1309				if (Manifest.permission.CAMERA.equals(getFirstDenied(grantResults, permissions))) {
1310					res = R.string.no_camera_permission;
1311				} else {
1312					res = R.string.no_storage_permission;
1313				}
1314				Toast.makeText(getActivity(), res, Toast.LENGTH_SHORT).show();
1315			}
1316	}
1317
1318	public void startDownloadable(Message message) {
1319		if (!Config.ONLY_INTERNAL_STORAGE && !hasStoragePermission(REQUEST_START_DOWNLOAD)) {
1320			this.mPendingDownloadableMessage = message;
1321			return;
1322		}
1323		Transferable transferable = message.getTransferable();
1324		if (transferable != null) {
1325			if (!transferable.start()) {
1326				Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT).show();
1327			}
1328		} else if (message.treatAsDownloadable()) {
1329			activity.xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message, true);
1330		}
1331	}
1332
1333	@SuppressLint("InflateParams")
1334	protected void clearHistoryDialog(final Conversation conversation) {
1335		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1336		builder.setTitle(getString(R.string.clear_conversation_history));
1337		final View dialogView = getActivity().getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
1338		final CheckBox endConversationCheckBox = dialogView.findViewById(R.id.end_conversation_checkbox);
1339		builder.setView(dialogView);
1340		builder.setNegativeButton(getString(R.string.cancel), null);
1341		builder.setPositiveButton(getString(R.string.delete_messages), (dialog, which) -> {
1342			this.activity.xmppConnectionService.clearConversationHistory(conversation);
1343			if (endConversationCheckBox.isChecked()) {
1344				this.activity.xmppConnectionService.archiveConversation(conversation);
1345				this.activity.onConversationArchived(conversation);
1346			} else {
1347				activity.onConversationsListItemUpdated();
1348				refresh();
1349			}
1350		});
1351		builder.create().show();
1352	}
1353
1354	protected void muteConversationDialog(final Conversation conversation) {
1355		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1356		builder.setTitle(R.string.disable_notifications);
1357		final int[] durations = getResources().getIntArray(R.array.mute_options_durations);
1358		final CharSequence[] labels = new CharSequence[durations.length];
1359		for (int i = 0; i < durations.length; ++i) {
1360			if (durations[i] == -1) {
1361				labels[i] = getString(R.string.until_further_notice);
1362			} else {
1363				labels[i] = TimeframeUtils.resolve(activity, 1000L * durations[i]);
1364			}
1365		}
1366		builder.setItems(labels, (dialog, which) -> {
1367			final long till;
1368			if (durations[which] == -1) {
1369				till = Long.MAX_VALUE;
1370			} else {
1371				till = System.currentTimeMillis() + (durations[which] * 1000);
1372			}
1373			conversation.setMutedTill(till);
1374			activity.xmppConnectionService.updateConversation(conversation);
1375			activity.onConversationsListItemUpdated();
1376			refresh();
1377			getActivity().invalidateOptionsMenu();
1378		});
1379		builder.create().show();
1380	}
1381
1382	private boolean hasStoragePermission(int requestCode) {
1383		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1384			if (activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
1385				requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
1386				return false;
1387			} else {
1388				return true;
1389			}
1390		} else {
1391			return true;
1392		}
1393	}
1394
1395	private boolean hasStorageAndCameraPermission(int requestCode) {
1396		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1397			List<String> missingPermissions = new ArrayList<>();
1398			if (!Config.ONLY_INTERNAL_STORAGE && activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
1399				missingPermissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
1400			}
1401			if (activity.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
1402				missingPermissions.add(Manifest.permission.CAMERA);
1403			}
1404			if (missingPermissions.size() == 0) {
1405				return true;
1406			} else {
1407				requestPermissions(missingPermissions.toArray(new String[missingPermissions.size()]), requestCode);
1408				return false;
1409			}
1410		} else {
1411			return true;
1412		}
1413	}
1414
1415	public void unmuteConversation(final Conversation conversation) {
1416		conversation.setMutedTill(0);
1417		this.activity.xmppConnectionService.updateConversation(conversation);
1418		this.activity.onConversationsListItemUpdated();
1419		refresh();
1420		getActivity().invalidateOptionsMenu();
1421	}
1422
1423	protected void selectPresenceToAttachFile(final int attachmentChoice) {
1424		final Account account = conversation.getAccount();
1425		final PresenceSelector.OnPresenceSelected callback = () -> {
1426			Intent intent = new Intent();
1427			boolean chooser = false;
1428			String fallbackPackageId = null;
1429			switch (attachmentChoice) {
1430				case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
1431					intent.setAction(Intent.ACTION_GET_CONTENT);
1432					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1433						intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
1434					}
1435					intent.setType("image/*");
1436					chooser = true;
1437					break;
1438				case ATTACHMENT_CHOICE_RECORD_VIDEO:
1439					intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
1440					break;
1441				case ATTACHMENT_CHOICE_TAKE_PHOTO:
1442					final Uri uri = activity.xmppConnectionService.getFileBackend().getTakePhotoUri();
1443					pendingTakePhotoUri.push(uri);
1444					intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
1445					intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
1446					intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1447					intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
1448					break;
1449				case ATTACHMENT_CHOICE_CHOOSE_FILE:
1450					chooser = true;
1451					intent.setType("*/*");
1452					intent.addCategory(Intent.CATEGORY_OPENABLE);
1453					intent.setAction(Intent.ACTION_GET_CONTENT);
1454					break;
1455				case ATTACHMENT_CHOICE_RECORD_VOICE:
1456					intent.setAction(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
1457					fallbackPackageId = "eu.siacs.conversations.voicerecorder";
1458					break;
1459				case ATTACHMENT_CHOICE_LOCATION:
1460					intent.setAction("eu.siacs.conversations.location.request");
1461					fallbackPackageId = "eu.siacs.conversations.sharelocation";
1462					break;
1463			}
1464			if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
1465				if (chooser) {
1466					startActivityForResult(
1467							Intent.createChooser(intent, getString(R.string.perform_action_with)),
1468							attachmentChoice);
1469				} else {
1470					startActivityForResult(intent, attachmentChoice);
1471				}
1472			} else if (fallbackPackageId != null) {
1473				startActivity(getInstallApkIntent(fallbackPackageId));
1474			}
1475		};
1476		if (account.httpUploadAvailable() || attachmentChoice == ATTACHMENT_CHOICE_LOCATION) {
1477			conversation.setNextCounterpart(null);
1478			callback.onPresenceSelected();
1479		} else {
1480			activity.selectPresence(conversation, callback);
1481		}
1482	}
1483
1484	private Intent getInstallApkIntent(final String packageId) {
1485		Intent intent = new Intent(Intent.ACTION_VIEW);
1486		intent.setData(Uri.parse("market://details?id=" + packageId));
1487		if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
1488			return intent;
1489		} else {
1490			intent.setData(Uri.parse("http://play.google.com/store/apps/details?id=" + packageId));
1491			return intent;
1492		}
1493	}
1494
1495	@Override
1496	public void onResume() {
1497		new Handler().post(() -> {
1498			final Activity activity = getActivity();
1499			if (activity == null) {
1500				return;
1501			}
1502			final PackageManager packageManager = activity.getPackageManager();
1503			ConversationMenuConfigurator.updateAttachmentAvailability(packageManager);
1504			getActivity().invalidateOptionsMenu();
1505		});
1506		super.onResume();
1507		if (activity != null && this.conversation != null) {
1508			activity.onConversationRead(this.conversation);
1509		}
1510	}
1511
1512	private void showErrorMessage(final Message message) {
1513		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1514		builder.setTitle(R.string.error_message);
1515		builder.setMessage(message.getErrorMessage());
1516		builder.setPositiveButton(R.string.confirm, null);
1517		builder.create().show();
1518	}
1519
1520	private void shareWith(Message message) {
1521		Intent shareIntent = new Intent();
1522		shareIntent.setAction(Intent.ACTION_SEND);
1523		if (message.isGeoUri()) {
1524			shareIntent.putExtra(Intent.EXTRA_TEXT, message.getBody());
1525			shareIntent.setType("text/plain");
1526		} else if (!message.isFileOrImage()) {
1527			shareIntent.putExtra(Intent.EXTRA_TEXT, message.getMergedBody().toString());
1528			shareIntent.setType("text/plain");
1529		} else {
1530			final DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
1531			try {
1532				shareIntent.putExtra(Intent.EXTRA_STREAM, FileBackend.getUriForFile(getActivity(), file));
1533			} catch (SecurityException e) {
1534				Toast.makeText(getActivity(), activity.getString(R.string.no_permission_to_access_x, file.getAbsolutePath()), Toast.LENGTH_SHORT).show();
1535				return;
1536			}
1537			shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1538			String mime = message.getMimeType();
1539			if (mime == null) {
1540				mime = "*/*";
1541			}
1542			shareIntent.setType(mime);
1543		}
1544		try {
1545			startActivity(Intent.createChooser(shareIntent, getText(R.string.share_with)));
1546		} catch (ActivityNotFoundException e) {
1547			//This should happen only on faulty androids because normally chooser is always available
1548			Toast.makeText(getActivity(), R.string.no_application_found_to_open_file, Toast.LENGTH_SHORT).show();
1549		}
1550	}
1551
1552	private void copyMessage(Message message) {
1553		if (activity.copyTextToClipboard(message.getMergedBody().toString(), R.string.message)) {
1554			Toast.makeText(getActivity(), R.string.message_copied_to_clipboard, Toast.LENGTH_SHORT).show();
1555		}
1556	}
1557
1558	private void deleteFile(Message message) {
1559		if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
1560			message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1561			activity.onConversationsListItemUpdated();
1562			refresh();
1563		}
1564	}
1565
1566	private void resendMessage(final Message message) {
1567		if (message.isFileOrImage()) {
1568			DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
1569			if (file.exists()) {
1570				final Conversation conversation = message.getConversation();
1571				final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
1572				if (!message.hasFileOnRemoteHost()
1573						&& xmppConnection != null
1574						&& !xmppConnection.getFeatures().httpUpload(message.getFileParams().size)) {
1575					activity.selectPresence(conversation, () -> {
1576						message.setCounterpart(conversation.getNextCounterpart());
1577						activity.xmppConnectionService.resendFailedMessages(message);
1578						new Handler().post(() -> {
1579							int size = messageList.size();
1580							this.binding.messagesView.setSelection(size - 1);
1581						});
1582					});
1583					return;
1584				}
1585			} else {
1586				Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
1587				message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1588				activity.onConversationsListItemUpdated();
1589				refresh();
1590				return;
1591			}
1592		}
1593		activity.xmppConnectionService.resendFailedMessages(message);
1594		new Handler().post(() -> {
1595			int size = messageList.size();
1596			this.binding.messagesView.setSelection(size - 1);
1597		});
1598	}
1599
1600	private void copyUrl(Message message) {
1601		final String url;
1602		final int resId;
1603		if (message.isGeoUri()) {
1604			resId = R.string.location;
1605			url = message.getBody();
1606		} else if (message.hasFileOnRemoteHost()) {
1607			resId = R.string.file_url;
1608			url = message.getFileParams().url.toString();
1609		} else {
1610			url = message.getBody().trim();
1611			resId = R.string.file_url;
1612		}
1613		if (activity.copyTextToClipboard(url, resId)) {
1614			Toast.makeText(getActivity(), R.string.url_copied_to_clipboard, Toast.LENGTH_SHORT).show();
1615		}
1616	}
1617
1618	private void cancelTransmission(Message message) {
1619		Transferable transferable = message.getTransferable();
1620		if (transferable != null) {
1621			transferable.cancel();
1622		} else if (message.getStatus() != Message.STATUS_RECEIVED) {
1623			activity.xmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
1624		}
1625	}
1626
1627	private void retryDecryption(Message message) {
1628		message.setEncryption(Message.ENCRYPTION_PGP);
1629		activity.onConversationsListItemUpdated();
1630		refresh();
1631		conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
1632	}
1633
1634	private void privateMessageWith(final Jid counterpart) {
1635		if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1636			activity.xmppConnectionService.sendChatState(conversation);
1637		}
1638		this.binding.textinput.setText("");
1639		this.conversation.setNextCounterpart(counterpart);
1640		updateChatMsgHint();
1641		updateSendButton();
1642		updateEditablity();
1643	}
1644
1645	private void correctMessage(Message message) {
1646		while (message.mergeable(message.next())) {
1647			message = message.next();
1648		}
1649		this.conversation.setCorrectingMessage(message);
1650		final Editable editable = binding.textinput.getText();
1651		this.conversation.setDraftMessage(editable.toString());
1652		this.binding.textinput.setText("");
1653		this.binding.textinput.append(message.getBody());
1654
1655	}
1656
1657	private void highlightInConference(String nick) {
1658		final Editable editable = this.binding.textinput.getText();
1659		String oldString = editable.toString().trim();
1660		final int pos = this.binding.textinput.getSelectionStart();
1661		if (oldString.isEmpty() || pos == 0) {
1662			editable.insert(0, nick + ": ");
1663		} else {
1664			final char before = editable.charAt(pos - 1);
1665			final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
1666			if (before == '\n') {
1667				editable.insert(pos, nick + ": ");
1668			} else {
1669				if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
1670					if (NickValidityChecker.check(conversation, Arrays.asList(editable.subSequence(0, pos - 2).toString().split(", ")))) {
1671						editable.insert(pos - 2, ", " + nick);
1672						return;
1673					}
1674				}
1675				editable.insert(pos, (Character.isWhitespace(before) ? "" : " ") + nick + (Character.isWhitespace(after) ? "" : " "));
1676				if (Character.isWhitespace(after)) {
1677					this.binding.textinput.setSelection(this.binding.textinput.getSelectionStart() + 1);
1678				}
1679			}
1680		}
1681	}
1682
1683	@Override
1684	public void onSaveInstanceState(Bundle outState) {
1685		super.onSaveInstanceState(outState);
1686		if (conversation != null) {
1687			outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
1688			final Uri uri = pendingTakePhotoUri.peek();
1689			if (uri != null) {
1690				outState.putString(STATE_PHOTO_URI, uri.toString());
1691			}
1692			final ScrollState scrollState = getScrollPosition();
1693			if (scrollState != null) {
1694				outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
1695			}
1696		}
1697	}
1698
1699	@Override
1700	public void onActivityCreated(Bundle savedInstanceState) {
1701		super.onActivityCreated(savedInstanceState);
1702		if (savedInstanceState == null) {
1703			return;
1704		}
1705		String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
1706		if (uuid != null) {
1707			this.pendingConversationsUuid.push(uuid);
1708			String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
1709			if (takePhotoUri != null) {
1710				pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
1711			}
1712			pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
1713		}
1714	}
1715
1716	@Override
1717	public void onStart() {
1718		super.onStart();
1719		if (this.reInitRequiredOnStart) {
1720			final Bundle extras = pendingExtras.pop();
1721			reInit(conversation, extras != null);
1722			if (extras != null) {
1723				processExtras(extras);
1724			}
1725		} else {
1726			Log.d(Config.LOGTAG, "skipped reinit on start");
1727		}
1728	}
1729
1730	@Override
1731	public void onStop() {
1732		super.onStop();
1733		final Activity activity = getActivity();
1734		if (activity == null || !activity.isChangingConfigurations()) {
1735			hideSoftKeyboard(activity);
1736			messageListAdapter.stopAudioPlayer();
1737		}
1738		if (this.conversation != null) {
1739			final String msg = this.binding.textinput.getText().toString();
1740			if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED && this.conversation.setNextMessage(msg)) {
1741				this.activity.xmppConnectionService.updateConversation(this.conversation);
1742			}
1743			updateChatState(this.conversation, msg);
1744			this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
1745		}
1746		this.reInitRequiredOnStart = true;
1747	}
1748
1749	private void updateChatState(final Conversation conversation, final String msg) {
1750		ChatState state = msg.length() == 0 ? Config.DEFAULT_CHATSTATE : ChatState.PAUSED;
1751		Account.State status = conversation.getAccount().getStatus();
1752		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
1753			activity.xmppConnectionService.sendChatState(conversation);
1754		}
1755	}
1756
1757	private void saveMessageDraftStopAudioPlayer() {
1758		final Conversation previousConversation = this.conversation;
1759		if (this.activity == null || this.binding == null || previousConversation == null) {
1760			return;
1761		}
1762		Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
1763		final String msg = this.binding.textinput.getText().toString();
1764		if (previousConversation.setNextMessage(msg)) {
1765			activity.xmppConnectionService.updateConversation(previousConversation);
1766		}
1767		updateChatState(this.conversation, msg);
1768		messageListAdapter.stopAudioPlayer();
1769	}
1770
1771	public void reInit(Conversation conversation, Bundle extras) {
1772		this.saveMessageDraftStopAudioPlayer();
1773		if (this.reInit(conversation, extras != null)) {
1774			if (extras != null) {
1775				processExtras(extras);
1776			}
1777			this.reInitRequiredOnStart = false;
1778		} else {
1779			this.reInitRequiredOnStart = true;
1780			pendingExtras.push(extras);
1781		}
1782	}
1783
1784	private void reInit(Conversation conversation) {
1785		reInit(conversation, false);
1786	}
1787
1788	private boolean reInit(final Conversation conversation, final boolean hasExtras) {
1789		if (conversation == null) {
1790			return false;
1791		}
1792		this.conversation = conversation;
1793		//once we set the conversation all is good and it will automatically do the right thing in onStart()
1794		if (this.activity == null || this.binding == null) {
1795			return false;
1796		}
1797		stopScrolling();
1798		Log.d(Config.LOGTAG, "reInit(hasExtras=" + Boolean.toString(hasExtras) + ")");
1799
1800		if (this.conversation.isRead() && hasExtras) {
1801			Log.d(Config.LOGTAG, "trimming conversation");
1802			this.conversation.trim();
1803		}
1804
1805		setupIme();
1806
1807		final boolean scrolledToBottomAndNoPending = this.scrolledToBottom() && pendingScrollState.peek() == null;
1808
1809		this.binding.textSendButton.setContentDescription(activity.getString(R.string.send_message_to_x, conversation.getName()));
1810		this.binding.textinput.setKeyboardListener(null);
1811		this.binding.textinput.setText("");
1812		this.binding.textinput.append(this.conversation.getNextMessage());
1813		this.binding.textinput.setKeyboardListener(this);
1814		messageListAdapter.updatePreferences();
1815		refresh(false);
1816		this.conversation.messagesLoaded.set(true);
1817
1818		Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + Boolean.toString(scrolledToBottomAndNoPending));
1819
1820		if (hasExtras || scrolledToBottomAndNoPending) {
1821			synchronized (this.messageList) {
1822				Log.d(Config.LOGTAG, "jump to first unread message");
1823				final Message first = conversation.getFirstUnreadMessage();
1824				final int bottom = Math.max(0, this.messageList.size() - 1);
1825				final int pos;
1826				if (first == null) {
1827					pos = bottom;
1828				} else {
1829					int i = getIndexOf(first.getUuid(), this.messageList);
1830					pos = i < 0 ? bottom : i;
1831				}
1832				setSelection(pos);
1833			}
1834		}
1835
1836		activity.onConversationRead(this.conversation);
1837		//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
1838		activity.xmppConnectionService.getNotificationService().setOpenConversation(this.conversation);
1839		return true;
1840	}
1841
1842	private void setSelection(int pos) {
1843		this.binding.messagesView.setSelection(pos);
1844		this.binding.messagesView.post(() -> this.binding.messagesView.setSelection(pos));
1845	}
1846
1847	private boolean scrolledToBottom() {
1848		if (this.binding == null) {
1849			return false;
1850		}
1851		final ListView listView = this.binding.messagesView;
1852		if (listView.getLastVisiblePosition() == listView.getAdapter().getCount() - 1) {
1853			final View lastChild = listView.getChildAt(listView.getChildCount() - 1);
1854			return lastChild != null && lastChild.getBottom() <= listView.getHeight();
1855		} else {
1856			return false;
1857		}
1858	}
1859
1860	private void processExtras(Bundle extras) {
1861		final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
1862		final String text = extras.getString(ConversationsActivity.EXTRA_TEXT);
1863		final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
1864		final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
1865		if (nick != null) {
1866			if (pm) {
1867				Jid jid = conversation.getJid();
1868				try {
1869					Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
1870					privateMessageWith(next);
1871				} catch (final IllegalArgumentException ignored) {
1872					//do nothing
1873				}
1874			} else {
1875				final MucOptions mucOptions = conversation.getMucOptions();
1876				if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
1877					highlightInConference(nick);
1878				}
1879			}
1880		} else {
1881			appendText(text);
1882		}
1883		final Message message = downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
1884		if (message != null) {
1885			startDownloadable(message);
1886		}
1887	}
1888
1889	private boolean showBlockSubmenu(View view) {
1890		final Jid jid = conversation.getJid();
1891		if (jid.getLocal() == null) {
1892			BlockContactDialog.show(activity, conversation);
1893		} else {
1894			PopupMenu popupMenu = new PopupMenu(getActivity(), view);
1895			popupMenu.inflate(R.menu.block);
1896			popupMenu.setOnMenuItemClickListener(menuItem -> {
1897				Blockable blockable;
1898				switch (menuItem.getItemId()) {
1899					case R.id.block_domain:
1900						blockable = conversation.getAccount().getRoster().getContact(Jid.ofDomain(jid.getDomain()));
1901						break;
1902					default:
1903						blockable = conversation;
1904				}
1905				BlockContactDialog.show(activity, blockable);
1906				return true;
1907			});
1908			popupMenu.show();
1909		}
1910		return true;
1911	}
1912
1913	private void updateSnackBar(final Conversation conversation) {
1914		final Account account = conversation.getAccount();
1915		final XmppConnection connection = account.getXmppConnection();
1916		final int mode = conversation.getMode();
1917		final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
1918		if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
1919			return;
1920		}
1921		if (account.getStatus() == Account.State.DISABLED) {
1922			showSnackbar(R.string.this_account_is_disabled, R.string.enable, this.mEnableAccountListener);
1923		} else if (conversation.isBlocked()) {
1924			showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
1925		} else if (contact != null && !contact.showInRoster() && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1926			showSnackbar(R.string.contact_added_you, R.string.add_back, this.mAddBackClickListener, this.mLongPressBlockListener);
1927		} else if (contact != null && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1928			showSnackbar(R.string.contact_asks_for_presence_subscription, R.string.allow, this.mAllowPresenceSubscription, this.mLongPressBlockListener);
1929		} else if (mode == Conversation.MODE_MULTI
1930				&& !conversation.getMucOptions().online()
1931				&& account.getStatus() == Account.State.ONLINE) {
1932			switch (conversation.getMucOptions().getError()) {
1933				case NICK_IN_USE:
1934					showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
1935					break;
1936				case NO_RESPONSE:
1937					showSnackbar(R.string.joining_conference, 0, null);
1938					break;
1939				case SERVER_NOT_FOUND:
1940					if (conversation.receivedMessagesCount() > 0) {
1941						showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
1942					} else {
1943						showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
1944					}
1945					break;
1946				case PASSWORD_REQUIRED:
1947					showSnackbar(R.string.conference_requires_password, R.string.enter_password, enterPassword);
1948					break;
1949				case BANNED:
1950					showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
1951					break;
1952				case MEMBERS_ONLY:
1953					showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
1954					break;
1955				case KICKED:
1956					showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
1957					break;
1958				case UNKNOWN:
1959					showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
1960					break;
1961				case INVALID_NICK:
1962					showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
1963				case SHUTDOWN:
1964					showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
1965					break;
1966				default:
1967					hideSnackbar();
1968					break;
1969			}
1970		} else if (account.hasPendingPgpIntent(conversation)) {
1971			showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
1972		} else if (connection != null
1973				&& connection.getFeatures().blocking()
1974				&& conversation.countMessages() != 0
1975				&& !conversation.isBlocked()
1976				&& conversation.isWithStranger()) {
1977			showSnackbar(R.string.received_message_from_stranger, R.string.block, mBlockClickListener);
1978		} else {
1979			hideSnackbar();
1980		}
1981	}
1982
1983	@Override
1984	public void refresh() {
1985		if (this.binding == null) {
1986			Log.d(Config.LOGTAG, "ConversationFragment.refresh() skipped updated because view binding was null");
1987			return;
1988		}
1989		this.refresh(true);
1990	}
1991
1992	private void refresh(boolean notifyConversationRead) {
1993		synchronized (this.messageList) {
1994			if (this.conversation != null) {
1995				conversation.populateWithMessages(this.messageList);
1996				updateSnackBar(conversation);
1997				updateStatusMessages();
1998				this.messageListAdapter.notifyDataSetChanged();
1999				updateChatMsgHint();
2000				if (notifyConversationRead && activity != null) {
2001					activity.onConversationRead(this.conversation);
2002				}
2003				updateSendButton();
2004				updateEditablity();
2005			}
2006		}
2007	}
2008
2009	protected void messageSent() {
2010		mSendingPgpMessage.set(false);
2011		this.binding.textinput.setText("");
2012		if (conversation.setCorrectingMessage(null)) {
2013			this.binding.textinput.append(conversation.getDraftMessage());
2014			conversation.setDraftMessage(null);
2015		}
2016		if (conversation.setNextMessage(this.binding.textinput.getText().toString())) {
2017			activity.xmppConnectionService.updateConversation(conversation);
2018		}
2019		updateChatMsgHint();
2020		SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity);
2021		final boolean prefScrollToBottom = p.getBoolean("scroll_to_bottom", activity.getResources().getBoolean(R.bool.scroll_to_bottom));
2022		if (prefScrollToBottom || scrolledToBottom()) {
2023			new Handler().post(() -> {
2024				int size = messageList.size();
2025				this.binding.messagesView.setSelection(size - 1);
2026			});
2027		}
2028	}
2029
2030	public void setFocusOnInputField() {
2031		this.binding.textinput.requestFocus();
2032	}
2033
2034	public void doneSendingPgpMessage() {
2035		mSendingPgpMessage.set(false);
2036	}
2037
2038	public long getMaxHttpUploadSize(Conversation conversation) {
2039		final XmppConnection connection = conversation.getAccount().getXmppConnection();
2040		return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
2041	}
2042
2043	private void updateEditablity() {
2044		boolean canWrite = this.conversation.getMode() == Conversation.MODE_SINGLE || this.conversation.getMucOptions().participating() || this.conversation.getNextCounterpart() != null;
2045		this.binding.textinput.setFocusable(canWrite);
2046		this.binding.textinput.setFocusableInTouchMode(canWrite);
2047		this.binding.textSendButton.setEnabled(canWrite);
2048		this.binding.textinput.setCursorVisible(canWrite);
2049	}
2050
2051	public void updateSendButton() {
2052		boolean useSendButtonToIndicateStatus = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean("send_button_status", getResources().getBoolean(R.bool.send_button_status));
2053		final Conversation c = this.conversation;
2054		final Presence.Status status;
2055		final String text = this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
2056		final SendButtonAction action = SendButtonTool.getAction(getActivity(), c, text);
2057		if (useSendButtonToIndicateStatus && c.getAccount().getStatus() == Account.State.ONLINE) {
2058			if (activity.xmppConnectionService != null && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
2059				status = Presence.Status.OFFLINE;
2060			} else if (c.getMode() == Conversation.MODE_SINGLE) {
2061				status = c.getContact().getShownStatus();
2062			} else {
2063				status = c.getMucOptions().online() ? Presence.Status.ONLINE : Presence.Status.OFFLINE;
2064			}
2065		} else {
2066			status = Presence.Status.OFFLINE;
2067		}
2068		this.binding.textSendButton.setTag(action);
2069		this.binding.textSendButton.setImageResource(SendButtonTool.getSendButtonImageResource(getActivity(), action, status));
2070	}
2071
2072	protected void updateDateSeparators() {
2073		synchronized (this.messageList) {
2074			for (int i = 0; i < this.messageList.size(); ++i) {
2075				final Message current = this.messageList.get(i);
2076				if (i == 0 || !UIHelper.sameDay(this.messageList.get(i - 1).getTimeSent(), current.getTimeSent())) {
2077					this.messageList.add(i, Message.createDateSeparator(current));
2078					i++;
2079				}
2080			}
2081		}
2082	}
2083
2084	protected void updateStatusMessages() {
2085		updateDateSeparators();
2086		synchronized (this.messageList) {
2087			if (showLoadMoreMessages(conversation)) {
2088				this.messageList.add(0, Message.createLoadMoreMessage(conversation));
2089			}
2090			if (conversation.getMode() == Conversation.MODE_SINGLE) {
2091				ChatState state = conversation.getIncomingChatState();
2092				if (state == ChatState.COMPOSING) {
2093					this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_is_typing, conversation.getName())));
2094				} else if (state == ChatState.PAUSED) {
2095					this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_has_stopped_typing, conversation.getName())));
2096				} else {
2097					for (int i = this.messageList.size() - 1; i >= 0; --i) {
2098						if (this.messageList.get(i).getStatus() == Message.STATUS_RECEIVED) {
2099							return;
2100						} else {
2101							if (this.messageList.get(i).getStatus() == Message.STATUS_SEND_DISPLAYED) {
2102								this.messageList.add(i + 1,
2103										Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, conversation.getName())));
2104								return;
2105							}
2106						}
2107					}
2108				}
2109			} else {
2110				final MucOptions mucOptions = conversation.getMucOptions();
2111				final List<MucOptions.User> allUsers = mucOptions.getUsers();
2112				final Set<ReadByMarker> addedMarkers = new HashSet<>();
2113				ChatState state = ChatState.COMPOSING;
2114				List<MucOptions.User> users = conversation.getMucOptions().getUsersWithChatState(state, 5);
2115				if (users.size() == 0) {
2116					state = ChatState.PAUSED;
2117					users = conversation.getMucOptions().getUsersWithChatState(state, 5);
2118				}
2119				if (mucOptions.isPrivateAndNonAnonymous()) {
2120					for (int i = this.messageList.size() - 1; i >= 0; --i) {
2121						final Set<ReadByMarker> markersForMessage = messageList.get(i).getReadByMarkers();
2122						final List<MucOptions.User> shownMarkers = new ArrayList<>();
2123						for (ReadByMarker marker : markersForMessage) {
2124							if (!ReadByMarker.contains(marker, addedMarkers)) {
2125								addedMarkers.add(marker); //may be put outside this condition. set should do dedup anyway
2126								MucOptions.User user = mucOptions.findUser(marker);
2127								if (user != null && !users.contains(user)) {
2128									shownMarkers.add(user);
2129								}
2130							}
2131						}
2132						final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
2133						final Message statusMessage;
2134						final int size = shownMarkers.size();
2135						if (size > 1) {
2136							final String body;
2137							if (size <= 4) {
2138								body = getString(R.string.contacts_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers));
2139							} else {
2140								body = getString(R.string.contacts_and_n_more_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers, 3), size - 3);
2141							}
2142							statusMessage = Message.createStatusMessage(conversation, body);
2143							statusMessage.setCounterparts(shownMarkers);
2144						} else if (size == 1) {
2145							statusMessage = Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, UIHelper.getDisplayName(shownMarkers.get(0))));
2146							statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
2147							statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
2148						} else {
2149							statusMessage = null;
2150						}
2151						if (statusMessage != null) {
2152							this.messageList.add(i + 1, statusMessage);
2153						}
2154						addedMarkers.add(markerForSender);
2155						if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
2156							break;
2157						}
2158					}
2159				}
2160				if (users.size() > 0) {
2161					Message statusMessage;
2162					if (users.size() == 1) {
2163						MucOptions.User user = users.get(0);
2164						int id = state == ChatState.COMPOSING ? R.string.contact_is_typing : R.string.contact_has_stopped_typing;
2165						statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.getDisplayName(user)));
2166						statusMessage.setTrueCounterpart(user.getRealJid());
2167						statusMessage.setCounterpart(user.getFullJid());
2168					} else {
2169						int id = state == ChatState.COMPOSING ? R.string.contacts_are_typing : R.string.contacts_have_stopped_typing;
2170						statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.concatNames(users)));
2171						statusMessage.setCounterparts(users);
2172					}
2173					this.messageList.add(statusMessage);
2174				}
2175
2176			}
2177		}
2178	}
2179
2180	private void stopScrolling() {
2181		long now = SystemClock.uptimeMillis();
2182		MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
2183		binding.messagesView.dispatchTouchEvent(cancel);
2184	}
2185
2186	private boolean showLoadMoreMessages(final Conversation c) {
2187		if (activity == null || activity.xmppConnectionService == null) {
2188			return false;
2189		}
2190		final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
2191		final MessageArchiveService service = activity.xmppConnectionService.getMessageArchiveService();
2192		return mam && (c.getLastClearHistory().getTimestamp() != 0 || (c.countMessages() == 0 && c.messagesLoaded.get() && c.hasMessagesLeftOnServer() && !service.queryInProgress(c)));
2193	}
2194
2195	private boolean hasMamSupport(final Conversation c) {
2196		if (c.getMode() == Conversation.MODE_SINGLE) {
2197			final XmppConnection connection = c.getAccount().getXmppConnection();
2198			return connection != null && connection.getFeatures().mam();
2199		} else {
2200			return c.getMucOptions().mamSupport();
2201		}
2202	}
2203
2204	protected void showSnackbar(final int message, final int action, final OnClickListener clickListener) {
2205		showSnackbar(message, action, clickListener, null);
2206	}
2207
2208	protected void showSnackbar(final int message, final int action, final OnClickListener clickListener, final View.OnLongClickListener longClickListener) {
2209		this.binding.snackbar.setVisibility(View.VISIBLE);
2210		this.binding.snackbar.setOnClickListener(null);
2211		this.binding.snackbarMessage.setText(message);
2212		this.binding.snackbarMessage.setOnClickListener(null);
2213		this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
2214		if (action != 0) {
2215			this.binding.snackbarAction.setText(action);
2216		}
2217		this.binding.snackbarAction.setOnClickListener(clickListener);
2218		this.binding.snackbarAction.setOnLongClickListener(longClickListener);
2219	}
2220
2221	protected void hideSnackbar() {
2222		this.binding.snackbar.setVisibility(View.GONE);
2223	}
2224
2225	protected void sendPlainTextMessage(Message message) {
2226		activity.xmppConnectionService.sendMessage(message);
2227		messageSent();
2228	}
2229
2230	protected void sendPgpMessage(final Message message) {
2231		final XmppConnectionService xmppService = activity.xmppConnectionService;
2232		final Contact contact = message.getConversation().getContact();
2233		if (!activity.hasPgp()) {
2234			activity.showInstallPgpDialog();
2235			return;
2236		}
2237		if (conversation.getAccount().getPgpSignature() == null) {
2238			activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
2239			return;
2240		}
2241		if (!mSendingPgpMessage.compareAndSet(false, true)) {
2242			Log.d(Config.LOGTAG, "sending pgp message already in progress");
2243		}
2244		if (conversation.getMode() == Conversation.MODE_SINGLE) {
2245			if (contact.getPgpKeyId() != 0) {
2246				xmppService.getPgpEngine().hasKey(contact,
2247						new UiCallback<Contact>() {
2248
2249							@Override
2250							public void userInputRequried(PendingIntent pi, Contact contact) {
2251								startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
2252							}
2253
2254							@Override
2255							public void success(Contact contact) {
2256								encryptTextMessage(message);
2257							}
2258
2259							@Override
2260							public void error(int error, Contact contact) {
2261								activity.runOnUiThread(() -> Toast.makeText(activity,
2262										R.string.unable_to_connect_to_keychain,
2263										Toast.LENGTH_SHORT
2264								).show());
2265								mSendingPgpMessage.set(false);
2266							}
2267						});
2268
2269			} else {
2270				showNoPGPKeyDialog(false, (dialog, which) -> {
2271					conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2272					xmppService.updateConversation(conversation);
2273					message.setEncryption(Message.ENCRYPTION_NONE);
2274					xmppService.sendMessage(message);
2275					messageSent();
2276				});
2277			}
2278		} else {
2279			if (conversation.getMucOptions().pgpKeysInUse()) {
2280				if (!conversation.getMucOptions().everybodyHasKeys()) {
2281					Toast warning = Toast
2282							.makeText(getActivity(),
2283									R.string.missing_public_keys,
2284									Toast.LENGTH_LONG);
2285					warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
2286					warning.show();
2287				}
2288				encryptTextMessage(message);
2289			} else {
2290				showNoPGPKeyDialog(true, (dialog, which) -> {
2291					conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2292					message.setEncryption(Message.ENCRYPTION_NONE);
2293					xmppService.updateConversation(conversation);
2294					xmppService.sendMessage(message);
2295					messageSent();
2296				});
2297			}
2298		}
2299	}
2300
2301	public void encryptTextMessage(Message message) {
2302		activity.xmppConnectionService.getPgpEngine().encrypt(message,
2303				new UiCallback<Message>() {
2304
2305					@Override
2306					public void userInputRequried(PendingIntent pi, Message message) {
2307						startPendingIntent(pi, REQUEST_SEND_MESSAGE);
2308					}
2309
2310					@Override
2311					public void success(Message message) {
2312						//TODO the following two call can be made before the callback
2313						getActivity().runOnUiThread(() -> messageSent());
2314					}
2315
2316					@Override
2317					public void error(final int error, Message message) {
2318						getActivity().runOnUiThread(() -> {
2319							doneSendingPgpMessage();
2320							Toast.makeText(getActivity(), R.string.unable_to_connect_to_keychain, Toast.LENGTH_SHORT).show();
2321						});
2322
2323					}
2324				});
2325	}
2326
2327	public void showNoPGPKeyDialog(boolean plural, DialogInterface.OnClickListener listener) {
2328		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
2329		builder.setIconAttribute(android.R.attr.alertDialogIcon);
2330		if (plural) {
2331			builder.setTitle(getString(R.string.no_pgp_keys));
2332			builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
2333		} else {
2334			builder.setTitle(getString(R.string.no_pgp_key));
2335			builder.setMessage(getText(R.string.contact_has_no_pgp_key));
2336		}
2337		builder.setNegativeButton(getString(R.string.cancel), null);
2338		builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
2339		builder.create().show();
2340	}
2341
2342	protected void sendAxolotlMessage(final Message message) {
2343		activity.xmppConnectionService.sendMessage(message);
2344		messageSent();
2345	}
2346
2347	public void appendText(String text) {
2348		if (text == null) {
2349			return;
2350		}
2351		String previous = this.binding.textinput.getText().toString();
2352		if (previous.length() != 0 && !previous.endsWith(" ")) {
2353			text = " " + text;
2354		}
2355		this.binding.textinput.append(text);
2356	}
2357
2358	@Override
2359	public boolean onEnterPressed() {
2360		SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
2361		final boolean enterIsSend = p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
2362		if (enterIsSend) {
2363			sendMessage();
2364			return true;
2365		} else {
2366			return false;
2367		}
2368	}
2369
2370	@Override
2371	public void onTypingStarted() {
2372		final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2373		if (service == null) {
2374			return;
2375		}
2376		Account.State status = conversation.getAccount().getStatus();
2377		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
2378			service.sendChatState(conversation);
2379		}
2380		updateSendButton();
2381	}
2382
2383	@Override
2384	public void onTypingStopped() {
2385		final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2386		if (service == null) {
2387			return;
2388		}
2389		Account.State status = conversation.getAccount().getStatus();
2390		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
2391			service.sendChatState(conversation);
2392		}
2393	}
2394
2395	@Override
2396	public void onTextDeleted() {
2397		final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2398		if (service == null) {
2399			return;
2400		}
2401		Account.State status = conversation.getAccount().getStatus();
2402		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
2403			service.sendChatState(conversation);
2404		}
2405		updateSendButton();
2406	}
2407
2408	@Override
2409	public void onTextChanged() {
2410		if (conversation != null && conversation.getCorrectingMessage() != null) {
2411			updateSendButton();
2412		}
2413	}
2414
2415	@Override
2416	public boolean onTabPressed(boolean repeated) {
2417		if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
2418			return false;
2419		}
2420		if (repeated) {
2421			completionIndex++;
2422		} else {
2423			lastCompletionLength = 0;
2424			completionIndex = 0;
2425			final String content = this.binding.textinput.getText().toString();
2426			lastCompletionCursor = this.binding.textinput.getSelectionEnd();
2427			int start = lastCompletionCursor > 0 ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1 : 0;
2428			firstWord = start == 0;
2429			incomplete = content.substring(start, lastCompletionCursor);
2430		}
2431		List<String> completions = new ArrayList<>();
2432		for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
2433			String name = user.getName();
2434			if (name != null && name.startsWith(incomplete)) {
2435				completions.add(name + (firstWord ? ": " : " "));
2436			}
2437		}
2438		Collections.sort(completions);
2439		if (completions.size() > completionIndex) {
2440			String completion = completions.get(completionIndex).substring(incomplete.length());
2441			this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
2442			this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
2443			lastCompletionLength = completion.length();
2444		} else {
2445			completionIndex = -1;
2446			this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
2447			lastCompletionLength = 0;
2448		}
2449		return true;
2450	}
2451
2452	private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
2453		try {
2454			getActivity().startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0);
2455		} catch (final SendIntentException ignored) {
2456		}
2457	}
2458
2459	@Override
2460	public void onBackendConnected() {
2461		Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
2462		String uuid = pendingConversationsUuid.pop();
2463		if (uuid != null) {
2464			Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
2465			if (conversation == null) {
2466				Log.d(Config.LOGTAG, "unable to restore activity");
2467				clearPending();
2468				return;
2469			}
2470			reInit(conversation);
2471			ScrollState scrollState = pendingScrollState.pop();
2472			if (scrollState != null) {
2473				setScrollPosition(scrollState);
2474			}
2475		}
2476		ActivityResult activityResult = postponedActivityResult.pop();
2477		if (activityResult != null) {
2478			handleActivityResult(activityResult);
2479		}
2480		clearPending();
2481	}
2482
2483	private void clearPending() {
2484		if (postponedActivityResult.pop() != null) {
2485			Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left");
2486		}
2487		pendingScrollState.pop();
2488		if (pendingTakePhotoUri.pop() != null) {
2489			Log.e(Config.LOGTAG, "cleared pending photo uri");
2490		}
2491	}
2492
2493	public Conversation getConversation() {
2494		return conversation;
2495	}
2496}