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