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