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