ConversationFragment.java

   1package eu.siacs.conversations.ui;
   2
   3import android.app.Activity;
   4import android.app.AlertDialog;
   5import android.app.Fragment;
   6import android.app.PendingIntent;
   7import android.content.ActivityNotFoundException;
   8import android.content.Context;
   9import android.content.DialogInterface;
  10import android.content.Intent;
  11import android.content.IntentSender.SendIntentException;
  12import android.os.Bundle;
  13import android.os.Handler;
  14import android.support.v13.view.inputmethod.InputConnectionCompat;
  15import android.support.v13.view.inputmethod.InputContentInfoCompat;
  16import android.text.Editable;
  17import android.text.InputType;
  18import android.util.Log;
  19import android.util.Pair;
  20import android.view.ContextMenu;
  21import android.view.ContextMenu.ContextMenuInfo;
  22import android.view.Gravity;
  23import android.view.KeyEvent;
  24import android.view.LayoutInflater;
  25import android.view.MenuItem;
  26import android.view.View;
  27import android.view.View.OnClickListener;
  28import android.view.ViewGroup;
  29import android.view.inputmethod.EditorInfo;
  30import android.view.inputmethod.InputMethodManager;
  31import android.widget.AbsListView;
  32import android.widget.AbsListView.OnScrollListener;
  33import android.widget.AdapterView;
  34import android.widget.AdapterView.AdapterContextMenuInfo;
  35import android.widget.ImageButton;
  36import android.widget.ListView;
  37import android.widget.PopupMenu;
  38import android.widget.RelativeLayout;
  39import android.widget.TextView;
  40import android.widget.TextView.OnEditorActionListener;
  41import android.widget.Toast;
  42
  43import net.java.otr4j.session.SessionStatus;
  44
  45import java.util.ArrayList;
  46import java.util.Arrays;
  47import java.util.Collections;
  48import java.util.List;
  49import java.util.UUID;
  50import java.util.concurrent.atomic.AtomicBoolean;
  51
  52import eu.siacs.conversations.Config;
  53import eu.siacs.conversations.R;
  54import eu.siacs.conversations.entities.Account;
  55import eu.siacs.conversations.entities.Blockable;
  56import eu.siacs.conversations.entities.Contact;
  57import eu.siacs.conversations.entities.Conversation;
  58import eu.siacs.conversations.entities.DownloadableFile;
  59import eu.siacs.conversations.entities.Message;
  60import eu.siacs.conversations.entities.MucOptions;
  61import eu.siacs.conversations.entities.Presence;
  62import eu.siacs.conversations.entities.Transferable;
  63import eu.siacs.conversations.entities.TransferablePlaceholder;
  64import eu.siacs.conversations.http.HttpDownloadConnection;
  65import eu.siacs.conversations.persistance.FileBackend;
  66import eu.siacs.conversations.services.MessageArchiveService;
  67import eu.siacs.conversations.services.XmppConnectionService;
  68import eu.siacs.conversations.ui.XmppActivity.OnPresenceSelected;
  69import eu.siacs.conversations.ui.XmppActivity.OnValueEdited;
  70import eu.siacs.conversations.ui.adapter.MessageAdapter;
  71import eu.siacs.conversations.ui.adapter.MessageAdapter.OnContactPictureClicked;
  72import eu.siacs.conversations.ui.adapter.MessageAdapter.OnContactPictureLongClicked;
  73import eu.siacs.conversations.ui.widget.ListSelectionManager;
  74import eu.siacs.conversations.utils.NickValidityChecker;
  75import eu.siacs.conversations.utils.UIHelper;
  76import eu.siacs.conversations.xmpp.XmppConnection;
  77import eu.siacs.conversations.xmpp.chatstate.ChatState;
  78import eu.siacs.conversations.xmpp.jid.Jid;
  79
  80public class ConversationFragment extends Fragment implements EditMessage.KeyboardListener {
  81
  82	protected Conversation conversation;
  83	private OnClickListener leaveMuc = new OnClickListener() {
  84
  85		@Override
  86		public void onClick(View v) {
  87			activity.endConversation(conversation);
  88		}
  89	};
  90	private OnClickListener joinMuc = new OnClickListener() {
  91
  92		@Override
  93		public void onClick(View v) {
  94			activity.xmppConnectionService.joinMuc(conversation);
  95		}
  96	};
  97	private OnClickListener enterPassword = new OnClickListener() {
  98
  99		@Override
 100		public void onClick(View v) {
 101			MucOptions muc = conversation.getMucOptions();
 102			String password = muc.getPassword();
 103			if (password == null) {
 104				password = "";
 105			}
 106			activity.quickPasswordEdit(password, new OnValueEdited() {
 107
 108				@Override
 109				public void onValueEdited(String value) {
 110					activity.xmppConnectionService.providePasswordForMuc(
 111							conversation, value);
 112				}
 113			});
 114		}
 115	};
 116	protected ListView messagesView;
 117	final protected List<Message> messageList = new ArrayList<>();
 118	protected MessageAdapter messageListAdapter;
 119	private EditMessage mEditMessage;
 120	private ImageButton mSendButton;
 121	private RelativeLayout snackbar;
 122	private TextView snackbarMessage;
 123	private TextView snackbarAction;
 124	private Toast messageLoaderToast;
 125
 126	private OnScrollListener mOnScrollListener = new OnScrollListener() {
 127
 128		@Override
 129		public void onScrollStateChanged(AbsListView view, int scrollState) {
 130			// TODO Auto-generated method stub
 131
 132		}
 133
 134		@Override
 135		public void onScroll(AbsListView view, int firstVisibleItem,
 136							 int visibleItemCount, int totalItemCount) {
 137			synchronized (ConversationFragment.this.messageList) {
 138				if (firstVisibleItem < 5 && conversation != null && conversation.messagesLoaded.compareAndSet(true,false) && messageList.size() > 0) {
 139					long timestamp;
 140					if (messageList.get(0).getType() == Message.TYPE_STATUS && messageList.size() >= 2) {
 141						timestamp = messageList.get(1).getTimeSent();
 142					} else {
 143						timestamp = messageList.get(0).getTimeSent();
 144					}
 145					activity.xmppConnectionService.loadMoreMessages(conversation, timestamp, new XmppConnectionService.OnMoreMessagesLoaded() {
 146						@Override
 147						public void onMoreMessagesLoaded(final int c, final Conversation conversation) {
 148							if (ConversationFragment.this.conversation != conversation) {
 149								conversation.messagesLoaded.set(true);
 150								return;
 151							}
 152							activity.runOnUiThread(new Runnable() {
 153								@Override
 154								public void run() {
 155									final int oldPosition = messagesView.getFirstVisiblePosition();
 156									Message message = null;
 157									int childPos;
 158									for(childPos = 0; childPos + oldPosition < messageList.size(); ++childPos) {
 159										message =  messageList.get(oldPosition + childPos);
 160										if (message.getType() != Message.TYPE_STATUS) {
 161											break;
 162										}
 163									}
 164									final String uuid = message != null ? message.getUuid() : null;
 165									View v = messagesView.getChildAt(childPos);
 166									final int pxOffset = (v == null) ? 0 : v.getTop();
 167									ConversationFragment.this.conversation.populateWithMessages(ConversationFragment.this.messageList);
 168									try {
 169										updateStatusMessages();
 170									} catch (IllegalStateException e) {
 171										Log.d(Config.LOGTAG,"caught illegal state exception while updating status messages");
 172									}
 173									messageListAdapter.notifyDataSetChanged();
 174									int pos = Math.max(getIndexOf(uuid,messageList),0);
 175									messagesView.setSelectionFromTop(pos, pxOffset);
 176									if (messageLoaderToast != null) {
 177										messageLoaderToast.cancel();
 178									}
 179									conversation.messagesLoaded.set(true);
 180								}
 181							});
 182						}
 183
 184						@Override
 185						public void informUser(final int resId) {
 186
 187							activity.runOnUiThread(new Runnable() {
 188								@Override
 189								public void run() {
 190									if (messageLoaderToast != null) {
 191										messageLoaderToast.cancel();
 192									}
 193									if (ConversationFragment.this.conversation != conversation) {
 194										return;
 195									}
 196									messageLoaderToast = Toast.makeText(activity, resId, Toast.LENGTH_LONG);
 197									messageLoaderToast.show();
 198								}
 199							});
 200
 201						}
 202					});
 203
 204				}
 205			}
 206		}
 207	};
 208
 209	private int getIndexOf(String uuid, List<Message> messages) {
 210		if (uuid == null) {
 211			return messages.size() - 1;
 212		}
 213		for(int i = 0; i < messages.size(); ++i) {
 214			if (uuid.equals(messages.get(i).getUuid())) {
 215				return i;
 216			} else {
 217				Message next = messages.get(i);
 218				while(next != null && next.wasMergedIntoPrevious()) {
 219					if (uuid.equals(next.getUuid())) {
 220						return i;
 221					}
 222					next = next.next();
 223				}
 224
 225			}
 226		}
 227		return -1;
 228	}
 229
 230	public Pair<Integer,Integer> getScrollPosition() {
 231		if (this.messagesView.getCount() == 0 ||
 232				this.messagesView.getLastVisiblePosition() == this.messagesView.getCount() - 1) {
 233			return null;
 234		} else {
 235			final int pos = messagesView.getFirstVisiblePosition();
 236			final View view = messagesView.getChildAt(0);
 237			if (view == null) {
 238				return null;
 239			} else {
 240				return new Pair<>(pos, view.getTop());
 241			}
 242		}
 243	}
 244
 245	public void setScrollPosition(Pair<Integer,Integer> scrollPosition) {
 246		if (scrollPosition != null) {
 247			this.messagesView.setSelectionFromTop(scrollPosition.first, scrollPosition.second);
 248		}
 249	}
 250
 251	protected OnClickListener clickToDecryptListener = new OnClickListener() {
 252
 253		@Override
 254		public void onClick(View v) {
 255			PendingIntent pendingIntent = conversation.getAccount().getPgpDecryptionService().getPendingIntent();
 256			if (pendingIntent != null) {
 257				try {
 258					activity.startIntentSenderForResult(pendingIntent.getIntentSender(),
 259                            ConversationActivity.REQUEST_DECRYPT_PGP,
 260                            null,
 261                            0,
 262                            0,
 263                            0);
 264				} catch (SendIntentException e) {
 265					Toast.makeText(activity,R.string.unable_to_connect_to_keychain, Toast.LENGTH_SHORT).show();
 266					conversation.getAccount().getPgpDecryptionService().continueDecryption(true);
 267				}
 268			}
 269			updateSnackBar(conversation);
 270		}
 271	};
 272	protected OnClickListener clickToVerify = new OnClickListener() {
 273
 274		@Override
 275		public void onClick(View v) {
 276			activity.verifyOtrSessionDialog(conversation, v);
 277		}
 278	};
 279	private OnEditorActionListener mEditorActionListener = new OnEditorActionListener() {
 280
 281		@Override
 282		public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
 283			if (actionId == EditorInfo.IME_ACTION_SEND) {
 284				InputMethodManager imm = (InputMethodManager) v.getContext()
 285						.getSystemService(Context.INPUT_METHOD_SERVICE);
 286				if (imm.isFullscreenMode()) {
 287					imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
 288				}
 289				sendMessage();
 290				return true;
 291			} else {
 292				return false;
 293			}
 294		}
 295	};
 296	private EditMessage.OnCommitContentListener mEditorContentListener = new EditMessage.OnCommitContentListener() {
 297		@Override
 298		public boolean onCommitContent(InputContentInfoCompat inputContentInfo, int flags, Bundle opts, String[] contentMimeTypes) {
 299			// try to get permission to read the image, if applicable
 300			if ((flags & InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION) != 0) {
 301				try {
 302					inputContentInfo.requestPermission();
 303				} catch (Exception e) {
 304					Log.e(Config.LOGTAG, "InputContentInfoCompat#requestPermission() failed.", e);
 305					Toast.makeText(
 306							activity,
 307							activity.getString(R.string.no_permission_to_access_x, inputContentInfo.getDescription()),
 308							Toast.LENGTH_LONG
 309					).show();
 310					return false;
 311				}
 312			}
 313			if (activity.hasStoragePermission(ConversationActivity.REQUEST_ADD_EDITOR_CONTENT)) {
 314				activity.attachImageToConversation(inputContentInfo.getContentUri());
 315			} else {
 316				activity.mPendingEditorContent = inputContentInfo.getContentUri();
 317			}
 318			return true;
 319		}
 320	};
 321	private OnClickListener mSendButtonListener = new OnClickListener() {
 322
 323		@Override
 324		public void onClick(View v) {
 325			Object tag = v.getTag();
 326			if (tag instanceof SendButtonAction) {
 327				SendButtonAction action = (SendButtonAction) tag;
 328				switch (action) {
 329					case TAKE_PHOTO:
 330						activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_TAKE_PHOTO);
 331						break;
 332					case RECORD_VIDEO:
 333						activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_RECORD_VIDEO);
 334						break;
 335					case SEND_LOCATION:
 336						activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_LOCATION);
 337						break;
 338					case RECORD_VOICE:
 339						activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_RECORD_VOICE);
 340						break;
 341					case CHOOSE_PICTURE:
 342						activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_CHOOSE_IMAGE);
 343						break;
 344					case CANCEL:
 345						if (conversation != null) {
 346							if(conversation.setCorrectingMessage(null)) {
 347								mEditMessage.setText("");
 348								mEditMessage.append(conversation.getDraftMessage());
 349								conversation.setDraftMessage(null);
 350							} else if (conversation.getMode() == Conversation.MODE_MULTI) {
 351								conversation.setNextCounterpart(null);
 352							}
 353							updateChatMsgHint();
 354							updateSendButton();
 355							updateEditablity();
 356						}
 357						break;
 358					default:
 359						sendMessage();
 360				}
 361			} else {
 362				sendMessage();
 363			}
 364		}
 365	};
 366	private OnClickListener clickToMuc = new OnClickListener() {
 367
 368		@Override
 369		public void onClick(View v) {
 370			Intent intent = new Intent(getActivity(), ConferenceDetailsActivity.class);
 371			intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
 372			intent.putExtra("uuid", conversation.getUuid());
 373			startActivity(intent);
 374		}
 375	};
 376	private ConversationActivity activity;
 377	private Message selectedMessage;
 378
 379	private void sendMessage() {
 380		final String body = mEditMessage.getText().toString();
 381		final Conversation conversation = this.conversation;
 382		if (body.length() == 0 || conversation == null) {
 383			return;
 384		}
 385		final Message message;
 386		if (conversation.getCorrectingMessage() == null) {
 387			message = new Message(conversation, body, conversation.getNextEncryption());
 388			if (conversation.getMode() == Conversation.MODE_MULTI) {
 389				if (conversation.getNextCounterpart() != null) {
 390					message.setCounterpart(conversation.getNextCounterpart());
 391					message.setType(Message.TYPE_PRIVATE);
 392				}
 393			}
 394		} else {
 395			message = conversation.getCorrectingMessage();
 396			message.setBody(body);
 397			message.setEdited(message.getUuid());
 398			message.setUuid(UUID.randomUUID().toString());
 399		}
 400		switch (message.getConversation().getNextEncryption()) {
 401			case Message.ENCRYPTION_OTR:
 402				sendOtrMessage(message);
 403				break;
 404			case Message.ENCRYPTION_PGP:
 405				sendPgpMessage(message);
 406				break;
 407			case Message.ENCRYPTION_AXOLOTL:
 408				if(!activity.trustKeysIfNeeded(ConversationActivity.REQUEST_TRUST_KEYS_TEXT)) {
 409					sendAxolotlMessage(message);
 410				}
 411				break;
 412			default:
 413				sendPlainTextMessage(message);
 414		}
 415	}
 416
 417	public void updateChatMsgHint() {
 418		final boolean multi = conversation.getMode() == Conversation.MODE_MULTI;
 419		if (conversation.getCorrectingMessage() != null) {
 420			this.mEditMessage.setHint(R.string.send_corrected_message);
 421		} else if (multi && conversation.getNextCounterpart() != null) {
 422			this.mEditMessage.setHint(getString(
 423					R.string.send_private_message_to,
 424					conversation.getNextCounterpart().getResourcepart()));
 425		} else if (multi && !conversation.getMucOptions().participating()) {
 426			this.mEditMessage.setHint(R.string.you_are_not_participating);
 427		} else {
 428			this.mEditMessage.setHint(UIHelper.getMessageHint(activity,conversation));
 429			getActivity().invalidateOptionsMenu();
 430		}
 431	}
 432
 433	public void setupIme() {
 434		if (activity != null) {
 435			if (activity.usingEnterKey() && activity.enterIsSend()) {
 436				mEditMessage.setInputType(mEditMessage.getInputType() & (~InputType.TYPE_TEXT_FLAG_MULTI_LINE));
 437				mEditMessage.setInputType(mEditMessage.getInputType() & (~InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE));
 438			} else if (activity.usingEnterKey()) {
 439				mEditMessage.setInputType(mEditMessage.getInputType() | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
 440				mEditMessage.setInputType(mEditMessage.getInputType() & (~InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE));
 441			} else {
 442				mEditMessage.setInputType(mEditMessage.getInputType() | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
 443				mEditMessage.setInputType(mEditMessage.getInputType() | InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE);
 444			}
 445		}
 446	}
 447
 448	@Override
 449	public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 450		final View view = inflater.inflate(R.layout.fragment_conversation, container, false);
 451		view.setOnClickListener(null);
 452
 453		mEditMessage = (EditMessage) view.findViewById(R.id.textinput);
 454		mEditMessage.setOnClickListener(new OnClickListener() {
 455
 456			@Override
 457			public void onClick(View v) {
 458				if (activity != null) {
 459					activity.hideConversationsOverview();
 460				}
 461			}
 462		});
 463
 464		mEditMessage.setOnEditorActionListener(mEditorActionListener);
 465		mEditMessage.setRichContentListener(new String[]{"image/*"}, mEditorContentListener);
 466
 467		mSendButton = (ImageButton) view.findViewById(R.id.textSendButton);
 468		mSendButton.setOnClickListener(this.mSendButtonListener);
 469
 470		snackbar = (RelativeLayout) view.findViewById(R.id.snackbar);
 471		snackbarMessage = (TextView) view.findViewById(R.id.snackbar_message);
 472		snackbarAction = (TextView) view.findViewById(R.id.snackbar_action);
 473
 474		messagesView = (ListView) view.findViewById(R.id.messages_view);
 475		messagesView.setOnScrollListener(mOnScrollListener);
 476		messagesView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
 477		messageListAdapter = new MessageAdapter((ConversationActivity) getActivity(), this.messageList);
 478		messageListAdapter.setOnContactPictureClicked(new OnContactPictureClicked() {
 479
 480			@Override
 481			public void onContactPictureClicked(Message message) {
 482				if (message.getStatus() <= Message.STATUS_RECEIVED) {
 483					if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
 484						Jid user = message.getCounterpart();
 485						if (user != null && !user.isBareJid()) {
 486							if (!message.getConversation().getMucOptions().isUserInRoom(user)) {
 487								Toast.makeText(activity,activity.getString(R.string.user_has_left_conference,user.getResourcepart()),Toast.LENGTH_SHORT).show();
 488							}
 489							highlightInConference(user.getResourcepart());
 490						}
 491					} else {
 492						if (!message.getContact().isSelf()) {
 493							String fingerprint;
 494							if (message.getEncryption() == Message.ENCRYPTION_PGP
 495									|| message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 496								fingerprint = "pgp";
 497							} else {
 498								fingerprint = message.getFingerprint();
 499							}
 500							activity.switchToContactDetails(message.getContact(), fingerprint);
 501						}
 502					}
 503				} else {
 504					Account account = message.getConversation().getAccount();
 505					Intent intent;
 506					if (activity.manuallyChangePresence()) {
 507						intent = new Intent(activity, SetPresenceActivity.class);
 508						intent.putExtra(SetPresenceActivity.EXTRA_ACCOUNT, account.getJid().toBareJid().toString());
 509					} else {
 510						intent = new Intent(activity, EditAccountActivity.class);
 511						intent.putExtra("jid", account.getJid().toBareJid().toString());
 512						String fingerprint;
 513						if (message.getEncryption() == Message.ENCRYPTION_PGP
 514								|| message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 515							fingerprint = "pgp";
 516						} else if (message.getEncryption() == Message.ENCRYPTION_OTR) {
 517							fingerprint = "otr";
 518						} else {
 519							fingerprint = message.getFingerprint();
 520						}
 521						intent.putExtra("fingerprint", fingerprint);
 522					}
 523					startActivity(intent);
 524				}
 525			}
 526		});
 527		messageListAdapter
 528				.setOnContactPictureLongClicked(new OnContactPictureLongClicked() {
 529
 530					@Override
 531					public void onContactPictureLongClicked(Message message) {
 532						if (message.getStatus() <= Message.STATUS_RECEIVED) {
 533							if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
 534								Jid user = message.getCounterpart();
 535								if (user != null && !user.isBareJid()) {
 536									if (message.getConversation().getMucOptions().isUserInRoom(user)) {
 537										privateMessageWith(user);
 538									} else {
 539										Toast.makeText(activity, activity.getString(R.string.user_has_left_conference, user.getResourcepart()), Toast.LENGTH_SHORT).show();
 540									}
 541								}
 542							}
 543						} else {
 544							activity.showQrCode();
 545						}
 546					}
 547				});
 548		messageListAdapter.setOnQuoteListener(new MessageAdapter.OnQuoteListener() {
 549
 550			@Override
 551			public void onQuote(String text) {
 552				if (mEditMessage.isEnabled()) {
 553					text = text.replaceAll("(\n *){2,}", "\n").replaceAll("(^|\n)", "$1> ").replaceAll("\n$", "");
 554					Editable editable = mEditMessage.getEditableText();
 555					int position = mEditMessage.getSelectionEnd();
 556					if (position == -1) position = editable.length();
 557					if (position > 0 && editable.charAt(position - 1) != '\n') {
 558						editable.insert(position++, "\n");
 559					}
 560					editable.insert(position, text);
 561					position += text.length();
 562					editable.insert(position++, "\n");
 563					if (position < editable.length() && editable.charAt(position) != '\n') {
 564						editable.insert(position, "\n");
 565					}
 566					mEditMessage.setSelection(position);
 567					mEditMessage.requestFocus();
 568					InputMethodManager inputMethodManager = (InputMethodManager) getActivity()
 569							.getSystemService(Context.INPUT_METHOD_SERVICE);
 570					if (inputMethodManager != null) {
 571						inputMethodManager.showSoftInput(mEditMessage, InputMethodManager.SHOW_IMPLICIT);
 572					}
 573				}
 574			}
 575		});
 576		messagesView.setAdapter(messageListAdapter);
 577
 578		registerForContextMenu(messagesView);
 579
 580		return view;
 581	}
 582
 583	@Override
 584	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
 585		synchronized (this.messageList) {
 586			super.onCreateContextMenu(menu, v, menuInfo);
 587			AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
 588			this.selectedMessage = this.messageList.get(acmi.position);
 589			populateContextMenu(menu);
 590		}
 591	}
 592
 593	private void populateContextMenu(ContextMenu menu) {
 594		final Message m = this.selectedMessage;
 595		final Transferable t = m.getTransferable();
 596		Message relevantForCorrection = m;
 597		while(relevantForCorrection.mergeable(relevantForCorrection.next())) {
 598			relevantForCorrection = relevantForCorrection.next();
 599		}
 600		if (m.getType() != Message.TYPE_STATUS) {
 601			final boolean treatAsFile = m.getType() != Message.TYPE_TEXT
 602					&& m.getType() != Message.TYPE_PRIVATE
 603					&& t == null;
 604			activity.getMenuInflater().inflate(R.menu.message_context, menu);
 605			menu.setHeaderTitle(R.string.message_options);
 606			MenuItem selectText = menu.findItem(R.id.select_text);
 607			MenuItem retryDecryption = menu.findItem(R.id.retry_decryption);
 608			MenuItem correctMessage = menu.findItem(R.id.correct_message);
 609			MenuItem shareWith = menu.findItem(R.id.share_with);
 610			MenuItem sendAgain = menu.findItem(R.id.send_again);
 611			MenuItem copyUrl = menu.findItem(R.id.copy_url);
 612			MenuItem downloadFile = menu.findItem(R.id.download_file);
 613			MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
 614			MenuItem deleteFile = menu.findItem(R.id.delete_file);
 615			MenuItem showErrorMessage = menu.findItem(R.id.show_error_message);
 616			if (!treatAsFile && !m.isGeoUri() && !m.treatAsDownloadable()) {
 617				selectText.setVisible(ListSelectionManager.isSupported());
 618			}
 619			if (m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED) {
 620				retryDecryption.setVisible(true);
 621			}
 622			if (relevantForCorrection.getType() == Message.TYPE_TEXT
 623					&& relevantForCorrection.isLastCorrectableMessage()
 624					&& (m.getConversation().getMucOptions().nonanonymous() || m.getConversation().getMode() == Conversation.MODE_SINGLE)) {
 625				correctMessage.setVisible(true);
 626			}
 627			if (treatAsFile || (m.getType() == Message.TYPE_TEXT && !m.treatAsDownloadable())) {
 628				shareWith.setVisible(true);
 629			}
 630			if (m.getStatus() == Message.STATUS_SEND_FAILED) {
 631				sendAgain.setVisible(true);
 632			}
 633			if (m.hasFileOnRemoteHost()
 634					|| m.isGeoUri()
 635					|| m.treatAsDownloadable()
 636					|| (t != null && t instanceof HttpDownloadConnection)) {
 637				copyUrl.setVisible(true);
 638			}
 639			if ((m.isFileOrImage() && t instanceof TransferablePlaceholder && m.hasFileOnRemoteHost())) {
 640				downloadFile.setVisible(true);
 641				downloadFile.setTitle(activity.getString(R.string.download_x_file,UIHelper.getFileDescriptionString(activity, m)));
 642			}
 643			boolean waitingOfferedSending = m.getStatus() == Message.STATUS_WAITING
 644					|| m.getStatus() == Message.STATUS_UNSEND
 645					|| m.getStatus() == Message.STATUS_OFFERED;
 646			if ((t != null && !(t instanceof TransferablePlaceholder)) || waitingOfferedSending && m.needsUploading()) {
 647				cancelTransmission.setVisible(true);
 648			}
 649			if (treatAsFile) {
 650				String path = m.getRelativeFilePath();
 651				if (path == null || !path.startsWith("/")) {
 652					deleteFile.setVisible(true);
 653					deleteFile.setTitle(activity.getString(R.string.delete_x_file, UIHelper.getFileDescriptionString(activity, m)));
 654				}
 655			}
 656			if (m.getStatus() == Message.STATUS_SEND_FAILED && m.getErrorMessage() != null) {
 657				showErrorMessage.setVisible(true);
 658			}
 659		}
 660	}
 661
 662	@Override
 663	public boolean onContextItemSelected(MenuItem item) {
 664		switch (item.getItemId()) {
 665			case R.id.share_with:
 666				shareWith(selectedMessage);
 667				return true;
 668			case R.id.select_text:
 669				selectText(selectedMessage);
 670				return true;
 671			case R.id.correct_message:
 672				correctMessage(selectedMessage);
 673				return true;
 674			case R.id.send_again:
 675				resendMessage(selectedMessage);
 676				return true;
 677			case R.id.copy_url:
 678				copyUrl(selectedMessage);
 679				return true;
 680			case R.id.download_file:
 681				downloadFile(selectedMessage);
 682				return true;
 683			case R.id.cancel_transmission:
 684				cancelTransmission(selectedMessage);
 685				return true;
 686			case R.id.retry_decryption:
 687				retryDecryption(selectedMessage);
 688				return true;
 689			case R.id.delete_file:
 690				deleteFile(selectedMessage);
 691				return true;
 692			case R.id.show_error_message:
 693				showErrorMessage(selectedMessage);
 694				return true;
 695			default:
 696				return super.onContextItemSelected(item);
 697		}
 698	}
 699
 700	private void showErrorMessage(final Message message) {
 701		AlertDialog.Builder builder = new AlertDialog.Builder(activity);
 702		builder.setTitle(R.string.error_message);
 703		builder.setMessage(message.getErrorMessage());
 704		builder.setPositiveButton(R.string.confirm,null);
 705		builder.create().show();
 706	}
 707
 708	private void shareWith(Message message) {
 709		Intent shareIntent = new Intent();
 710		shareIntent.setAction(Intent.ACTION_SEND);
 711		if (message.isGeoUri()) {
 712			shareIntent.putExtra(Intent.EXTRA_TEXT, message.getBody());
 713			shareIntent.setType("text/plain");
 714		} else if (!message.isFileOrImage()) {
 715			shareIntent.putExtra(Intent.EXTRA_TEXT, message.getMergedBody().toString());
 716			shareIntent.setType("text/plain");
 717		} else {
 718			final DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
 719			try {
 720				shareIntent.putExtra(Intent.EXTRA_STREAM, FileBackend.getUriForFile(activity, file));
 721			} catch (SecurityException e) {
 722				Toast.makeText(activity, activity.getString(R.string.no_permission_to_access_x, file.getAbsolutePath()), Toast.LENGTH_SHORT).show();
 723				return;
 724			}
 725			shareIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
 726			String mime = message.getMimeType();
 727			if (mime == null) {
 728				mime = "*/*";
 729			}
 730			shareIntent.setType(mime);
 731		}
 732		try {
 733			activity.startActivity(Intent.createChooser(shareIntent, getText(R.string.share_with)));
 734		} catch (ActivityNotFoundException e) {
 735			//This should happen only on faulty androids because normally chooser is always available
 736			Toast.makeText(activity,R.string.no_application_found_to_open_file,Toast.LENGTH_SHORT).show();
 737		}
 738	}
 739
 740	private void selectText(Message message) {
 741		final int index;
 742		synchronized (this.messageList) {
 743			index = this.messageList.indexOf(message);
 744		}
 745		if (index >= 0) {
 746			final int first = this.messagesView.getFirstVisiblePosition();
 747			final int last = first + this.messagesView.getChildCount();
 748			if (index >= first && index < last)	{
 749				final View view = this.messagesView.getChildAt(index - first);
 750				final TextView messageBody = this.messageListAdapter.getMessageBody(view);
 751				if (messageBody != null) {
 752					ListSelectionManager.startSelection(messageBody);
 753				}
 754			}
 755		}
 756	}
 757
 758	private void deleteFile(Message message) {
 759		if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
 760			message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
 761			activity.updateConversationList();
 762			updateMessages();
 763		}
 764	}
 765
 766	private void resendMessage(final Message message) {
 767		if (message.isFileOrImage()) {
 768			DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
 769			if (file.exists()) {
 770				final Conversation conversation = message.getConversation();
 771				final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
 772				if (!message.hasFileOnRemoteHost()
 773						&& xmppConnection != null
 774						&& !xmppConnection.getFeatures().httpUpload(message.getFileParams().size)) {
 775					activity.selectPresence(conversation, new OnPresenceSelected() {
 776						@Override
 777						public void onPresenceSelected() {
 778							message.setCounterpart(conversation.getNextCounterpart());
 779							activity.xmppConnectionService.resendFailedMessages(message);
 780						}
 781					});
 782					return;
 783				}
 784			} else {
 785				Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
 786				message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
 787				activity.updateConversationList();
 788				updateMessages();
 789				return;
 790			}
 791		}
 792		activity.xmppConnectionService.resendFailedMessages(message);
 793	}
 794
 795	private void copyUrl(Message message) {
 796		final String url;
 797		final int resId;
 798		if (message.isGeoUri()) {
 799			resId = R.string.location;
 800			url = message.getBody();
 801		} else if (message.hasFileOnRemoteHost()) {
 802			resId = R.string.file_url;
 803			url = message.getFileParams().url.toString();
 804		} else {
 805			url = message.getBody().trim();
 806			resId = R.string.file_url;
 807		}
 808		if (activity.copyTextToClipboard(url, resId)) {
 809			Toast.makeText(activity, R.string.url_copied_to_clipboard,
 810					Toast.LENGTH_SHORT).show();
 811		}
 812	}
 813
 814	private void downloadFile(Message message) {
 815		activity.xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message,true);
 816	}
 817
 818	private void cancelTransmission(Message message) {
 819		Transferable transferable = message.getTransferable();
 820		if (transferable != null) {
 821			transferable.cancel();
 822		} else if (message.getStatus() != Message.STATUS_RECEIVED) {
 823			activity.xmppConnectionService.markMessage(message,Message.STATUS_SEND_FAILED);
 824		}
 825	}
 826
 827	private void retryDecryption(Message message) {
 828		message.setEncryption(Message.ENCRYPTION_PGP);
 829		activity.updateConversationList();
 830		updateMessages();
 831		conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
 832	}
 833
 834	protected void privateMessageWith(final Jid counterpart) {
 835		if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
 836			activity.xmppConnectionService.sendChatState(conversation);
 837		}
 838		this.mEditMessage.setText("");
 839		this.conversation.setNextCounterpart(counterpart);
 840		updateChatMsgHint();
 841		updateSendButton();
 842		updateEditablity();
 843	}
 844
 845	private void correctMessage(Message message) {
 846		while(message.mergeable(message.next())) {
 847			message = message.next();
 848		}
 849		this.conversation.setCorrectingMessage(message);
 850		final Editable editable = mEditMessage.getText();
 851		this.conversation.setDraftMessage(editable.toString());
 852		this.mEditMessage.setText("");
 853		this.mEditMessage.append(message.getBody());
 854
 855	}
 856
 857	protected void highlightInConference(String nick) {
 858		final Editable editable = mEditMessage.getText();
 859		String oldString = editable.toString().trim();
 860		final int pos = mEditMessage.getSelectionStart();
 861		if (oldString.isEmpty() || pos == 0) {
 862			editable.insert(0, nick + ": ");
 863		} else {
 864			final char before = editable.charAt(pos - 1);
 865			final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
 866			if (before == '\n') {
 867				editable.insert(pos, nick + ": ");
 868			} else {
 869				if (pos > 2 && editable.subSequence(pos-2,pos).toString().equals(": ")) {
 870					if (NickValidityChecker.check(conversation,Arrays.asList(editable.subSequence(0,pos-2).toString().split(", ")))) {
 871						editable.insert(pos - 2, ", " + nick);
 872						return;
 873					}
 874				}
 875				editable.insert(pos, (Character.isWhitespace(before) ? "" : " ") + nick + (Character.isWhitespace(after) ? "" : " "));
 876				if (Character.isWhitespace(after)) {
 877					mEditMessage.setSelection(mEditMessage.getSelectionStart() + 1);
 878				}
 879			}
 880		}
 881	}
 882
 883	@Override
 884	public void onStop() {
 885		super.onStop();
 886		if (activity == null || !activity.isChangingConfigurations()) {
 887			messageListAdapter.stopAudioPlayer();
 888		}
 889		if (this.conversation != null) {
 890			final String msg = mEditMessage.getText().toString();
 891			this.conversation.setNextMessage(msg);
 892			updateChatState(this.conversation, msg);
 893		}
 894	}
 895
 896	private void updateChatState(final Conversation conversation, final String msg) {
 897		ChatState state = msg.length() == 0 ? Config.DEFAULT_CHATSTATE : ChatState.PAUSED;
 898		Account.State status = conversation.getAccount().getStatus();
 899		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
 900			activity.xmppConnectionService.sendChatState(conversation);
 901		}
 902	}
 903
 904	public boolean reInit(Conversation conversation) {
 905		if (conversation == null) {
 906			return false;
 907		}
 908		this.activity = (ConversationActivity) getActivity();
 909		setupIme();
 910		if (this.conversation != null) {
 911			final String msg = mEditMessage.getText().toString();
 912			this.conversation.setNextMessage(msg);
 913			if (this.conversation != conversation) {
 914				updateChatState(this.conversation, msg);
 915				messageListAdapter.stopAudioPlayer();
 916			}
 917			this.conversation.trim();
 918
 919		}
 920
 921		if (activity != null) {
 922			this.mSendButton.setContentDescription(activity.getString(R.string.send_message_to_x,conversation.getName()));
 923		}
 924
 925		this.conversation = conversation;
 926		this.mEditMessage.setKeyboardListener(null);
 927		this.mEditMessage.setText("");
 928		this.mEditMessage.append(this.conversation.getNextMessage());
 929		this.mEditMessage.setKeyboardListener(this);
 930		messageListAdapter.updatePreferences();
 931		this.messagesView.setAdapter(messageListAdapter);
 932		updateMessages();
 933		this.conversation.messagesLoaded.set(true);
 934		synchronized (this.messageList) {
 935			final Message first = conversation.getFirstUnreadMessage();
 936			final int bottom = Math.max(0, this.messageList.size() - 1);
 937			final int pos;
 938			if (first == null) {
 939				pos = bottom;
 940			} else {
 941				int i = getIndexOf(first.getUuid(), this.messageList);
 942				pos = i < 0 ? bottom : i;
 943			}
 944			messagesView.setSelection(pos);
 945			return pos == bottom;
 946		}
 947	}
 948
 949	private OnClickListener mEnableAccountListener = new OnClickListener() {
 950		@Override
 951		public void onClick(View v) {
 952			final Account account = conversation == null ? null : conversation.getAccount();
 953			if (account != null) {
 954				account.setOption(Account.OPTION_DISABLED, false);
 955				activity.xmppConnectionService.updateAccount(account);
 956			}
 957		}
 958	};
 959
 960	private OnClickListener mUnblockClickListener = new OnClickListener() {
 961		@Override
 962		public void onClick(final View v) {
 963			v.post(new Runnable() {
 964				@Override
 965				public void run() {
 966					v.setVisibility(View.INVISIBLE);
 967				}
 968			});
 969			if (conversation.isDomainBlocked()) {
 970				BlockContactDialog.show(activity, conversation);
 971			} else {
 972				activity.unblockConversation(conversation);
 973			}
 974		}
 975	};
 976
 977	private void showBlockSubmenu(View view) {
 978		final Jid jid = conversation.getJid();
 979			if (jid.isDomainJid()) {
 980				BlockContactDialog.show(activity, conversation);
 981			} else {
 982				PopupMenu popupMenu = new PopupMenu(activity, view);
 983				popupMenu.inflate(R.menu.block);
 984				popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
 985					@Override
 986					public boolean onMenuItemClick(MenuItem menuItem) {
 987						Blockable blockable;
 988						switch (menuItem.getItemId()) {
 989							case R.id.block_domain:
 990								blockable = conversation.getAccount().getRoster().getContact(jid.toDomainJid());
 991								break;
 992							default:
 993								blockable = conversation;
 994						}
 995						BlockContactDialog.show(activity, blockable);
 996						return true;
 997					}
 998				});
 999				popupMenu.show();
1000			}
1001	}
1002
1003	private OnClickListener mBlockClickListener = new OnClickListener() {
1004		@Override
1005		public void onClick(final View view) {
1006			showBlockSubmenu(view);
1007		}
1008	};
1009
1010	private OnClickListener mAddBackClickListener = new OnClickListener() {
1011
1012		@Override
1013		public void onClick(View v) {
1014			final Contact contact = conversation == null ? null : conversation.getContact();
1015			if (contact != null) {
1016				activity.xmppConnectionService.createContact(contact);
1017				activity.switchToContactDetails(contact);
1018			}
1019		}
1020	};
1021
1022	private View.OnLongClickListener mLongPressBlockListener = new View.OnLongClickListener() {
1023		@Override
1024		public boolean onLongClick(View v) {
1025			showBlockSubmenu(v);
1026			return true;
1027		}
1028	};
1029
1030	private OnClickListener mAllowPresenceSubscription = new OnClickListener() {
1031		@Override
1032		public void onClick(View v) {
1033			final Contact contact = conversation == null ? null : conversation.getContact();
1034			if (contact != null) {
1035				activity.xmppConnectionService.sendPresencePacket(contact.getAccount(),
1036						activity.xmppConnectionService.getPresenceGenerator()
1037								.sendPresenceUpdatesTo(contact));
1038				hideSnackbar();
1039			}
1040		}
1041	};
1042
1043	private OnClickListener mAnswerSmpClickListener = new OnClickListener() {
1044		@Override
1045		public void onClick(View view) {
1046			Intent intent = new Intent(activity, VerifyOTRActivity.class);
1047			intent.setAction(VerifyOTRActivity.ACTION_VERIFY_CONTACT);
1048			intent.putExtra("contact", conversation.getContact().getJid().toBareJid().toString());
1049			intent.putExtra(VerifyOTRActivity.EXTRA_ACCOUNT, conversation.getAccount().getJid().toBareJid().toString());
1050			intent.putExtra("mode", VerifyOTRActivity.MODE_ANSWER_QUESTION);
1051			startActivity(intent);
1052		}
1053	};
1054
1055	private void updateSnackBar(final Conversation conversation) {
1056		final Account account = conversation.getAccount();
1057		final XmppConnection connection = account.getXmppConnection();
1058		final int mode = conversation.getMode();
1059		final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
1060		if (account.getStatus() == Account.State.DISABLED) {
1061			showSnackbar(R.string.this_account_is_disabled, R.string.enable, this.mEnableAccountListener);
1062		} else if (conversation.isBlocked()) {
1063			showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
1064		} else if (contact != null && !contact.showInRoster() && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1065			showSnackbar(R.string.contact_added_you, R.string.add_back, this.mAddBackClickListener, this.mLongPressBlockListener);
1066		} else if (contact != null && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1067			showSnackbar(R.string.contact_asks_for_presence_subscription, R.string.allow, this.mAllowPresenceSubscription, this.mLongPressBlockListener);
1068		} else if (mode == Conversation.MODE_MULTI
1069				&& !conversation.getMucOptions().online()
1070				&& account.getStatus() == Account.State.ONLINE) {
1071			switch (conversation.getMucOptions().getError()) {
1072				case NICK_IN_USE:
1073					showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
1074					break;
1075				case NO_RESPONSE:
1076					showSnackbar(R.string.joining_conference, 0, null);
1077					break;
1078				case SERVER_NOT_FOUND:
1079					if (conversation.receivedMessagesCount() > 0) {
1080						showSnackbar(R.string.remote_server_not_found,R.string.try_again, joinMuc);
1081					} else {
1082						showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
1083					}
1084					break;
1085				case PASSWORD_REQUIRED:
1086					showSnackbar(R.string.conference_requires_password, R.string.enter_password, enterPassword);
1087					break;
1088				case BANNED:
1089					showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
1090					break;
1091				case MEMBERS_ONLY:
1092					showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
1093					break;
1094				case KICKED:
1095					showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
1096					break;
1097				case UNKNOWN:
1098					showSnackbar(R.string.conference_unknown_error, R.string.join, joinMuc);
1099					break;
1100				case SHUTDOWN:
1101					showSnackbar(R.string.conference_shutdown, R.string.join, joinMuc);
1102					break;
1103				default:
1104					hideSnackbar();
1105					break;
1106			}
1107		} else if (account.hasPendingPgpIntent(conversation)) {
1108			showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
1109		} else if (mode == Conversation.MODE_SINGLE
1110				&& conversation.smpRequested()) {
1111			showSnackbar(R.string.smp_requested, R.string.verify, this.mAnswerSmpClickListener);
1112		} else if (mode == Conversation.MODE_SINGLE
1113				&& conversation.hasValidOtrSession()
1114				&& (conversation.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED)
1115				&& (!conversation.isOtrFingerprintVerified())) {
1116			showSnackbar(R.string.unknown_otr_fingerprint, R.string.verify, clickToVerify);
1117		} else if (connection != null
1118				&& connection.getFeatures().blocking()
1119				&& conversation.countMessages() != 0
1120				&& !conversation.isBlocked()
1121				&& conversation.isWithStranger()) {
1122			showSnackbar(R.string.received_message_from_stranger,R.string.block, mBlockClickListener);
1123		} else {
1124			hideSnackbar();
1125		}
1126	}
1127
1128	public void updateMessages() {
1129		synchronized (this.messageList) {
1130			if (getView() == null) {
1131				return;
1132			}
1133			final ConversationActivity activity = (ConversationActivity) getActivity();
1134			if (this.conversation != null) {
1135				conversation.populateWithMessages(ConversationFragment.this.messageList);
1136				updateSnackBar(conversation);
1137				updateStatusMessages();
1138				this.messageListAdapter.notifyDataSetChanged();
1139				updateChatMsgHint();
1140				if (!activity.isConversationsOverviewVisable() || !activity.isConversationsOverviewHideable()) {
1141					activity.sendReadMarkerIfNecessary(conversation);
1142				}
1143				updateSendButton();
1144				updateEditablity();
1145			}
1146		}
1147	}
1148
1149	protected void messageSent() {
1150		mSendingPgpMessage.set(false);
1151		mEditMessage.setText("");
1152		if (conversation.setCorrectingMessage(null)) {
1153			mEditMessage.append(conversation.getDraftMessage());
1154			conversation.setDraftMessage(null);
1155		}
1156		conversation.setNextMessage(mEditMessage.getText().toString());
1157		updateChatMsgHint();
1158		new Handler().post(new Runnable() {
1159			@Override
1160			public void run() {
1161				int size = messageList.size();
1162				messagesView.setSelection(size - 1);
1163			}
1164		});
1165	}
1166
1167	public void setFocusOnInputField() {
1168		mEditMessage.requestFocus();
1169	}
1170
1171	public void doneSendingPgpMessage() {
1172		mSendingPgpMessage.set(false);
1173	}
1174
1175	enum SendButtonAction {TEXT, TAKE_PHOTO, SEND_LOCATION, RECORD_VOICE, CANCEL, CHOOSE_PICTURE, RECORD_VIDEO;
1176
1177		public static SendButtonAction valueOfOrDefault(String setting, SendButtonAction text) {
1178			try {
1179				return valueOf(setting);
1180			} catch (IllegalArgumentException e) {
1181				return TEXT;
1182			}
1183		}
1184	}
1185
1186	private int getSendButtonImageResource(SendButtonAction action, Presence.Status status) {
1187		switch (action) {
1188			case TEXT:
1189				switch (status) {
1190					case CHAT:
1191					case ONLINE:
1192						return R.drawable.ic_send_text_online;
1193					case AWAY:
1194						return R.drawable.ic_send_text_away;
1195					case XA:
1196					case DND:
1197						return R.drawable.ic_send_text_dnd;
1198					default:
1199						return activity.getThemeResource(R.attr.ic_send_text_offline, R.drawable.ic_send_text_offline);
1200				}
1201			case RECORD_VIDEO:
1202				switch (status) {
1203					case CHAT:
1204					case ONLINE:
1205						return R.drawable.ic_send_videocam_online;
1206					case AWAY:
1207						return R.drawable.ic_send_videocam_away;
1208					case XA:
1209					case DND:
1210						return R.drawable.ic_send_videocam_dnd;
1211					default:
1212						return activity.getThemeResource(R.attr.ic_send_videocam_offline, R.drawable.ic_send_videocam_offline);
1213				}
1214			case TAKE_PHOTO:
1215				switch (status) {
1216					case CHAT:
1217					case ONLINE:
1218						return R.drawable.ic_send_photo_online;
1219					case AWAY:
1220						return R.drawable.ic_send_photo_away;
1221					case XA:
1222					case DND:
1223						return R.drawable.ic_send_photo_dnd;
1224					default:
1225						return activity.getThemeResource(R.attr.ic_send_photo_offline, R.drawable.ic_send_photo_offline);
1226				}
1227			case RECORD_VOICE:
1228				switch (status) {
1229					case CHAT:
1230					case ONLINE:
1231						return R.drawable.ic_send_voice_online;
1232					case AWAY:
1233						return R.drawable.ic_send_voice_away;
1234					case XA:
1235					case DND:
1236						return R.drawable.ic_send_voice_dnd;
1237					default:
1238						return activity.getThemeResource(R.attr.ic_send_voice_offline, R.drawable.ic_send_voice_offline);
1239				}
1240			case SEND_LOCATION:
1241				switch (status) {
1242					case CHAT:
1243					case ONLINE:
1244						return R.drawable.ic_send_location_online;
1245					case AWAY:
1246						return R.drawable.ic_send_location_away;
1247					case XA:
1248					case DND:
1249						return R.drawable.ic_send_location_dnd;
1250					default:
1251						return activity.getThemeResource(R.attr.ic_send_location_offline, R.drawable.ic_send_location_offline);
1252				}
1253			case CANCEL:
1254				switch (status) {
1255					case CHAT:
1256					case ONLINE:
1257						return R.drawable.ic_send_cancel_online;
1258					case AWAY:
1259						return R.drawable.ic_send_cancel_away;
1260					case XA:
1261					case DND:
1262						return R.drawable.ic_send_cancel_dnd;
1263					default:
1264						return activity.getThemeResource(R.attr.ic_send_cancel_offline, R.drawable.ic_send_cancel_offline);
1265				}
1266			case CHOOSE_PICTURE:
1267				switch (status) {
1268					case CHAT:
1269					case ONLINE:
1270						return R.drawable.ic_send_picture_online;
1271					case AWAY:
1272						return R.drawable.ic_send_picture_away;
1273					case XA:
1274					case DND:
1275						return R.drawable.ic_send_picture_dnd;
1276					default:
1277						return activity.getThemeResource(R.attr.ic_send_picture_offline, R.drawable.ic_send_picture_offline);
1278				}
1279		}
1280		return activity.getThemeResource(R.attr.ic_send_text_offline, R.drawable.ic_send_text_offline);
1281	}
1282
1283	private void updateEditablity() {
1284		boolean canWrite = this.conversation.getMode() == Conversation.MODE_SINGLE || this.conversation.getMucOptions().participating() || this.conversation.getNextCounterpart() != null;
1285		this.mEditMessage.setFocusable(canWrite);
1286		this.mEditMessage.setFocusableInTouchMode(canWrite);
1287		this.mSendButton.setEnabled(canWrite);
1288		this.mEditMessage.setCursorVisible(canWrite);
1289	}
1290
1291	public void updateSendButton() {
1292		final Conversation c = this.conversation;
1293		final SendButtonAction action;
1294		final Presence.Status status;
1295		final String text = this.mEditMessage == null ? "" : this.mEditMessage.getText().toString();
1296		final boolean empty = text.length() == 0;
1297		final boolean conference = c.getMode() == Conversation.MODE_MULTI;
1298		if (c.getCorrectingMessage() != null && (empty || text.equals(c.getCorrectingMessage().getBody()))) {
1299			action = SendButtonAction.CANCEL;
1300		} else if (conference && !c.getAccount().httpUploadAvailable()) {
1301			if (empty && c.getNextCounterpart() != null) {
1302				action = SendButtonAction.CANCEL;
1303			} else {
1304				action = SendButtonAction.TEXT;
1305			}
1306		} else {
1307			if (empty) {
1308				if (conference && c.getNextCounterpart() != null) {
1309					action = SendButtonAction.CANCEL;
1310				} else {
1311					String setting = activity.getPreferences().getString("quick_action", activity.getResources().getString(R.string.quick_action));
1312					if (!setting.equals("none") && UIHelper.receivedLocationQuestion(conversation.getLatestMessage())) {
1313						action = SendButtonAction.SEND_LOCATION;
1314					} else {
1315						if (setting.equals("recent")) {
1316							setting = activity.getPreferences().getString(ConversationActivity.RECENTLY_USED_QUICK_ACTION, SendButtonAction.TEXT.toString());
1317							action = SendButtonAction.valueOfOrDefault(setting,SendButtonAction.TEXT);
1318						} else {
1319							action = SendButtonAction.valueOfOrDefault(setting,SendButtonAction.TEXT);
1320						}
1321					}
1322				}
1323			} else {
1324				action = SendButtonAction.TEXT;
1325			}
1326		}
1327		if (activity.useSendButtonToIndicateStatus() && c.getAccount().getStatus() == Account.State.ONLINE) {
1328			if (activity.xmppConnectionService != null && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
1329				status = Presence.Status.OFFLINE;
1330			} else if (c.getMode() == Conversation.MODE_SINGLE) {
1331				status = c.getContact().getShownStatus();
1332			} else {
1333				status = c.getMucOptions().online() ? Presence.Status.ONLINE : Presence.Status.OFFLINE;
1334			}
1335		} else {
1336			status = Presence.Status.OFFLINE;
1337		}
1338		this.mSendButton.setTag(action);
1339		this.mSendButton.setImageResource(getSendButtonImageResource(action, status));
1340	}
1341
1342	protected void updateDateSeparators() {
1343		synchronized (this.messageList) {
1344			for(int i = 0; i < this.messageList.size(); ++i) {
1345				final Message current = this.messageList.get(i);
1346				if (i == 0 || !UIHelper.sameDay(this.messageList.get(i-1).getTimeSent(),current.getTimeSent())) {
1347					this.messageList.add(i,Message.createDateSeparator(current));
1348					i++;
1349				}
1350			}
1351		}
1352	}
1353
1354	protected void updateStatusMessages() {
1355		updateDateSeparators();
1356		synchronized (this.messageList) {
1357			if (showLoadMoreMessages(conversation)) {
1358				this.messageList.add(0, Message.createLoadMoreMessage(conversation));
1359			}
1360			if (conversation.getMode() == Conversation.MODE_SINGLE) {
1361				ChatState state = conversation.getIncomingChatState();
1362				if (state == ChatState.COMPOSING) {
1363					this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_is_typing, conversation.getName())));
1364				} else if (state == ChatState.PAUSED) {
1365					this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_has_stopped_typing, conversation.getName())));
1366				} else {
1367					for (int i = this.messageList.size() - 1; i >= 0; --i) {
1368						if (this.messageList.get(i).getStatus() == Message.STATUS_RECEIVED) {
1369							return;
1370						} else {
1371							if (this.messageList.get(i).getStatus() == Message.STATUS_SEND_DISPLAYED) {
1372								this.messageList.add(i + 1,
1373										Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, conversation.getName())));
1374								return;
1375							}
1376						}
1377					}
1378				}
1379			} else {
1380				ChatState state = ChatState.COMPOSING;
1381				List<MucOptions.User> users = conversation.getMucOptions().getUsersWithChatState(state,5);
1382				if (users.size() == 0) {
1383					state = ChatState.PAUSED;
1384					users = conversation.getMucOptions().getUsersWithChatState(state, 5);
1385
1386				}
1387				if (users.size() > 0) {
1388					Message statusMessage;
1389					if (users.size() == 1) {
1390						MucOptions.User user = users.get(0);
1391						int id = state == ChatState.COMPOSING ? R.string.contact_is_typing : R.string.contact_has_stopped_typing;
1392						statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.getDisplayName(user)));
1393						statusMessage.setTrueCounterpart(user.getRealJid());
1394						statusMessage.setCounterpart(user.getFullJid());
1395					} else {
1396						StringBuilder builder = new StringBuilder();
1397						for(MucOptions.User user : users) {
1398							if (builder.length() != 0) {
1399								builder.append(", ");
1400							}
1401							builder.append(UIHelper.getDisplayName(user));
1402						}
1403						int id = state == ChatState.COMPOSING ? R.string.contacts_are_typing : R.string.contacts_have_stopped_typing;
1404						statusMessage = Message.createStatusMessage(conversation, getString(id, builder.toString()));
1405					}
1406					this.messageList.add(statusMessage);
1407				}
1408
1409			}
1410		}
1411	}
1412
1413	private boolean showLoadMoreMessages(final Conversation c) {
1414		final boolean mam = hasMamSupport(c);
1415		final MessageArchiveService service = activity.xmppConnectionService.getMessageArchiveService();
1416		return mam && (c.getLastClearHistory().getTimestamp() != 0  || (c.countMessages() == 0 && c.messagesLoaded.get() && c.hasMessagesLeftOnServer()  && !service.queryInProgress(c)));
1417	}
1418
1419	private boolean hasMamSupport(final Conversation c) {
1420		if (c.getMode() == Conversation.MODE_SINGLE) {
1421			final XmppConnection connection = c.getAccount().getXmppConnection();
1422			return connection != null && connection.getFeatures().mam();
1423		} else {
1424			return c.getMucOptions().mamSupport();
1425		}
1426	}
1427
1428	protected void showSnackbar(final int message, final int action, final OnClickListener clickListener) {
1429		showSnackbar(message,action,clickListener,null);
1430	}
1431
1432	protected void showSnackbar(final int message, final int action, final OnClickListener clickListener, final View.OnLongClickListener longClickListener) {
1433		snackbar.setVisibility(View.VISIBLE);
1434		snackbar.setOnClickListener(null);
1435		snackbarMessage.setText(message);
1436		snackbarMessage.setOnClickListener(null);
1437		snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
1438		if (action != 0) {
1439			snackbarAction.setText(action);
1440		}
1441		snackbarAction.setOnClickListener(clickListener);
1442		snackbarAction.setOnLongClickListener(longClickListener);
1443	}
1444
1445	protected void hideSnackbar() {
1446		snackbar.setVisibility(View.GONE);
1447	}
1448
1449	protected void sendPlainTextMessage(Message message) {
1450		ConversationActivity activity = (ConversationActivity) getActivity();
1451		activity.xmppConnectionService.sendMessage(message);
1452		messageSent();
1453	}
1454
1455	private AtomicBoolean mSendingPgpMessage = new AtomicBoolean(false);
1456
1457	protected void sendPgpMessage(final Message message) {
1458		final ConversationActivity activity = (ConversationActivity) getActivity();
1459		final XmppConnectionService xmppService = activity.xmppConnectionService;
1460		final Contact contact = message.getConversation().getContact();
1461		if (!activity.hasPgp()) {
1462			activity.showInstallPgpDialog();
1463			return;
1464		}
1465		if (conversation.getAccount().getPgpSignature() == null) {
1466			activity.announcePgp(conversation.getAccount(), conversation, activity.onOpenPGPKeyPublished);
1467			return;
1468		}
1469		if (!mSendingPgpMessage.compareAndSet(false,true)) {
1470			Log.d(Config.LOGTAG,"sending pgp message already in progress");
1471		}
1472		if (conversation.getMode() == Conversation.MODE_SINGLE) {
1473			if (contact.getPgpKeyId() != 0) {
1474				xmppService.getPgpEngine().hasKey(contact,
1475						new UiCallback<Contact>() {
1476
1477							@Override
1478							public void userInputRequried(PendingIntent pi,
1479														  Contact contact) {
1480								activity.runIntent(
1481										pi,
1482										ConversationActivity.REQUEST_ENCRYPT_MESSAGE);
1483							}
1484
1485							@Override
1486							public void success(Contact contact) {
1487								activity.encryptTextMessage(message);
1488							}
1489
1490							@Override
1491							public void error(int error, Contact contact) {
1492								activity.runOnUiThread(new Runnable() {
1493									@Override
1494									public void run() {
1495										Toast.makeText(activity,
1496												R.string.unable_to_connect_to_keychain,
1497												Toast.LENGTH_SHORT
1498										).show();
1499									}
1500								});
1501								mSendingPgpMessage.set(false);
1502							}
1503						});
1504
1505			} else {
1506				showNoPGPKeyDialog(false,
1507						new DialogInterface.OnClickListener() {
1508
1509							@Override
1510							public void onClick(DialogInterface dialog,
1511												int which) {
1512								conversation
1513										.setNextEncryption(Message.ENCRYPTION_NONE);
1514								xmppService.updateConversation(conversation);
1515								message.setEncryption(Message.ENCRYPTION_NONE);
1516								xmppService.sendMessage(message);
1517								messageSent();
1518							}
1519						});
1520			}
1521		} else {
1522			if (conversation.getMucOptions().pgpKeysInUse()) {
1523				if (!conversation.getMucOptions().everybodyHasKeys()) {
1524					Toast warning = Toast
1525							.makeText(getActivity(),
1526									R.string.missing_public_keys,
1527									Toast.LENGTH_LONG);
1528					warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
1529					warning.show();
1530				}
1531				activity.encryptTextMessage(message);
1532			} else {
1533				showNoPGPKeyDialog(true,
1534						new DialogInterface.OnClickListener() {
1535
1536							@Override
1537							public void onClick(DialogInterface dialog,
1538												int which) {
1539								conversation
1540										.setNextEncryption(Message.ENCRYPTION_NONE);
1541								message.setEncryption(Message.ENCRYPTION_NONE);
1542								xmppService.updateConversation(conversation);
1543								xmppService.sendMessage(message);
1544								messageSent();
1545							}
1546						});
1547			}
1548		}
1549	}
1550
1551	public void showNoPGPKeyDialog(boolean plural,
1552								   DialogInterface.OnClickListener listener) {
1553		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1554		builder.setIconAttribute(android.R.attr.alertDialogIcon);
1555		if (plural) {
1556			builder.setTitle(getString(R.string.no_pgp_keys));
1557			builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
1558		} else {
1559			builder.setTitle(getString(R.string.no_pgp_key));
1560			builder.setMessage(getText(R.string.contact_has_no_pgp_key));
1561		}
1562		builder.setNegativeButton(getString(R.string.cancel), null);
1563		builder.setPositiveButton(getString(R.string.send_unencrypted),
1564				listener);
1565		builder.create().show();
1566	}
1567
1568	protected void sendAxolotlMessage(final Message message) {
1569		final ConversationActivity activity = (ConversationActivity) getActivity();
1570		final XmppConnectionService xmppService = activity.xmppConnectionService;
1571		xmppService.sendMessage(message);
1572		messageSent();
1573	}
1574
1575	protected void sendOtrMessage(final Message message) {
1576		final ConversationActivity activity = (ConversationActivity) getActivity();
1577		final XmppConnectionService xmppService = activity.xmppConnectionService;
1578		activity.selectPresence(message.getConversation(),
1579				new OnPresenceSelected() {
1580
1581					@Override
1582					public void onPresenceSelected() {
1583						message.setCounterpart(conversation.getNextCounterpart());
1584						xmppService.sendMessage(message);
1585						messageSent();
1586					}
1587				});
1588	}
1589
1590	public void appendText(String text) {
1591		if (text == null) {
1592			return;
1593		}
1594		String previous = this.mEditMessage.getText().toString();
1595		if (previous.length() != 0 && !previous.endsWith(" ")) {
1596			text = " " + text;
1597		}
1598		this.mEditMessage.append(text);
1599	}
1600
1601	@Override
1602	public boolean onEnterPressed() {
1603		if (activity.enterIsSend()) {
1604			sendMessage();
1605			return true;
1606		} else {
1607			return false;
1608		}
1609	}
1610
1611	@Override
1612	public void onTypingStarted() {
1613		Account.State status = conversation.getAccount().getStatus();
1614		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
1615			activity.xmppConnectionService.sendChatState(conversation);
1616		}
1617		activity.hideConversationsOverview();
1618		updateSendButton();
1619	}
1620
1621	@Override
1622	public void onTypingStopped() {
1623		Account.State status = conversation.getAccount().getStatus();
1624		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
1625			activity.xmppConnectionService.sendChatState(conversation);
1626		}
1627	}
1628
1629	@Override
1630	public void onTextDeleted() {
1631		Account.State status = conversation.getAccount().getStatus();
1632		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1633			activity.xmppConnectionService.sendChatState(conversation);
1634		}
1635		updateSendButton();
1636	}
1637
1638	@Override
1639	public void onTextChanged() {
1640		if (conversation != null && conversation.getCorrectingMessage() != null) {
1641			updateSendButton();
1642		}
1643	}
1644
1645	private int completionIndex = 0;
1646	private int lastCompletionLength = 0;
1647	private String incomplete;
1648	private int lastCompletionCursor;
1649	private boolean firstWord = false;
1650
1651	@Override
1652	public boolean onTabPressed(boolean repeated) {
1653		if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
1654			return false;
1655		}
1656		if (repeated) {
1657			completionIndex++;
1658		} else {
1659			lastCompletionLength = 0;
1660			completionIndex = 0;
1661			final String content = mEditMessage.getText().toString();
1662			lastCompletionCursor = mEditMessage.getSelectionEnd();
1663			int start = lastCompletionCursor > 0 ? content.lastIndexOf(" ",lastCompletionCursor-1) + 1 : 0;
1664			firstWord = start == 0;
1665			incomplete = content.substring(start,lastCompletionCursor);
1666		}
1667		List<String> completions = new ArrayList<>();
1668		for(MucOptions.User user : conversation.getMucOptions().getUsers()) {
1669			String name = user.getName();
1670			if (name != null && name.startsWith(incomplete)) {
1671				completions.add(name+(firstWord ? ": " : " "));
1672			}
1673		}
1674		Collections.sort(completions);
1675		if (completions.size() > completionIndex) {
1676			String completion = completions.get(completionIndex).substring(incomplete.length());
1677			mEditMessage.getEditableText().delete(lastCompletionCursor,lastCompletionCursor + lastCompletionLength);
1678			mEditMessage.getEditableText().insert(lastCompletionCursor, completion);
1679			lastCompletionLength = completion.length();
1680		} else {
1681			completionIndex = -1;
1682			mEditMessage.getEditableText().delete(lastCompletionCursor,lastCompletionCursor + lastCompletionLength);
1683			lastCompletionLength = 0;
1684		}
1685		return true;
1686	}
1687
1688	@Override
1689	public void onActivityResult(int requestCode, int resultCode,
1690	                                final Intent data) {
1691		if (resultCode == Activity.RESULT_OK) {
1692			if (requestCode == ConversationActivity.REQUEST_DECRYPT_PGP) {
1693				activity.getSelectedConversation().getAccount().getPgpDecryptionService().continueDecryption(true);
1694			} else if (requestCode == ConversationActivity.REQUEST_TRUST_KEYS_TEXT) {
1695				final String body = mEditMessage.getText().toString();
1696				Message message = new Message(conversation, body, conversation.getNextEncryption());
1697				sendAxolotlMessage(message);
1698			} else if (requestCode == ConversationActivity.REQUEST_TRUST_KEYS_MENU) {
1699				int choice = data.getIntExtra("choice", ConversationActivity.ATTACHMENT_CHOICE_INVALID);
1700				activity.selectPresenceToAttachFile(choice, conversation.getNextEncryption());
1701			}
1702		} else if (resultCode == Activity.RESULT_CANCELED) {
1703			if (requestCode == ConversationActivity.REQUEST_DECRYPT_PGP) {
1704				// discard the message to prevent decryption being blocked
1705				conversation.getAccount().getPgpDecryptionService().giveUpCurrentDecryption();
1706			}
1707		}
1708	}
1709
1710}