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