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