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