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