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(Message message) {
 767		if (message.getType() == Message.TYPE_FILE || message.getType() == Message.TYPE_IMAGE) {
 768			DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
 769			if (!file.exists()) {
 770				Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
 771				message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
 772				activity.updateConversationList();
 773				updateMessages();
 774				return;
 775			}
 776		}
 777		activity.xmppConnectionService.resendFailedMessages(message);
 778	}
 779
 780	private void copyUrl(Message message) {
 781		final String url;
 782		final int resId;
 783		if (message.isGeoUri()) {
 784			resId = R.string.location;
 785			url = message.getBody();
 786		} else if (message.hasFileOnRemoteHost()) {
 787			resId = R.string.file_url;
 788			url = message.getFileParams().url.toString();
 789		} else {
 790			url = message.getBody().trim();
 791			resId = R.string.file_url;
 792		}
 793		if (activity.copyTextToClipboard(url, resId)) {
 794			Toast.makeText(activity, R.string.url_copied_to_clipboard,
 795					Toast.LENGTH_SHORT).show();
 796		}
 797	}
 798
 799	private void downloadFile(Message message) {
 800		activity.xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message,true);
 801	}
 802
 803	private void cancelTransmission(Message message) {
 804		Transferable transferable = message.getTransferable();
 805		if (transferable != null) {
 806			transferable.cancel();
 807		} else if (message.getStatus() != Message.STATUS_RECEIVED) {
 808			activity.xmppConnectionService.markMessage(message,Message.STATUS_SEND_FAILED);
 809		}
 810	}
 811
 812	private void retryDecryption(Message message) {
 813		message.setEncryption(Message.ENCRYPTION_PGP);
 814		activity.updateConversationList();
 815		updateMessages();
 816		conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
 817	}
 818
 819	protected void privateMessageWith(final Jid counterpart) {
 820		if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
 821			activity.xmppConnectionService.sendChatState(conversation);
 822		}
 823		this.mEditMessage.setText("");
 824		this.conversation.setNextCounterpart(counterpart);
 825		updateChatMsgHint();
 826		updateSendButton();
 827		updateEditablity();
 828	}
 829
 830	private void correctMessage(Message message) {
 831		while(message.mergeable(message.next())) {
 832			message = message.next();
 833		}
 834		this.conversation.setCorrectingMessage(message);
 835		final Editable editable = mEditMessage.getText();
 836		this.conversation.setDraftMessage(editable.toString());
 837		this.mEditMessage.setText("");
 838		this.mEditMessage.append(message.getBody());
 839
 840	}
 841
 842	protected void highlightInConference(String nick) {
 843		final Editable editable = mEditMessage.getText();
 844		String oldString = editable.toString().trim();
 845		final int pos = mEditMessage.getSelectionStart();
 846		if (oldString.isEmpty() || pos == 0) {
 847			editable.insert(0, nick + ": ");
 848		} else {
 849			final char before = editable.charAt(pos - 1);
 850			final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
 851			if (before == '\n') {
 852				editable.insert(pos, nick + ": ");
 853			} else {
 854				if (pos > 2 && editable.subSequence(pos-2,pos).toString().equals(": ")) {
 855					if (NickValidityChecker.check(conversation,Arrays.asList(editable.subSequence(0,pos-2).toString().split(", ")))) {
 856						editable.insert(pos - 2, ", " + nick);
 857						return;
 858					}
 859				}
 860				editable.insert(pos, (Character.isWhitespace(before) ? "" : " ") + nick + (Character.isWhitespace(after) ? "" : " "));
 861				if (Character.isWhitespace(after)) {
 862					mEditMessage.setSelection(mEditMessage.getSelectionStart() + 1);
 863				}
 864			}
 865		}
 866	}
 867
 868	@Override
 869	public void onStop() {
 870		super.onStop();
 871		if (this.conversation != null) {
 872			final String msg = mEditMessage.getText().toString();
 873			this.conversation.setNextMessage(msg);
 874			updateChatState(this.conversation, msg);
 875		}
 876	}
 877
 878	private void updateChatState(final Conversation conversation, final String msg) {
 879		ChatState state = msg.length() == 0 ? Config.DEFAULT_CHATSTATE : ChatState.PAUSED;
 880		Account.State status = conversation.getAccount().getStatus();
 881		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
 882			activity.xmppConnectionService.sendChatState(conversation);
 883		}
 884	}
 885
 886	public boolean reInit(Conversation conversation) {
 887		if (conversation == null) {
 888			return false;
 889		}
 890		this.activity = (ConversationActivity) getActivity();
 891		setupIme();
 892		if (this.conversation != null) {
 893			final String msg = mEditMessage.getText().toString();
 894			this.conversation.setNextMessage(msg);
 895			if (this.conversation != conversation) {
 896				updateChatState(this.conversation, msg);
 897			}
 898			this.conversation.trim();
 899
 900		}
 901
 902		if (activity != null) {
 903			this.mSendButton.setContentDescription(activity.getString(R.string.send_message_to_x,conversation.getName()));
 904		}
 905
 906		this.conversation = conversation;
 907		this.mEditMessage.setKeyboardListener(null);
 908		this.mEditMessage.setText("");
 909		this.mEditMessage.append(this.conversation.getNextMessage());
 910		this.mEditMessage.setKeyboardListener(this);
 911		messageListAdapter.updatePreferences();
 912		this.messagesView.setAdapter(messageListAdapter);
 913		updateMessages();
 914		this.conversation.messagesLoaded.set(true);
 915		synchronized (this.messageList) {
 916			final Message first = conversation.getFirstUnreadMessage();
 917			final int bottom = Math.max(0, this.messageList.size() - 1);
 918			final int pos;
 919			if (first == null) {
 920				pos = bottom;
 921			} else {
 922				int i = getIndexOf(first.getUuid(), this.messageList);
 923				pos = i < 0 ? bottom : i;
 924			}
 925			messagesView.setSelection(pos);
 926			return pos == bottom;
 927		}
 928	}
 929
 930	private OnClickListener mEnableAccountListener = new OnClickListener() {
 931		@Override
 932		public void onClick(View v) {
 933			final Account account = conversation == null ? null : conversation.getAccount();
 934			if (account != null) {
 935				account.setOption(Account.OPTION_DISABLED, false);
 936				activity.xmppConnectionService.updateAccount(account);
 937			}
 938		}
 939	};
 940
 941	private OnClickListener mUnblockClickListener = new OnClickListener() {
 942		@Override
 943		public void onClick(final View v) {
 944			v.post(new Runnable() {
 945				@Override
 946				public void run() {
 947					v.setVisibility(View.INVISIBLE);
 948				}
 949			});
 950			if (conversation.isDomainBlocked()) {
 951				BlockContactDialog.show(activity, conversation);
 952			} else {
 953				activity.unblockConversation(conversation);
 954			}
 955		}
 956	};
 957
 958	private void showBlockSubmenu(View view) {
 959		final Jid jid = conversation.getJid();
 960			if (jid.isDomainJid()) {
 961				BlockContactDialog.show(activity, conversation);
 962			} else {
 963				PopupMenu popupMenu = new PopupMenu(activity, view);
 964				popupMenu.inflate(R.menu.block);
 965				popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
 966					@Override
 967					public boolean onMenuItemClick(MenuItem menuItem) {
 968						Blockable blockable;
 969						switch (menuItem.getItemId()) {
 970							case R.id.block_domain:
 971								blockable = conversation.getAccount().getRoster().getContact(jid.toDomainJid());
 972								break;
 973							default:
 974								blockable = conversation;
 975						}
 976						BlockContactDialog.show(activity, blockable);
 977						return true;
 978					}
 979				});
 980				popupMenu.show();
 981			}
 982	}
 983
 984	private OnClickListener mBlockClickListener = new OnClickListener() {
 985		@Override
 986		public void onClick(final View view) {
 987			showBlockSubmenu(view);
 988		}
 989	};
 990
 991	private OnClickListener mAddBackClickListener = new OnClickListener() {
 992
 993		@Override
 994		public void onClick(View v) {
 995			final Contact contact = conversation == null ? null : conversation.getContact();
 996			if (contact != null) {
 997				activity.xmppConnectionService.createContact(contact);
 998				activity.switchToContactDetails(contact);
 999			}
1000		}
1001	};
1002
1003	private View.OnLongClickListener mLongPressBlockListener = new View.OnLongClickListener() {
1004		@Override
1005		public boolean onLongClick(View v) {
1006			showBlockSubmenu(v);
1007			return true;
1008		}
1009	};
1010
1011	private OnClickListener mAllowPresenceSubscription = new OnClickListener() {
1012		@Override
1013		public void onClick(View v) {
1014			final Contact contact = conversation == null ? null : conversation.getContact();
1015			if (contact != null) {
1016				activity.xmppConnectionService.sendPresencePacket(contact.getAccount(),
1017						activity.xmppConnectionService.getPresenceGenerator()
1018								.sendPresenceUpdatesTo(contact));
1019				hideSnackbar();
1020			}
1021		}
1022	};
1023
1024	private OnClickListener mAnswerSmpClickListener = new OnClickListener() {
1025		@Override
1026		public void onClick(View view) {
1027			Intent intent = new Intent(activity, VerifyOTRActivity.class);
1028			intent.setAction(VerifyOTRActivity.ACTION_VERIFY_CONTACT);
1029			intent.putExtra("contact", conversation.getContact().getJid().toBareJid().toString());
1030			intent.putExtra(VerifyOTRActivity.EXTRA_ACCOUNT, conversation.getAccount().getJid().toBareJid().toString());
1031			intent.putExtra("mode", VerifyOTRActivity.MODE_ANSWER_QUESTION);
1032			startActivity(intent);
1033		}
1034	};
1035
1036	private void updateSnackBar(final Conversation conversation) {
1037		final Account account = conversation.getAccount();
1038		final XmppConnection connection = account.getXmppConnection();
1039		final int mode = conversation.getMode();
1040		final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
1041		if (account.getStatus() == Account.State.DISABLED) {
1042			showSnackbar(R.string.this_account_is_disabled, R.string.enable, this.mEnableAccountListener);
1043		} else if (conversation.isBlocked()) {
1044			showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
1045		} else if (contact != null && !contact.showInRoster() && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1046			showSnackbar(R.string.contact_added_you, R.string.add_back, this.mAddBackClickListener, this.mLongPressBlockListener);
1047		} else if (contact != null && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1048			showSnackbar(R.string.contact_asks_for_presence_subscription, R.string.allow, this.mAllowPresenceSubscription, this.mLongPressBlockListener);
1049		} else if (mode == Conversation.MODE_MULTI
1050				&& !conversation.getMucOptions().online()
1051				&& account.getStatus() == Account.State.ONLINE) {
1052			switch (conversation.getMucOptions().getError()) {
1053				case NICK_IN_USE:
1054					showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
1055					break;
1056				case NO_RESPONSE:
1057					showSnackbar(R.string.joining_conference, 0, null);
1058					break;
1059				case SERVER_NOT_FOUND:
1060					if (conversation.receivedMessagesCount() > 0) {
1061						showSnackbar(R.string.remote_server_not_found,R.string.try_again, joinMuc);
1062					} else {
1063						showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
1064					}
1065					break;
1066				case PASSWORD_REQUIRED:
1067					showSnackbar(R.string.conference_requires_password, R.string.enter_password, enterPassword);
1068					break;
1069				case BANNED:
1070					showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
1071					break;
1072				case MEMBERS_ONLY:
1073					showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
1074					break;
1075				case KICKED:
1076					showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
1077					break;
1078				case UNKNOWN:
1079					showSnackbar(R.string.conference_unknown_error, R.string.join, joinMuc);
1080					break;
1081				case SHUTDOWN:
1082					showSnackbar(R.string.conference_shutdown, R.string.join, joinMuc);
1083					break;
1084				default:
1085					hideSnackbar();
1086					break;
1087			}
1088		} else if (account.hasPendingPgpIntent(conversation)) {
1089			showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
1090		} else if (mode == Conversation.MODE_SINGLE
1091				&& conversation.smpRequested()) {
1092			showSnackbar(R.string.smp_requested, R.string.verify, this.mAnswerSmpClickListener);
1093		} else if (mode == Conversation.MODE_SINGLE
1094				&& conversation.hasValidOtrSession()
1095				&& (conversation.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED)
1096				&& (!conversation.isOtrFingerprintVerified())) {
1097			showSnackbar(R.string.unknown_otr_fingerprint, R.string.verify, clickToVerify);
1098		} else if (connection != null
1099				&& connection.getFeatures().blocking()
1100				&& conversation.countMessages() != 0
1101				&& !conversation.isBlocked()
1102				&& conversation.isWithStranger()) {
1103			showSnackbar(R.string.received_message_from_stranger,R.string.block, mBlockClickListener);
1104		} else {
1105			hideSnackbar();
1106		}
1107	}
1108
1109	public void updateMessages() {
1110		synchronized (this.messageList) {
1111			if (getView() == null) {
1112				return;
1113			}
1114			final ConversationActivity activity = (ConversationActivity) getActivity();
1115			if (this.conversation != null) {
1116				conversation.populateWithMessages(ConversationFragment.this.messageList);
1117				updateSnackBar(conversation);
1118				updateStatusMessages();
1119				this.messageListAdapter.notifyDataSetChanged();
1120				updateChatMsgHint();
1121				if (!activity.isConversationsOverviewVisable() || !activity.isConversationsOverviewHideable()) {
1122					activity.sendReadMarkerIfNecessary(conversation);
1123				}
1124				updateSendButton();
1125				updateEditablity();
1126			}
1127		}
1128	}
1129
1130	protected void messageSent() {
1131		mSendingPgpMessage.set(false);
1132		mEditMessage.setText("");
1133		if (conversation.setCorrectingMessage(null)) {
1134			mEditMessage.append(conversation.getDraftMessage());
1135			conversation.setDraftMessage(null);
1136		}
1137		conversation.setNextMessage(mEditMessage.getText().toString());
1138		updateChatMsgHint();
1139		new Handler().post(new Runnable() {
1140			@Override
1141			public void run() {
1142				int size = messageList.size();
1143				messagesView.setSelection(size - 1);
1144			}
1145		});
1146	}
1147
1148	public void setFocusOnInputField() {
1149		mEditMessage.requestFocus();
1150	}
1151
1152	public void doneSendingPgpMessage() {
1153		mSendingPgpMessage.set(false);
1154	}
1155
1156	enum SendButtonAction {TEXT, TAKE_PHOTO, SEND_LOCATION, RECORD_VOICE, CANCEL, CHOOSE_PICTURE, RECORD_VIDEO;
1157
1158		public static SendButtonAction valueOfOrDefault(String setting, SendButtonAction text) {
1159			try {
1160				return valueOf(setting);
1161			} catch (IllegalArgumentException e) {
1162				return TEXT;
1163			}
1164		}
1165	}
1166
1167	private int getSendButtonImageResource(SendButtonAction action, Presence.Status status) {
1168		switch (action) {
1169			case TEXT:
1170				switch (status) {
1171					case CHAT:
1172					case ONLINE:
1173						return R.drawable.ic_send_text_online;
1174					case AWAY:
1175						return R.drawable.ic_send_text_away;
1176					case XA:
1177					case DND:
1178						return R.drawable.ic_send_text_dnd;
1179					default:
1180						return activity.getThemeResource(R.attr.ic_send_text_offline, R.drawable.ic_send_text_offline);
1181				}
1182			case RECORD_VIDEO:
1183				switch (status) {
1184					case CHAT:
1185					case ONLINE:
1186						return R.drawable.ic_send_videocam_online;
1187					case AWAY:
1188						return R.drawable.ic_send_videocam_away;
1189					case XA:
1190					case DND:
1191						return R.drawable.ic_send_videocam_dnd;
1192					default:
1193						return activity.getThemeResource(R.attr.ic_send_videocam_offline, R.drawable.ic_send_videocam_offline);
1194				}
1195			case TAKE_PHOTO:
1196				switch (status) {
1197					case CHAT:
1198					case ONLINE:
1199						return R.drawable.ic_send_photo_online;
1200					case AWAY:
1201						return R.drawable.ic_send_photo_away;
1202					case XA:
1203					case DND:
1204						return R.drawable.ic_send_photo_dnd;
1205					default:
1206						return activity.getThemeResource(R.attr.ic_send_photo_offline, R.drawable.ic_send_photo_offline);
1207				}
1208			case RECORD_VOICE:
1209				switch (status) {
1210					case CHAT:
1211					case ONLINE:
1212						return R.drawable.ic_send_voice_online;
1213					case AWAY:
1214						return R.drawable.ic_send_voice_away;
1215					case XA:
1216					case DND:
1217						return R.drawable.ic_send_voice_dnd;
1218					default:
1219						return activity.getThemeResource(R.attr.ic_send_voice_offline, R.drawable.ic_send_voice_offline);
1220				}
1221			case SEND_LOCATION:
1222				switch (status) {
1223					case CHAT:
1224					case ONLINE:
1225						return R.drawable.ic_send_location_online;
1226					case AWAY:
1227						return R.drawable.ic_send_location_away;
1228					case XA:
1229					case DND:
1230						return R.drawable.ic_send_location_dnd;
1231					default:
1232						return activity.getThemeResource(R.attr.ic_send_location_offline, R.drawable.ic_send_location_offline);
1233				}
1234			case CANCEL:
1235				switch (status) {
1236					case CHAT:
1237					case ONLINE:
1238						return R.drawable.ic_send_cancel_online;
1239					case AWAY:
1240						return R.drawable.ic_send_cancel_away;
1241					case XA:
1242					case DND:
1243						return R.drawable.ic_send_cancel_dnd;
1244					default:
1245						return activity.getThemeResource(R.attr.ic_send_cancel_offline, R.drawable.ic_send_cancel_offline);
1246				}
1247			case CHOOSE_PICTURE:
1248				switch (status) {
1249					case CHAT:
1250					case ONLINE:
1251						return R.drawable.ic_send_picture_online;
1252					case AWAY:
1253						return R.drawable.ic_send_picture_away;
1254					case XA:
1255					case DND:
1256						return R.drawable.ic_send_picture_dnd;
1257					default:
1258						return activity.getThemeResource(R.attr.ic_send_picture_offline, R.drawable.ic_send_picture_offline);
1259				}
1260		}
1261		return activity.getThemeResource(R.attr.ic_send_text_offline, R.drawable.ic_send_text_offline);
1262	}
1263
1264	private void updateEditablity() {
1265		boolean canWrite = this.conversation.getMode() == Conversation.MODE_SINGLE || this.conversation.getMucOptions().participating() || this.conversation.getNextCounterpart() != null;
1266		this.mEditMessage.setFocusable(canWrite);
1267		this.mEditMessage.setFocusableInTouchMode(canWrite);
1268		this.mSendButton.setEnabled(canWrite);
1269		this.mEditMessage.setCursorVisible(canWrite);
1270	}
1271
1272	public void updateSendButton() {
1273		final Conversation c = this.conversation;
1274		final SendButtonAction action;
1275		final Presence.Status status;
1276		final String text = this.mEditMessage == null ? "" : this.mEditMessage.getText().toString();
1277		final boolean empty = text.length() == 0;
1278		final boolean conference = c.getMode() == Conversation.MODE_MULTI;
1279		if (c.getCorrectingMessage() != null && (empty || text.equals(c.getCorrectingMessage().getBody()))) {
1280			action = SendButtonAction.CANCEL;
1281		} else if (conference && !c.getAccount().httpUploadAvailable()) {
1282			if (empty && c.getNextCounterpart() != null) {
1283				action = SendButtonAction.CANCEL;
1284			} else {
1285				action = SendButtonAction.TEXT;
1286			}
1287		} else {
1288			if (empty) {
1289				if (conference && c.getNextCounterpart() != null) {
1290					action = SendButtonAction.CANCEL;
1291				} else {
1292					String setting = activity.getPreferences().getString("quick_action", activity.getResources().getString(R.string.quick_action));
1293					if (!setting.equals("none") && UIHelper.receivedLocationQuestion(conversation.getLatestMessage())) {
1294						action = SendButtonAction.SEND_LOCATION;
1295					} else {
1296						if (setting.equals("recent")) {
1297							setting = activity.getPreferences().getString(ConversationActivity.RECENTLY_USED_QUICK_ACTION, SendButtonAction.TEXT.toString());
1298							action = SendButtonAction.valueOfOrDefault(setting,SendButtonAction.TEXT);
1299						} else {
1300							action = SendButtonAction.valueOfOrDefault(setting,SendButtonAction.TEXT);
1301						}
1302					}
1303				}
1304			} else {
1305				action = SendButtonAction.TEXT;
1306			}
1307		}
1308		if (activity.useSendButtonToIndicateStatus() && c.getAccount().getStatus() == Account.State.ONLINE) {
1309			if (activity.xmppConnectionService != null && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
1310				status = Presence.Status.OFFLINE;
1311			} else if (c.getMode() == Conversation.MODE_SINGLE) {
1312				status = c.getContact().getShownStatus();
1313			} else {
1314				status = c.getMucOptions().online() ? Presence.Status.ONLINE : Presence.Status.OFFLINE;
1315			}
1316		} else {
1317			status = Presence.Status.OFFLINE;
1318		}
1319		this.mSendButton.setTag(action);
1320		this.mSendButton.setImageResource(getSendButtonImageResource(action, status));
1321	}
1322
1323	protected void updateDateSeparators() {
1324		synchronized (this.messageList) {
1325			for(int i = 0; i < this.messageList.size(); ++i) {
1326				final Message current = this.messageList.get(i);
1327				if (i == 0 || !UIHelper.sameDay(this.messageList.get(i-1).getTimeSent(),current.getTimeSent())) {
1328					this.messageList.add(i,Message.createDateSeparator(current));
1329					i++;
1330				}
1331			}
1332		}
1333	}
1334
1335	protected void updateStatusMessages() {
1336		updateDateSeparators();
1337		synchronized (this.messageList) {
1338			if (showLoadMoreMessages(conversation)) {
1339				this.messageList.add(0, Message.createLoadMoreMessage(conversation));
1340			}
1341			if (conversation.getMode() == Conversation.MODE_SINGLE) {
1342				ChatState state = conversation.getIncomingChatState();
1343				if (state == ChatState.COMPOSING) {
1344					this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_is_typing, conversation.getName())));
1345				} else if (state == ChatState.PAUSED) {
1346					this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_has_stopped_typing, conversation.getName())));
1347				} else {
1348					for (int i = this.messageList.size() - 1; i >= 0; --i) {
1349						if (this.messageList.get(i).getStatus() == Message.STATUS_RECEIVED) {
1350							return;
1351						} else {
1352							if (this.messageList.get(i).getStatus() == Message.STATUS_SEND_DISPLAYED) {
1353								this.messageList.add(i + 1,
1354										Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, conversation.getName())));
1355								return;
1356							}
1357						}
1358					}
1359				}
1360			} else {
1361				ChatState state = ChatState.COMPOSING;
1362				List<MucOptions.User> users = conversation.getMucOptions().getUsersWithChatState(state,5);
1363				if (users.size() == 0) {
1364					state = ChatState.PAUSED;
1365					users = conversation.getMucOptions().getUsersWithChatState(state, 5);
1366
1367				}
1368				if (users.size() > 0) {
1369					Message statusMessage;
1370					if (users.size() == 1) {
1371						MucOptions.User user = users.get(0);
1372						int id = state == ChatState.COMPOSING ? R.string.contact_is_typing : R.string.contact_has_stopped_typing;
1373						statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.getDisplayName(user)));
1374						statusMessage.setTrueCounterpart(user.getRealJid());
1375						statusMessage.setCounterpart(user.getFullJid());
1376					} else {
1377						StringBuilder builder = new StringBuilder();
1378						for(MucOptions.User user : users) {
1379							if (builder.length() != 0) {
1380								builder.append(", ");
1381							}
1382							builder.append(UIHelper.getDisplayName(user));
1383						}
1384						int id = state == ChatState.COMPOSING ? R.string.contacts_are_typing : R.string.contacts_have_stopped_typing;
1385						statusMessage = Message.createStatusMessage(conversation, getString(id, builder.toString()));
1386					}
1387					this.messageList.add(statusMessage);
1388				}
1389
1390			}
1391		}
1392	}
1393
1394	private boolean showLoadMoreMessages(final Conversation c) {
1395		final boolean mam = hasMamSupport(c);
1396		final MessageArchiveService service = activity.xmppConnectionService.getMessageArchiveService();
1397		return mam && (c.getLastClearHistory().getTimestamp() != 0  || (c.countMessages() == 0 && c.messagesLoaded.get() && c.hasMessagesLeftOnServer()  && !service.queryInProgress(c)));
1398	}
1399
1400	private boolean hasMamSupport(final Conversation c) {
1401		if (c.getMode() == Conversation.MODE_SINGLE) {
1402			final XmppConnection connection = c.getAccount().getXmppConnection();
1403			return connection != null && connection.getFeatures().mam();
1404		} else {
1405			return c.getMucOptions().mamSupport();
1406		}
1407	}
1408
1409	protected void showSnackbar(final int message, final int action, final OnClickListener clickListener) {
1410		showSnackbar(message,action,clickListener,null);
1411	}
1412
1413	protected void showSnackbar(final int message, final int action, final OnClickListener clickListener, final View.OnLongClickListener longClickListener) {
1414		snackbar.setVisibility(View.VISIBLE);
1415		snackbar.setOnClickListener(null);
1416		snackbarMessage.setText(message);
1417		snackbarMessage.setOnClickListener(null);
1418		snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
1419		if (action != 0) {
1420			snackbarAction.setText(action);
1421		}
1422		snackbarAction.setOnClickListener(clickListener);
1423		snackbarAction.setOnLongClickListener(longClickListener);
1424	}
1425
1426	protected void hideSnackbar() {
1427		snackbar.setVisibility(View.GONE);
1428	}
1429
1430	protected void sendPlainTextMessage(Message message) {
1431		ConversationActivity activity = (ConversationActivity) getActivity();
1432		activity.xmppConnectionService.sendMessage(message);
1433		messageSent();
1434	}
1435
1436	private AtomicBoolean mSendingPgpMessage = new AtomicBoolean(false);
1437
1438	protected void sendPgpMessage(final Message message) {
1439		final ConversationActivity activity = (ConversationActivity) getActivity();
1440		final XmppConnectionService xmppService = activity.xmppConnectionService;
1441		final Contact contact = message.getConversation().getContact();
1442		if (!activity.hasPgp()) {
1443			activity.showInstallPgpDialog();
1444			return;
1445		}
1446		if (conversation.getAccount().getPgpSignature() == null) {
1447			activity.announcePgp(conversation.getAccount(), conversation, activity.onOpenPGPKeyPublished);
1448			return;
1449		}
1450		if (!mSendingPgpMessage.compareAndSet(false,true)) {
1451			Log.d(Config.LOGTAG,"sending pgp message already in progress");
1452		}
1453		if (conversation.getMode() == Conversation.MODE_SINGLE) {
1454			if (contact.getPgpKeyId() != 0) {
1455				xmppService.getPgpEngine().hasKey(contact,
1456						new UiCallback<Contact>() {
1457
1458							@Override
1459							public void userInputRequried(PendingIntent pi,
1460														  Contact contact) {
1461								activity.runIntent(
1462										pi,
1463										ConversationActivity.REQUEST_ENCRYPT_MESSAGE);
1464							}
1465
1466							@Override
1467							public void success(Contact contact) {
1468								activity.encryptTextMessage(message);
1469							}
1470
1471							@Override
1472							public void error(int error, Contact contact) {
1473								activity.runOnUiThread(new Runnable() {
1474									@Override
1475									public void run() {
1476										Toast.makeText(activity,
1477												R.string.unable_to_connect_to_keychain,
1478												Toast.LENGTH_SHORT
1479										).show();
1480									}
1481								});
1482								mSendingPgpMessage.set(false);
1483							}
1484						});
1485
1486			} else {
1487				showNoPGPKeyDialog(false,
1488						new DialogInterface.OnClickListener() {
1489
1490							@Override
1491							public void onClick(DialogInterface dialog,
1492												int which) {
1493								conversation
1494										.setNextEncryption(Message.ENCRYPTION_NONE);
1495								xmppService.updateConversation(conversation);
1496								message.setEncryption(Message.ENCRYPTION_NONE);
1497								xmppService.sendMessage(message);
1498								messageSent();
1499							}
1500						});
1501			}
1502		} else {
1503			if (conversation.getMucOptions().pgpKeysInUse()) {
1504				if (!conversation.getMucOptions().everybodyHasKeys()) {
1505					Toast warning = Toast
1506							.makeText(getActivity(),
1507									R.string.missing_public_keys,
1508									Toast.LENGTH_LONG);
1509					warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
1510					warning.show();
1511				}
1512				activity.encryptTextMessage(message);
1513			} else {
1514				showNoPGPKeyDialog(true,
1515						new DialogInterface.OnClickListener() {
1516
1517							@Override
1518							public void onClick(DialogInterface dialog,
1519												int which) {
1520								conversation
1521										.setNextEncryption(Message.ENCRYPTION_NONE);
1522								message.setEncryption(Message.ENCRYPTION_NONE);
1523								xmppService.updateConversation(conversation);
1524								xmppService.sendMessage(message);
1525								messageSent();
1526							}
1527						});
1528			}
1529		}
1530	}
1531
1532	public void showNoPGPKeyDialog(boolean plural,
1533								   DialogInterface.OnClickListener listener) {
1534		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1535		builder.setIconAttribute(android.R.attr.alertDialogIcon);
1536		if (plural) {
1537			builder.setTitle(getString(R.string.no_pgp_keys));
1538			builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
1539		} else {
1540			builder.setTitle(getString(R.string.no_pgp_key));
1541			builder.setMessage(getText(R.string.contact_has_no_pgp_key));
1542		}
1543		builder.setNegativeButton(getString(R.string.cancel), null);
1544		builder.setPositiveButton(getString(R.string.send_unencrypted),
1545				listener);
1546		builder.create().show();
1547	}
1548
1549	protected void sendAxolotlMessage(final Message message) {
1550		final ConversationActivity activity = (ConversationActivity) getActivity();
1551		final XmppConnectionService xmppService = activity.xmppConnectionService;
1552		xmppService.sendMessage(message);
1553		messageSent();
1554	}
1555
1556	protected void sendOtrMessage(final Message message) {
1557		final ConversationActivity activity = (ConversationActivity) getActivity();
1558		final XmppConnectionService xmppService = activity.xmppConnectionService;
1559		activity.selectPresence(message.getConversation(),
1560				new OnPresenceSelected() {
1561
1562					@Override
1563					public void onPresenceSelected() {
1564						message.setCounterpart(conversation.getNextCounterpart());
1565						xmppService.sendMessage(message);
1566						messageSent();
1567					}
1568				});
1569	}
1570
1571	public void appendText(String text) {
1572		if (text == null) {
1573			return;
1574		}
1575		String previous = this.mEditMessage.getText().toString();
1576		if (previous.length() != 0 && !previous.endsWith(" ")) {
1577			text = " " + text;
1578		}
1579		this.mEditMessage.append(text);
1580	}
1581
1582	@Override
1583	public boolean onEnterPressed() {
1584		if (activity.enterIsSend()) {
1585			sendMessage();
1586			return true;
1587		} else {
1588			return false;
1589		}
1590	}
1591
1592	@Override
1593	public void onTypingStarted() {
1594		Account.State status = conversation.getAccount().getStatus();
1595		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
1596			activity.xmppConnectionService.sendChatState(conversation);
1597		}
1598		activity.hideConversationsOverview();
1599		updateSendButton();
1600	}
1601
1602	@Override
1603	public void onTypingStopped() {
1604		Account.State status = conversation.getAccount().getStatus();
1605		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
1606			activity.xmppConnectionService.sendChatState(conversation);
1607		}
1608	}
1609
1610	@Override
1611	public void onTextDeleted() {
1612		Account.State status = conversation.getAccount().getStatus();
1613		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1614			activity.xmppConnectionService.sendChatState(conversation);
1615		}
1616		updateSendButton();
1617	}
1618
1619	@Override
1620	public void onTextChanged() {
1621		if (conversation != null && conversation.getCorrectingMessage() != null) {
1622			updateSendButton();
1623		}
1624	}
1625
1626	private int completionIndex = 0;
1627	private int lastCompletionLength = 0;
1628	private String incomplete;
1629	private int lastCompletionCursor;
1630	private boolean firstWord = false;
1631
1632	@Override
1633	public boolean onTabPressed(boolean repeated) {
1634		if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
1635			return false;
1636		}
1637		if (repeated) {
1638			completionIndex++;
1639		} else {
1640			lastCompletionLength = 0;
1641			completionIndex = 0;
1642			final String content = mEditMessage.getText().toString();
1643			lastCompletionCursor = mEditMessage.getSelectionEnd();
1644			int start = lastCompletionCursor > 0 ? content.lastIndexOf(" ",lastCompletionCursor-1) + 1 : 0;
1645			firstWord = start == 0;
1646			incomplete = content.substring(start,lastCompletionCursor);
1647		}
1648		List<String> completions = new ArrayList<>();
1649		for(MucOptions.User user : conversation.getMucOptions().getUsers()) {
1650			String name = user.getName();
1651			if (name != null && name.startsWith(incomplete)) {
1652				completions.add(name+(firstWord ? ": " : " "));
1653			}
1654		}
1655		Collections.sort(completions);
1656		if (completions.size() > completionIndex) {
1657			String completion = completions.get(completionIndex).substring(incomplete.length());
1658			mEditMessage.getEditableText().delete(lastCompletionCursor,lastCompletionCursor + lastCompletionLength);
1659			mEditMessage.getEditableText().insert(lastCompletionCursor, completion);
1660			lastCompletionLength = completion.length();
1661		} else {
1662			completionIndex = -1;
1663			mEditMessage.getEditableText().delete(lastCompletionCursor,lastCompletionCursor + lastCompletionLength);
1664			lastCompletionLength = 0;
1665		}
1666		return true;
1667	}
1668
1669	@Override
1670	public void onActivityResult(int requestCode, int resultCode,
1671	                                final Intent data) {
1672		if (resultCode == Activity.RESULT_OK) {
1673			if (requestCode == ConversationActivity.REQUEST_DECRYPT_PGP) {
1674				activity.getSelectedConversation().getAccount().getPgpDecryptionService().continueDecryption(true);
1675			} else if (requestCode == ConversationActivity.REQUEST_TRUST_KEYS_TEXT) {
1676				final String body = mEditMessage.getText().toString();
1677				Message message = new Message(conversation, body, conversation.getNextEncryption());
1678				sendAxolotlMessage(message);
1679			} else if (requestCode == ConversationActivity.REQUEST_TRUST_KEYS_MENU) {
1680				int choice = data.getIntExtra("choice", ConversationActivity.ATTACHMENT_CHOICE_INVALID);
1681				activity.selectPresenceToAttachFile(choice, conversation.getNextEncryption());
1682			}
1683		} else if (resultCode == Activity.RESULT_CANCELED) {
1684			if (requestCode == ConversationActivity.REQUEST_DECRYPT_PGP) {
1685				// discard the message to prevent decryption being blocked
1686				conversation.getAccount().getPgpDecryptionService().giveUpCurrentDecryption();
1687			}
1688		}
1689	}
1690
1691}