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		} else if (message.getStatus() != Message.STATUS_RECEIVED) {
 809			activity.xmppConnectionService.markMessage(message,Message.STATUS_SEND_FAILED);
 810		}
 811	}
 812
 813	private void retryDecryption(Message message) {
 814		message.setEncryption(Message.ENCRYPTION_PGP);
 815		activity.updateConversationList();
 816		updateMessages();
 817		conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
 818	}
 819
 820	protected void privateMessageWith(final Jid counterpart) {
 821		if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
 822			activity.xmppConnectionService.sendChatState(conversation);
 823		}
 824		this.mEditMessage.setText("");
 825		this.conversation.setNextCounterpart(counterpart);
 826		updateChatMsgHint();
 827		updateSendButton();
 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 OnClickListener mBlockClickListener = new OnClickListener() {
 959		@Override
 960		public void onClick(final View view) {
 961			final Jid jid = conversation.getJid();
 962			if (jid.isDomainJid()) {
 963				BlockContactDialog.show(activity, conversation);
 964			} else {
 965				PopupMenu popupMenu = new PopupMenu(activity, view);
 966				popupMenu.inflate(R.menu.block);
 967				popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
 968					@Override
 969					public boolean onMenuItemClick(MenuItem menuItem) {
 970						Blockable blockable;
 971						switch (menuItem.getItemId()) {
 972							case R.id.block_domain:
 973								blockable = conversation.getAccount().getRoster().getContact(jid.toDomainJid());
 974								break;
 975							default:
 976								blockable = conversation;
 977						}
 978						BlockContactDialog.show(activity, blockable);
 979						return true;
 980					}
 981				});
 982				popupMenu.show();
 983			}
 984		}
 985	};
 986
 987	private OnClickListener mAddBackClickListener = new OnClickListener() {
 988
 989		@Override
 990		public void onClick(View v) {
 991			final Contact contact = conversation == null ? null : conversation.getContact();
 992			if (contact != null) {
 993				activity.xmppConnectionService.createContact(contact);
 994				activity.switchToContactDetails(contact);
 995			}
 996		}
 997	};
 998
 999	private OnClickListener mAllowPresenceSubscription = new OnClickListener() {
1000		@Override
1001		public void onClick(View v) {
1002			final Contact contact = conversation == null ? null : conversation.getContact();
1003			if (contact != null) {
1004				activity.xmppConnectionService.sendPresencePacket(contact.getAccount(),
1005						activity.xmppConnectionService.getPresenceGenerator()
1006								.sendPresenceUpdatesTo(contact));
1007				hideSnackbar();
1008			}
1009		}
1010	};
1011
1012	private OnClickListener mAnswerSmpClickListener = new OnClickListener() {
1013		@Override
1014		public void onClick(View view) {
1015			Intent intent = new Intent(activity, VerifyOTRActivity.class);
1016			intent.setAction(VerifyOTRActivity.ACTION_VERIFY_CONTACT);
1017			intent.putExtra("contact", conversation.getContact().getJid().toBareJid().toString());
1018			intent.putExtra(VerifyOTRActivity.EXTRA_ACCOUNT, conversation.getAccount().getJid().toBareJid().toString());
1019			intent.putExtra("mode", VerifyOTRActivity.MODE_ANSWER_QUESTION);
1020			startActivity(intent);
1021		}
1022	};
1023
1024	private void updateSnackBar(final Conversation conversation) {
1025		final Account account = conversation.getAccount();
1026		final XmppConnection connection = account.getXmppConnection();
1027		final int mode = conversation.getMode();
1028		final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
1029		if (account.getStatus() == Account.State.DISABLED) {
1030			showSnackbar(R.string.this_account_is_disabled, R.string.enable, this.mEnableAccountListener);
1031		} else if (conversation.isBlocked()) {
1032			showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
1033		} else if (contact != null && !contact.showInRoster() && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1034			showSnackbar(R.string.contact_added_you, R.string.add_back, this.mAddBackClickListener);
1035		} else if (contact != null && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1036			showSnackbar(R.string.contact_asks_for_presence_subscription, R.string.allow, this.mAllowPresenceSubscription);
1037		} else if (mode == Conversation.MODE_MULTI
1038				&& !conversation.getMucOptions().online()
1039				&& account.getStatus() == Account.State.ONLINE) {
1040			switch (conversation.getMucOptions().getError()) {
1041				case NICK_IN_USE:
1042					showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
1043					break;
1044				case NO_RESPONSE:
1045					showSnackbar(R.string.joining_conference, 0, null);
1046					break;
1047				case SERVER_NOT_FOUND:
1048					if (conversation.receivedMessagesCount() > 0) {
1049						showSnackbar(R.string.remote_server_not_found,R.string.try_again, joinMuc);
1050					} else {
1051						showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
1052					}
1053					break;
1054				case PASSWORD_REQUIRED:
1055					showSnackbar(R.string.conference_requires_password, R.string.enter_password, enterPassword);
1056					break;
1057				case BANNED:
1058					showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
1059					break;
1060				case MEMBERS_ONLY:
1061					showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
1062					break;
1063				case KICKED:
1064					showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
1065					break;
1066				case UNKNOWN:
1067					showSnackbar(R.string.conference_unknown_error, R.string.join, joinMuc);
1068					break;
1069				case SHUTDOWN:
1070					showSnackbar(R.string.conference_shutdown, R.string.join, joinMuc);
1071					break;
1072				default:
1073					hideSnackbar();
1074					break;
1075			}
1076		} else if (account.hasPendingPgpIntent(conversation)) {
1077			showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
1078		} else if (mode == Conversation.MODE_SINGLE
1079				&& conversation.smpRequested()) {
1080			showSnackbar(R.string.smp_requested, R.string.verify, this.mAnswerSmpClickListener);
1081		} else if (mode == Conversation.MODE_SINGLE
1082				&& conversation.hasValidOtrSession()
1083				&& (conversation.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED)
1084				&& (!conversation.isOtrFingerprintVerified())) {
1085			showSnackbar(R.string.unknown_otr_fingerprint, R.string.verify, clickToVerify);
1086		} else if (connection != null
1087				&& connection.getFeatures().blocking()
1088				&& conversation.countMessages() != 0
1089				&& !conversation.isBlocked()
1090				&& conversation.isWithStranger()) {
1091			showSnackbar(R.string.received_message_from_stranger,R.string.block, mBlockClickListener);
1092		} else {
1093			hideSnackbar();
1094		}
1095	}
1096
1097	public void updateMessages() {
1098		synchronized (this.messageList) {
1099			if (getView() == null) {
1100				return;
1101			}
1102			final ConversationActivity activity = (ConversationActivity) getActivity();
1103			if (this.conversation != null) {
1104				conversation.populateWithMessages(ConversationFragment.this.messageList);
1105				updateSnackBar(conversation);
1106				updateStatusMessages();
1107				this.messageListAdapter.notifyDataSetChanged();
1108				updateChatMsgHint();
1109				if (!activity.isConversationsOverviewVisable() || !activity.isConversationsOverviewHideable()) {
1110					activity.sendReadMarkerIfNecessary(conversation);
1111				}
1112				updateSendButton();
1113				updateEditablity();
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	private void updateEditablity() {
1231		boolean canWrite = this.conversation.getMode() == Conversation.MODE_SINGLE || this.conversation.getMucOptions().participating();
1232		this.mEditMessage.setFocusable(canWrite);
1233		this.mEditMessage.setFocusableInTouchMode(canWrite);
1234		this.mSendButton.setEnabled(canWrite);
1235		this.mEditMessage.setCursorVisible(canWrite);
1236	}
1237
1238	public void updateSendButton() {
1239		final Conversation c = this.conversation;
1240		final SendButtonAction action;
1241		final Presence.Status status;
1242		final String text = this.mEditMessage == null ? "" : this.mEditMessage.getText().toString();
1243		final boolean empty = text.length() == 0;
1244		final boolean conference = c.getMode() == Conversation.MODE_MULTI;
1245		if (c.getCorrectingMessage() != null && (empty || text.equals(c.getCorrectingMessage().getBody()))) {
1246			action = SendButtonAction.CANCEL;
1247		} else if (conference && !c.getAccount().httpUploadAvailable()) {
1248			if (empty && c.getNextCounterpart() != null) {
1249				action = SendButtonAction.CANCEL;
1250			} else {
1251				action = SendButtonAction.TEXT;
1252			}
1253		} else {
1254			if (empty) {
1255				if (conference && c.getNextCounterpart() != null) {
1256					action = SendButtonAction.CANCEL;
1257				} else {
1258					String setting = activity.getPreferences().getString("quick_action", activity.getResources().getString(R.string.quick_action));
1259					if (!setting.equals("none") && UIHelper.receivedLocationQuestion(conversation.getLatestMessage())) {
1260						setting = "location";
1261					} else if (setting.equals("recent")) {
1262						setting = activity.getPreferences().getString("recently_used_quick_action", "text");
1263					}
1264					switch (setting) {
1265						case "photo":
1266							action = SendButtonAction.TAKE_PHOTO;
1267							break;
1268						case "location":
1269							action = SendButtonAction.SEND_LOCATION;
1270							break;
1271						case "voice":
1272							action = SendButtonAction.RECORD_VOICE;
1273							break;
1274						case "picture":
1275							action = SendButtonAction.CHOOSE_PICTURE;
1276							break;
1277						default:
1278							action = SendButtonAction.TEXT;
1279							break;
1280					}
1281				}
1282			} else {
1283				action = SendButtonAction.TEXT;
1284			}
1285		}
1286		if (activity.useSendButtonToIndicateStatus() && c.getAccount().getStatus() == Account.State.ONLINE) {
1287			if (activity.xmppConnectionService != null && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
1288				status = Presence.Status.OFFLINE;
1289			} else if (c.getMode() == Conversation.MODE_SINGLE) {
1290				status = c.getContact().getShownStatus();
1291			} else {
1292				status = c.getMucOptions().online() ? Presence.Status.ONLINE : Presence.Status.OFFLINE;
1293			}
1294		} else {
1295			status = Presence.Status.OFFLINE;
1296		}
1297		this.mSendButton.setTag(action);
1298		this.mSendButton.setImageResource(getSendButtonImageResource(action, status));
1299	}
1300
1301	protected void updateStatusMessages() {
1302		synchronized (this.messageList) {
1303			if (showLoadMoreMessages(conversation)) {
1304				this.messageList.add(0, Message.createLoadMoreMessage(conversation));
1305			}
1306			if (conversation.getMode() == Conversation.MODE_SINGLE) {
1307				ChatState state = conversation.getIncomingChatState();
1308				if (state == ChatState.COMPOSING) {
1309					this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_is_typing, conversation.getName())));
1310				} else if (state == ChatState.PAUSED) {
1311					this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_has_stopped_typing, conversation.getName())));
1312				} else {
1313					for (int i = this.messageList.size() - 1; i >= 0; --i) {
1314						if (this.messageList.get(i).getStatus() == Message.STATUS_RECEIVED) {
1315							return;
1316						} else {
1317							if (this.messageList.get(i).getStatus() == Message.STATUS_SEND_DISPLAYED) {
1318								this.messageList.add(i + 1,
1319										Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, conversation.getName())));
1320								return;
1321							}
1322						}
1323					}
1324				}
1325			} else {
1326				ChatState state = ChatState.COMPOSING;
1327				List<MucOptions.User> users = conversation.getMucOptions().getUsersWithChatState(state,5);
1328				if (users.size() == 0) {
1329					state = ChatState.PAUSED;
1330					users = conversation.getMucOptions().getUsersWithChatState(state, 5);
1331
1332				}
1333				if (users.size() > 0) {
1334					Message statusMessage;
1335					if (users.size() == 1) {
1336						MucOptions.User user = users.get(0);
1337						int id = state == ChatState.COMPOSING ? R.string.contact_is_typing : R.string.contact_has_stopped_typing;
1338						statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.getDisplayName(user)));
1339						statusMessage.setTrueCounterpart(user.getRealJid());
1340						statusMessage.setCounterpart(user.getFullJid());
1341					} else {
1342						StringBuilder builder = new StringBuilder();
1343						for(MucOptions.User user : users) {
1344							if (builder.length() != 0) {
1345								builder.append(", ");
1346							}
1347							builder.append(UIHelper.getDisplayName(user));
1348						}
1349						int id = state == ChatState.COMPOSING ? R.string.contacts_are_typing : R.string.contacts_have_stopped_typing;
1350						statusMessage = Message.createStatusMessage(conversation, getString(id, builder.toString()));
1351					}
1352					this.messageList.add(statusMessage);
1353				}
1354
1355			}
1356		}
1357	}
1358
1359	private boolean showLoadMoreMessages(final Conversation c) {
1360		final boolean mam = hasMamSupport(c);
1361		final MessageArchiveService service = activity.xmppConnectionService.getMessageArchiveService();
1362		return mam && (c.getLastClearHistory().getTimestamp() != 0  || (c.countMessages() == 0 && c.messagesLoaded.get() && c.hasMessagesLeftOnServer()  && !service.queryInProgress(c)));
1363	}
1364
1365	private boolean hasMamSupport(final Conversation c) {
1366		if (c.getMode() == Conversation.MODE_SINGLE) {
1367			final XmppConnection connection = c.getAccount().getXmppConnection();
1368			return connection != null && connection.getFeatures().mam();
1369		} else {
1370			return c.getMucOptions().mamSupport();
1371		}
1372	}
1373
1374	protected void showSnackbar(final int message, final int action, final OnClickListener clickListener) {
1375		snackbar.setVisibility(View.VISIBLE);
1376		snackbar.setOnClickListener(null);
1377		snackbarMessage.setText(message);
1378		snackbarMessage.setOnClickListener(null);
1379		snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
1380		if (action != 0) {
1381			snackbarAction.setText(action);
1382		}
1383		snackbarAction.setOnClickListener(clickListener);
1384	}
1385
1386	protected void hideSnackbar() {
1387		snackbar.setVisibility(View.GONE);
1388	}
1389
1390	protected void sendPlainTextMessage(Message message) {
1391		ConversationActivity activity = (ConversationActivity) getActivity();
1392		activity.xmppConnectionService.sendMessage(message);
1393		messageSent();
1394	}
1395
1396	private AtomicBoolean mSendingPgpMessage = new AtomicBoolean(false);
1397
1398	protected void sendPgpMessage(final Message message) {
1399		final ConversationActivity activity = (ConversationActivity) getActivity();
1400		final XmppConnectionService xmppService = activity.xmppConnectionService;
1401		final Contact contact = message.getConversation().getContact();
1402		if (!activity.hasPgp()) {
1403			activity.showInstallPgpDialog();
1404			return;
1405		}
1406		if (conversation.getAccount().getPgpSignature() == null) {
1407			activity.announcePgp(conversation.getAccount(), conversation, activity.onOpenPGPKeyPublished);
1408			return;
1409		}
1410		if (!mSendingPgpMessage.compareAndSet(false,true)) {
1411			Log.d(Config.LOGTAG,"sending pgp message already in progress");
1412		}
1413		if (conversation.getMode() == Conversation.MODE_SINGLE) {
1414			if (contact.getPgpKeyId() != 0) {
1415				xmppService.getPgpEngine().hasKey(contact,
1416						new UiCallback<Contact>() {
1417
1418							@Override
1419							public void userInputRequried(PendingIntent pi,
1420														  Contact contact) {
1421								activity.runIntent(
1422										pi,
1423										ConversationActivity.REQUEST_ENCRYPT_MESSAGE);
1424							}
1425
1426							@Override
1427							public void success(Contact contact) {
1428								activity.encryptTextMessage(message);
1429							}
1430
1431							@Override
1432							public void error(int error, Contact contact) {
1433								activity.runOnUiThread(new Runnable() {
1434									@Override
1435									public void run() {
1436										Toast.makeText(activity,
1437												R.string.unable_to_connect_to_keychain,
1438												Toast.LENGTH_SHORT
1439										).show();
1440									}
1441								});
1442								mSendingPgpMessage.set(false);
1443							}
1444						});
1445
1446			} else {
1447				showNoPGPKeyDialog(false,
1448						new DialogInterface.OnClickListener() {
1449
1450							@Override
1451							public void onClick(DialogInterface dialog,
1452												int which) {
1453								conversation
1454										.setNextEncryption(Message.ENCRYPTION_NONE);
1455								xmppService.updateConversation(conversation);
1456								message.setEncryption(Message.ENCRYPTION_NONE);
1457								xmppService.sendMessage(message);
1458								messageSent();
1459							}
1460						});
1461			}
1462		} else {
1463			if (conversation.getMucOptions().pgpKeysInUse()) {
1464				if (!conversation.getMucOptions().everybodyHasKeys()) {
1465					Toast warning = Toast
1466							.makeText(getActivity(),
1467									R.string.missing_public_keys,
1468									Toast.LENGTH_LONG);
1469					warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
1470					warning.show();
1471				}
1472				activity.encryptTextMessage(message);
1473			} else {
1474				showNoPGPKeyDialog(true,
1475						new DialogInterface.OnClickListener() {
1476
1477							@Override
1478							public void onClick(DialogInterface dialog,
1479												int which) {
1480								conversation
1481										.setNextEncryption(Message.ENCRYPTION_NONE);
1482								message.setEncryption(Message.ENCRYPTION_NONE);
1483								xmppService.updateConversation(conversation);
1484								xmppService.sendMessage(message);
1485								messageSent();
1486							}
1487						});
1488			}
1489		}
1490	}
1491
1492	public void showNoPGPKeyDialog(boolean plural,
1493								   DialogInterface.OnClickListener listener) {
1494		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1495		builder.setIconAttribute(android.R.attr.alertDialogIcon);
1496		if (plural) {
1497			builder.setTitle(getString(R.string.no_pgp_keys));
1498			builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
1499		} else {
1500			builder.setTitle(getString(R.string.no_pgp_key));
1501			builder.setMessage(getText(R.string.contact_has_no_pgp_key));
1502		}
1503		builder.setNegativeButton(getString(R.string.cancel), null);
1504		builder.setPositiveButton(getString(R.string.send_unencrypted),
1505				listener);
1506		builder.create().show();
1507	}
1508
1509	protected void sendAxolotlMessage(final Message message) {
1510		final ConversationActivity activity = (ConversationActivity) getActivity();
1511		final XmppConnectionService xmppService = activity.xmppConnectionService;
1512		xmppService.sendMessage(message);
1513		messageSent();
1514	}
1515
1516	protected void sendOtrMessage(final Message message) {
1517		final ConversationActivity activity = (ConversationActivity) getActivity();
1518		final XmppConnectionService xmppService = activity.xmppConnectionService;
1519		activity.selectPresence(message.getConversation(),
1520				new OnPresenceSelected() {
1521
1522					@Override
1523					public void onPresenceSelected() {
1524						message.setCounterpart(conversation.getNextCounterpart());
1525						xmppService.sendMessage(message);
1526						messageSent();
1527					}
1528				});
1529	}
1530
1531	public void appendText(String text) {
1532		if (text == null) {
1533			return;
1534		}
1535		String previous = this.mEditMessage.getText().toString();
1536		if (previous.length() != 0 && !previous.endsWith(" ")) {
1537			text = " " + text;
1538		}
1539		this.mEditMessage.append(text);
1540	}
1541
1542	@Override
1543	public boolean onEnterPressed() {
1544		if (activity.enterIsSend()) {
1545			sendMessage();
1546			return true;
1547		} else {
1548			return false;
1549		}
1550	}
1551
1552	@Override
1553	public void onTypingStarted() {
1554		Account.State status = conversation.getAccount().getStatus();
1555		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
1556			activity.xmppConnectionService.sendChatState(conversation);
1557		}
1558		activity.hideConversationsOverview();
1559		updateSendButton();
1560	}
1561
1562	@Override
1563	public void onTypingStopped() {
1564		Account.State status = conversation.getAccount().getStatus();
1565		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
1566			activity.xmppConnectionService.sendChatState(conversation);
1567		}
1568	}
1569
1570	@Override
1571	public void onTextDeleted() {
1572		Account.State status = conversation.getAccount().getStatus();
1573		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1574			activity.xmppConnectionService.sendChatState(conversation);
1575		}
1576		updateSendButton();
1577	}
1578
1579	@Override
1580	public void onTextChanged() {
1581		if (conversation != null && conversation.getCorrectingMessage() != null) {
1582			updateSendButton();
1583		}
1584	}
1585
1586	private int completionIndex = 0;
1587	private int lastCompletionLength = 0;
1588	private String incomplete;
1589	private int lastCompletionCursor;
1590	private boolean firstWord = false;
1591
1592	@Override
1593	public boolean onTabPressed(boolean repeated) {
1594		if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
1595			return false;
1596		}
1597		if (repeated) {
1598			completionIndex++;
1599		} else {
1600			lastCompletionLength = 0;
1601			completionIndex = 0;
1602			final String content = mEditMessage.getText().toString();
1603			lastCompletionCursor = mEditMessage.getSelectionEnd();
1604			int start = lastCompletionCursor > 0 ? content.lastIndexOf(" ",lastCompletionCursor-1) + 1 : 0;
1605			firstWord = start == 0;
1606			incomplete = content.substring(start,lastCompletionCursor);
1607		}
1608		List<String> completions = new ArrayList<>();
1609		for(MucOptions.User user : conversation.getMucOptions().getUsers()) {
1610			String name = user.getName();
1611			if (name != null && name.startsWith(incomplete)) {
1612				completions.add(name+(firstWord ? ": " : " "));
1613			}
1614		}
1615		Collections.sort(completions);
1616		if (completions.size() > completionIndex) {
1617			String completion = completions.get(completionIndex).substring(incomplete.length());
1618			mEditMessage.getEditableText().delete(lastCompletionCursor,lastCompletionCursor + lastCompletionLength);
1619			mEditMessage.getEditableText().insert(lastCompletionCursor, completion);
1620			lastCompletionLength = completion.length();
1621		} else {
1622			completionIndex = -1;
1623			mEditMessage.getEditableText().delete(lastCompletionCursor,lastCompletionCursor + lastCompletionLength);
1624			lastCompletionLength = 0;
1625		}
1626		return true;
1627	}
1628
1629	@Override
1630	public void onActivityResult(int requestCode, int resultCode,
1631	                                final Intent data) {
1632		if (resultCode == Activity.RESULT_OK) {
1633			if (requestCode == ConversationActivity.REQUEST_DECRYPT_PGP) {
1634				activity.getSelectedConversation().getAccount().getPgpDecryptionService().continueDecryption(true);
1635			} else if (requestCode == ConversationActivity.REQUEST_TRUST_KEYS_TEXT) {
1636				final String body = mEditMessage.getText().toString();
1637				Message message = new Message(conversation, body, conversation.getNextEncryption());
1638				sendAxolotlMessage(message);
1639			} else if (requestCode == ConversationActivity.REQUEST_TRUST_KEYS_MENU) {
1640				int choice = data.getIntExtra("choice", ConversationActivity.ATTACHMENT_CHOICE_INVALID);
1641				activity.selectPresenceToAttachFile(choice, conversation.getNextEncryption());
1642			}
1643		}
1644	}
1645
1646}