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