ConversationActivity.java

   1package eu.siacs.conversations.ui;
   2
   3import android.annotation.SuppressLint;
   4import android.app.ActionBar;
   5import android.app.AlertDialog;
   6import android.app.FragmentTransaction;
   7import android.app.PendingIntent;
   8import android.content.ClipData;
   9import android.content.DialogInterface;
  10import android.content.DialogInterface.OnClickListener;
  11import android.content.Intent;
  12import android.content.IntentSender.SendIntentException;
  13import android.net.Uri;
  14import android.os.Build;
  15import android.os.Bundle;
  16import android.provider.MediaStore;
  17import android.support.v4.widget.SlidingPaneLayout;
  18import android.support.v4.widget.SlidingPaneLayout.PanelSlideListener;
  19import android.util.Log;
  20import android.view.KeyEvent;
  21import android.view.Menu;
  22import android.view.MenuItem;
  23import android.view.Surface;
  24import android.view.View;
  25import android.widget.AdapterView;
  26import android.widget.AdapterView.OnItemClickListener;
  27import android.widget.ArrayAdapter;
  28import android.widget.CheckBox;
  29import android.widget.PopupMenu;
  30import android.widget.PopupMenu.OnMenuItemClickListener;
  31import android.widget.Toast;
  32
  33import net.java.otr4j.session.SessionStatus;
  34
  35import java.util.ArrayList;
  36import java.util.Iterator;
  37import java.util.List;
  38
  39import de.timroes.android.listview.EnhancedListView;
  40import eu.siacs.conversations.Config;
  41import eu.siacs.conversations.R;
  42import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  43import eu.siacs.conversations.crypto.axolotl.XmppAxolotlSession;
  44import eu.siacs.conversations.entities.Account;
  45import eu.siacs.conversations.entities.Blockable;
  46import eu.siacs.conversations.entities.Contact;
  47import eu.siacs.conversations.entities.Conversation;
  48import eu.siacs.conversations.entities.Message;
  49import eu.siacs.conversations.services.XmppConnectionService;
  50import eu.siacs.conversations.services.XmppConnectionService.OnAccountUpdate;
  51import eu.siacs.conversations.services.XmppConnectionService.OnConversationUpdate;
  52import eu.siacs.conversations.services.XmppConnectionService.OnRosterUpdate;
  53import eu.siacs.conversations.ui.adapter.ConversationAdapter;
  54import eu.siacs.conversations.utils.ExceptionHelper;
  55import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
  56import eu.siacs.conversations.xmpp.jid.InvalidJidException;
  57import eu.siacs.conversations.xmpp.jid.Jid;
  58
  59public class ConversationActivity extends XmppActivity
  60	implements OnAccountUpdate, OnConversationUpdate, OnRosterUpdate, OnUpdateBlocklist, XmppConnectionService.OnShowErrorToast {
  61
  62	public static final String ACTION_DOWNLOAD = "eu.siacs.conversations.action.DOWNLOAD";
  63
  64	public static final String VIEW_CONVERSATION = "viewConversation";
  65	public static final String CONVERSATION = "conversationUuid";
  66	public static final String MESSAGE = "messageUuid";
  67	public static final String TEXT = "text";
  68	public static final String NICK = "nick";
  69	public static final String PRIVATE_MESSAGE = "pm";
  70
  71	public static final int REQUEST_SEND_MESSAGE = 0x0201;
  72	public static final int REQUEST_DECRYPT_PGP = 0x0202;
  73	public static final int REQUEST_ENCRYPT_MESSAGE = 0x0207;
  74	public static final int REQUEST_TRUST_KEYS_TEXT = 0x0208;
  75	public static final int REQUEST_TRUST_KEYS_MENU = 0x0209;
  76	public static final int ATTACHMENT_CHOICE_CHOOSE_IMAGE = 0x0301;
  77	public static final int ATTACHMENT_CHOICE_TAKE_PHOTO = 0x0302;
  78	public static final int ATTACHMENT_CHOICE_CHOOSE_FILE = 0x0303;
  79	public static final int ATTACHMENT_CHOICE_RECORD_VOICE = 0x0304;
  80	public static final int ATTACHMENT_CHOICE_LOCATION = 0x0305;
  81	public static final int ATTACHMENT_CHOICE_INVALID = 0x0306;
  82	private static final String STATE_OPEN_CONVERSATION = "state_open_conversation";
  83	private static final String STATE_PANEL_OPEN = "state_panel_open";
  84	private static final String STATE_PENDING_URI = "state_pending_uri";
  85
  86	private String mOpenConverstaion = null;
  87	private boolean mPanelOpen = true;
  88	final private List<Uri> mPendingImageUris = new ArrayList<>();
  89	final private List<Uri> mPendingFileUris = new ArrayList<>();
  90	private Uri mPendingGeoUri = null;
  91	private boolean forbidProcessingPendings = false;
  92
  93	private boolean conversationWasSelectedByKeyboard = false;
  94
  95	private View mContentView;
  96
  97	private List<Conversation> conversationList = new ArrayList<>();
  98	private Conversation swipedConversation = null;
  99	private Conversation mSelectedConversation = null;
 100	private EnhancedListView listView;
 101	private ConversationFragment mConversationFragment;
 102
 103	private ArrayAdapter<Conversation> listAdapter;
 104
 105	private Toast prepareFileToast;
 106
 107	private boolean mActivityPaused = false;
 108	private boolean mRedirected = true;
 109
 110	public Conversation getSelectedConversation() {
 111		return this.mSelectedConversation;
 112	}
 113
 114	public void setSelectedConversation(Conversation conversation) {
 115		this.mSelectedConversation = conversation;
 116	}
 117
 118	public void showConversationsOverview() {
 119		if (mContentView instanceof SlidingPaneLayout) {
 120			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 121			mSlidingPaneLayout.openPane();
 122		}
 123	}
 124
 125	@Override
 126	protected String getShareableUri() {
 127		Conversation conversation = getSelectedConversation();
 128		if (conversation != null) {
 129			return conversation.getAccount().getShareableUri();
 130		} else {
 131			return "";
 132		}
 133	}
 134
 135	public void hideConversationsOverview() {
 136		if (mContentView instanceof SlidingPaneLayout) {
 137			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 138			mSlidingPaneLayout.closePane();
 139		}
 140	}
 141
 142	public boolean isConversationsOverviewHideable() {
 143		if (mContentView instanceof SlidingPaneLayout) {
 144			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 145			return mSlidingPaneLayout.isSlideable();
 146		} else {
 147			return false;
 148		}
 149	}
 150
 151	public boolean isConversationsOverviewVisable() {
 152		if (mContentView instanceof SlidingPaneLayout) {
 153			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 154			return mSlidingPaneLayout.isOpen();
 155		} else {
 156			return true;
 157		}
 158	}
 159
 160	@Override
 161	protected void onCreate(final Bundle savedInstanceState) {
 162		super.onCreate(savedInstanceState);
 163		if (savedInstanceState != null) {
 164			mOpenConverstaion = savedInstanceState.getString(STATE_OPEN_CONVERSATION, null);
 165			mPanelOpen = savedInstanceState.getBoolean(STATE_PANEL_OPEN, true);
 166			String pending = savedInstanceState.getString(STATE_PENDING_URI, null);
 167			if (pending != null) {
 168				mPendingImageUris.clear();
 169				mPendingImageUris.add(Uri.parse(pending));
 170			}
 171		}
 172
 173		setContentView(R.layout.fragment_conversations_overview);
 174
 175		this.mConversationFragment = new ConversationFragment();
 176		FragmentTransaction transaction = getFragmentManager().beginTransaction();
 177		transaction.replace(R.id.selected_conversation, this.mConversationFragment, "conversation");
 178		transaction.commit();
 179
 180		listView = (EnhancedListView) findViewById(R.id.list);
 181		this.listAdapter = new ConversationAdapter(this, conversationList);
 182		listView.setAdapter(this.listAdapter);
 183
 184		if (getActionBar() != null) {
 185			getActionBar().setDisplayHomeAsUpEnabled(false);
 186			getActionBar().setHomeButtonEnabled(false);
 187		}
 188
 189		listView.setOnItemClickListener(new OnItemClickListener() {
 190
 191			@Override
 192			public void onItemClick(AdapterView<?> arg0, View clickedView,
 193					int position, long arg3) {
 194				if (getSelectedConversation() != conversationList.get(position)) {
 195					setSelectedConversation(conversationList.get(position));
 196					ConversationActivity.this.mConversationFragment.reInit(getSelectedConversation());
 197					conversationWasSelectedByKeyboard = false;
 198				}
 199				hideConversationsOverview();
 200				openConversation();
 201			}
 202		});
 203
 204		listView.setDismissCallback(new EnhancedListView.OnDismissCallback() {
 205
 206			@Override
 207			public EnhancedListView.Undoable onDismiss(final EnhancedListView enhancedListView, final int position) {
 208
 209				final int index = listView.getFirstVisiblePosition();
 210				View v = listView.getChildAt(0);
 211				final int top = (v == null) ? 0 : (v.getTop() - listView.getPaddingTop());
 212
 213				swipedConversation = listAdapter.getItem(position);
 214				listAdapter.remove(swipedConversation);
 215				swipedConversation.markRead();
 216				xmppConnectionService.getNotificationService().clear(swipedConversation);
 217
 218				final boolean formerlySelected = (getSelectedConversation() == swipedConversation);
 219				if (position == 0 && listAdapter.getCount() == 0) {
 220					endConversation(swipedConversation, false, true);
 221					return null;
 222				} else if (formerlySelected) {
 223					setSelectedConversation(listAdapter.getItem(0));
 224					ConversationActivity.this.mConversationFragment
 225							.reInit(getSelectedConversation());
 226				}
 227
 228				return new EnhancedListView.Undoable() {
 229
 230					@Override
 231					public void undo() {
 232						listAdapter.insert(swipedConversation, position);
 233						if (formerlySelected) {
 234							setSelectedConversation(swipedConversation);
 235							ConversationActivity.this.mConversationFragment
 236									.reInit(getSelectedConversation());
 237						}
 238						swipedConversation = null;
 239						listView.setSelectionFromTop(index + (listView.getChildCount() < position ? 1 : 0), top);
 240					}
 241
 242					@Override
 243					public void discard() {
 244						if (!swipedConversation.isRead()
 245								&& swipedConversation.getMode() == Conversation.MODE_SINGLE) {
 246							swipedConversation = null;
 247							return;
 248						}
 249						endConversation(swipedConversation, false, false);
 250						swipedConversation = null;
 251					}
 252
 253					@Override
 254					public String getTitle() {
 255						if (swipedConversation.getMode() == Conversation.MODE_MULTI) {
 256							return getResources().getString(R.string.title_undo_swipe_out_muc);
 257						} else {
 258							return getResources().getString(R.string.title_undo_swipe_out_conversation);
 259						}
 260					}
 261				};
 262			}
 263		});
 264		listView.enableSwipeToDismiss();
 265		listView.setSwipingLayout(R.id.swipeable_item);
 266		listView.setUndoStyle(EnhancedListView.UndoStyle.SINGLE_POPUP);
 267		listView.setUndoHideDelay(5000);
 268		listView.setRequireTouchBeforeDismiss(false);
 269
 270		mContentView = findViewById(R.id.content_view_spl);
 271		if (mContentView == null) {
 272			mContentView = findViewById(R.id.content_view_ll);
 273		}
 274		if (mContentView instanceof SlidingPaneLayout) {
 275			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 276			mSlidingPaneLayout.setParallaxDistance(150);
 277			mSlidingPaneLayout
 278				.setShadowResource(R.drawable.es_slidingpane_shadow);
 279			mSlidingPaneLayout.setSliderFadeColor(0);
 280			mSlidingPaneLayout.setPanelSlideListener(new PanelSlideListener() {
 281
 282				@Override
 283				public void onPanelOpened(View arg0) {
 284					updateActionBarTitle();
 285					invalidateOptionsMenu();
 286					hideKeyboard();
 287					if (xmppConnectionServiceBound) {
 288						xmppConnectionService.getNotificationService()
 289							.setOpenConversation(null);
 290					}
 291					closeContextMenu();
 292				}
 293
 294				@Override
 295				public void onPanelClosed(View arg0) {
 296					listView.discardUndo();
 297					openConversation();
 298				}
 299
 300				@Override
 301				public void onPanelSlide(View arg0, float arg1) {
 302					// TODO Auto-generated method stub
 303
 304				}
 305			});
 306		}
 307	}
 308
 309	@Override
 310	public void switchToConversation(Conversation conversation) {
 311		setSelectedConversation(conversation);
 312		runOnUiThread(new Runnable() {
 313			@Override
 314			public void run() {
 315				ConversationActivity.this.mConversationFragment.reInit(getSelectedConversation());
 316				openConversation();
 317			}
 318		});
 319	}
 320
 321	private void updateActionBarTitle() {
 322		updateActionBarTitle(isConversationsOverviewHideable() && !isConversationsOverviewVisable());
 323	}
 324
 325	private void updateActionBarTitle(boolean titleShouldBeName) {
 326		final ActionBar ab = getActionBar();
 327		final Conversation conversation = getSelectedConversation();
 328		if (ab != null) {
 329			if (titleShouldBeName && conversation != null) {
 330				ab.setDisplayHomeAsUpEnabled(true);
 331				ab.setHomeButtonEnabled(true);
 332				if (conversation.getMode() == Conversation.MODE_SINGLE || useSubjectToIdentifyConference()) {
 333					ab.setTitle(conversation.getName());
 334				} else {
 335					ab.setTitle(conversation.getJid().toBareJid().toString());
 336				}
 337			} else {
 338				ab.setDisplayHomeAsUpEnabled(false);
 339				ab.setHomeButtonEnabled(false);
 340				ab.setTitle(R.string.app_name);
 341			}
 342		}
 343	}
 344
 345	private void openConversation() {
 346		this.updateActionBarTitle();
 347		this.invalidateOptionsMenu();
 348		if (xmppConnectionServiceBound) {
 349			final Conversation conversation = getSelectedConversation();
 350			xmppConnectionService.getNotificationService().setOpenConversation(conversation);
 351			sendReadMarkerIfNecessary(conversation);
 352		}
 353		listAdapter.notifyDataSetChanged();
 354	}
 355
 356	public void sendReadMarkerIfNecessary(final Conversation conversation) {
 357		if (!mActivityPaused && conversation != null) {
 358			if (!conversation.isRead()) {
 359				xmppConnectionService.sendReadMarker(conversation);
 360			} else {
 361				xmppConnectionService.markRead(conversation);
 362			}
 363		}
 364	}
 365
 366	@Override
 367	public boolean onCreateOptionsMenu(Menu menu) {
 368		getMenuInflater().inflate(R.menu.conversations, menu);
 369		final MenuItem menuSecure = menu.findItem(R.id.action_security);
 370		final MenuItem menuArchive = menu.findItem(R.id.action_archive);
 371		final MenuItem menuMucDetails = menu.findItem(R.id.action_muc_details);
 372		final MenuItem menuContactDetails = menu.findItem(R.id.action_contact_details);
 373		final MenuItem menuAttach = menu.findItem(R.id.action_attach_file);
 374		final MenuItem menuClearHistory = menu.findItem(R.id.action_clear_history);
 375		final MenuItem menuAdd = menu.findItem(R.id.action_add);
 376		final MenuItem menuInviteContact = menu.findItem(R.id.action_invite);
 377		final MenuItem menuMute = menu.findItem(R.id.action_mute);
 378		final MenuItem menuUnmute = menu.findItem(R.id.action_unmute);
 379
 380		if (isConversationsOverviewVisable() && isConversationsOverviewHideable()) {
 381			menuArchive.setVisible(false);
 382			menuMucDetails.setVisible(false);
 383			menuContactDetails.setVisible(false);
 384			menuSecure.setVisible(false);
 385			menuInviteContact.setVisible(false);
 386			menuAttach.setVisible(false);
 387			menuClearHistory.setVisible(false);
 388			menuMute.setVisible(false);
 389			menuUnmute.setVisible(false);
 390		} else {
 391			menuAdd.setVisible(!isConversationsOverviewHideable());
 392			if (this.getSelectedConversation() != null) {
 393				if (this.getSelectedConversation().getNextEncryption() != Message.ENCRYPTION_NONE) {
 394					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
 395						menuSecure.setIcon(R.drawable.ic_lock_white_24dp);
 396					} else {
 397						menuSecure.setIcon(R.drawable.ic_action_secure);
 398					}
 399				}
 400				if (this.getSelectedConversation().getMode() == Conversation.MODE_MULTI) {
 401					menuContactDetails.setVisible(false);
 402					menuAttach.setVisible(getSelectedConversation().getAccount().httpUploadAvailable());
 403					menuInviteContact.setVisible(getSelectedConversation().getMucOptions().canInvite());
 404					menuSecure.setVisible(!Config.HIDE_PGP_IN_UI); //if pgp is hidden conferences have no choice of encryption
 405				} else {
 406					menuMucDetails.setVisible(false);
 407				}
 408				if (this.getSelectedConversation().isMuted()) {
 409					menuMute.setVisible(false);
 410				} else {
 411					menuUnmute.setVisible(false);
 412				}
 413			}
 414		}
 415		return true;
 416	}
 417
 418	protected void selectPresenceToAttachFile(final int attachmentChoice, final int encryption) {
 419		final Conversation conversation = getSelectedConversation();
 420		final Account account = conversation.getAccount();
 421		final OnPresenceSelected callback = new OnPresenceSelected() {
 422
 423			@Override
 424			public void onPresenceSelected() {
 425				Intent intent = new Intent();
 426				boolean chooser = false;
 427				String fallbackPackageId = null;
 428				switch (attachmentChoice) {
 429					case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
 430						intent.setAction(Intent.ACTION_GET_CONTENT);
 431						if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
 432							intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE,true);
 433						}
 434						intent.setType("image/*");
 435						chooser = true;
 436						break;
 437					case ATTACHMENT_CHOICE_TAKE_PHOTO:
 438						Uri uri = xmppConnectionService.getFileBackend().getTakePhotoUri();
 439						intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
 440						intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
 441						mPendingImageUris.clear();
 442						mPendingImageUris.add(uri);
 443						break;
 444					case ATTACHMENT_CHOICE_CHOOSE_FILE:
 445						chooser = true;
 446						intent.setType("*/*");
 447						intent.addCategory(Intent.CATEGORY_OPENABLE);
 448						intent.setAction(Intent.ACTION_GET_CONTENT);
 449						break;
 450					case ATTACHMENT_CHOICE_RECORD_VOICE:
 451						intent.setAction(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
 452						fallbackPackageId = "eu.siacs.conversations.voicerecorder";
 453						break;
 454					case ATTACHMENT_CHOICE_LOCATION:
 455						intent.setAction("eu.siacs.conversations.location.request");
 456						fallbackPackageId = "eu.siacs.conversations.sharelocation";
 457						break;
 458				}
 459				if (intent.resolveActivity(getPackageManager()) != null) {
 460					if (chooser) {
 461						startActivityForResult(
 462								Intent.createChooser(intent, getString(R.string.perform_action_with)),
 463								attachmentChoice);
 464					} else {
 465						startActivityForResult(intent, attachmentChoice);
 466					}
 467				} else if (fallbackPackageId != null) {
 468					startActivity(getInstallApkIntent(fallbackPackageId));
 469				}
 470			}
 471		};
 472		if ((account.httpUploadAvailable() || attachmentChoice == ATTACHMENT_CHOICE_LOCATION) && encryption != Message.ENCRYPTION_OTR) {
 473			conversation.setNextCounterpart(null);
 474			callback.onPresenceSelected();
 475		} else {
 476			selectPresence(conversation, callback);
 477		}
 478	}
 479
 480	private Intent getInstallApkIntent(final String packageId) {
 481		Intent intent = new Intent(Intent.ACTION_VIEW);
 482		intent.setData(Uri.parse("market://details?id=" + packageId));
 483		if (intent.resolveActivity(getPackageManager()) != null) {
 484			return intent;
 485		} else {
 486			intent.setData(Uri.parse("http://play.google.com/store/apps/details?id=" + packageId));
 487			return intent;
 488		}
 489	}
 490
 491	public void attachFile(final int attachmentChoice) {
 492		switch (attachmentChoice) {
 493			case ATTACHMENT_CHOICE_LOCATION:
 494				getPreferences().edit().putString("recently_used_quick_action","location").apply();
 495				break;
 496			case ATTACHMENT_CHOICE_RECORD_VOICE:
 497				getPreferences().edit().putString("recently_used_quick_action","voice").apply();
 498				break;
 499			case ATTACHMENT_CHOICE_TAKE_PHOTO:
 500				getPreferences().edit().putString("recently_used_quick_action","photo").apply();
 501				break;
 502			case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
 503				getPreferences().edit().putString("recently_used_quick_action","picture").apply();
 504				break;
 505		}
 506		final Conversation conversation = getSelectedConversation();
 507		final int encryption = conversation.getNextEncryption();
 508		if (encryption == Message.ENCRYPTION_PGP) {
 509			if (hasPgp()) {
 510				if (conversation.getContact().getPgpKeyId() != 0) {
 511					xmppConnectionService.getPgpEngine().hasKey(
 512							conversation.getContact(),
 513							new UiCallback<Contact>() {
 514
 515								@Override
 516								public void userInputRequried(PendingIntent pi,
 517										Contact contact) {
 518									ConversationActivity.this.runIntent(pi,attachmentChoice);
 519								}
 520
 521								@Override
 522								public void success(Contact contact) {
 523									selectPresenceToAttachFile(attachmentChoice,encryption);
 524								}
 525
 526								@Override
 527								public void error(int error, Contact contact) {
 528									displayErrorDialog(error);
 529								}
 530							});
 531				} else {
 532					final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
 533						.findFragmentByTag("conversation");
 534					if (fragment != null) {
 535						fragment.showNoPGPKeyDialog(false,
 536								new OnClickListener() {
 537
 538									@Override
 539									public void onClick(DialogInterface dialog,
 540											int which) {
 541										conversation
 542											.setNextEncryption(Message.ENCRYPTION_NONE);
 543										xmppConnectionService.databaseBackend
 544											.updateConversation(conversation);
 545										selectPresenceToAttachFile(attachmentChoice,Message.ENCRYPTION_NONE);
 546									}
 547								});
 548					}
 549				}
 550			} else {
 551				showInstallPgpDialog();
 552			}
 553		} else {
 554			if (encryption != Message.ENCRYPTION_AXOLOTL || !trustKeysIfNeeded(REQUEST_TRUST_KEYS_MENU, attachmentChoice)) {
 555				selectPresenceToAttachFile(attachmentChoice, encryption);
 556			}
 557		}
 558	}
 559
 560	@Override
 561	public boolean onOptionsItemSelected(final MenuItem item) {
 562		if (item.getItemId() == android.R.id.home) {
 563			showConversationsOverview();
 564			return true;
 565		} else if (item.getItemId() == R.id.action_add) {
 566			startActivity(new Intent(this, StartConversationActivity.class));
 567			return true;
 568		} else if (getSelectedConversation() != null) {
 569			switch (item.getItemId()) {
 570				case R.id.action_attach_file:
 571					attachFileDialog();
 572					break;
 573				case R.id.action_archive:
 574					this.endConversation(getSelectedConversation());
 575					break;
 576				case R.id.action_contact_details:
 577					switchToContactDetails(getSelectedConversation().getContact());
 578					break;
 579				case R.id.action_muc_details:
 580					Intent intent = new Intent(this,
 581							ConferenceDetailsActivity.class);
 582					intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
 583					intent.putExtra("uuid", getSelectedConversation().getUuid());
 584					startActivity(intent);
 585					break;
 586				case R.id.action_invite:
 587					inviteToConversation(getSelectedConversation());
 588					break;
 589				case R.id.action_security:
 590					selectEncryptionDialog(getSelectedConversation());
 591					break;
 592				case R.id.action_clear_history:
 593					clearHistoryDialog(getSelectedConversation());
 594					break;
 595				case R.id.action_mute:
 596					muteConversationDialog(getSelectedConversation());
 597					break;
 598				case R.id.action_unmute:
 599					unmuteConversation(getSelectedConversation());
 600					break;
 601				case R.id.action_block:
 602					BlockContactDialog.show(this, xmppConnectionService, getSelectedConversation());
 603					break;
 604				case R.id.action_unblock:
 605					BlockContactDialog.show(this, xmppConnectionService, getSelectedConversation());
 606					break;
 607				default:
 608					break;
 609			}
 610			return super.onOptionsItemSelected(item);
 611		} else {
 612			return super.onOptionsItemSelected(item);
 613		}
 614	}
 615
 616	public void endConversation(Conversation conversation) {
 617		endConversation(conversation, true, true);
 618	}
 619
 620	public void endConversation(Conversation conversation, boolean showOverview, boolean reinit) {
 621		if (showOverview) {
 622			showConversationsOverview();
 623		}
 624		xmppConnectionService.archiveConversation(conversation);
 625		if (reinit) {
 626			if (conversationList.size() > 0) {
 627				setSelectedConversation(conversationList.get(0));
 628				this.mConversationFragment.reInit(getSelectedConversation());
 629			} else {
 630				setSelectedConversation(null);
 631			}
 632		}
 633	}
 634
 635	@SuppressLint("InflateParams")
 636	protected void clearHistoryDialog(final Conversation conversation) {
 637		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 638		builder.setTitle(getString(R.string.clear_conversation_history));
 639		View dialogView = getLayoutInflater().inflate(
 640				R.layout.dialog_clear_history, null);
 641		final CheckBox endConversationCheckBox = (CheckBox) dialogView
 642			.findViewById(R.id.end_conversation_checkbox);
 643		builder.setView(dialogView);
 644		builder.setNegativeButton(getString(R.string.cancel), null);
 645		builder.setPositiveButton(getString(R.string.delete_messages),
 646				new OnClickListener() {
 647
 648					@Override
 649					public void onClick(DialogInterface dialog, int which) {
 650						ConversationActivity.this.xmppConnectionService.clearConversationHistory(conversation);
 651						if (endConversationCheckBox.isChecked()) {
 652							endConversation(conversation);
 653						} else {
 654							updateConversationList();
 655							ConversationActivity.this.mConversationFragment.updateMessages();
 656						}
 657					}
 658				});
 659		builder.create().show();
 660	}
 661
 662	protected void attachFileDialog() {
 663		View menuAttachFile = findViewById(R.id.action_attach_file);
 664		if (menuAttachFile == null) {
 665			return;
 666		}
 667		PopupMenu attachFilePopup = new PopupMenu(this, menuAttachFile);
 668		attachFilePopup.inflate(R.menu.attachment_choices);
 669		if (new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION).resolveActivity(getPackageManager()) == null) {
 670			attachFilePopup.getMenu().findItem(R.id.attach_record_voice).setVisible(false);
 671		}
 672		if (new Intent("eu.siacs.conversations.location.request").resolveActivity(getPackageManager()) == null) {
 673			attachFilePopup.getMenu().findItem(R.id.attach_location).setVisible(false);
 674		}
 675		attachFilePopup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 676
 677			@Override
 678			public boolean onMenuItemClick(MenuItem item) {
 679				switch (item.getItemId()) {
 680					case R.id.attach_choose_picture:
 681						attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
 682						break;
 683					case R.id.attach_take_picture:
 684						attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
 685						break;
 686					case R.id.attach_choose_file:
 687						attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
 688						break;
 689					case R.id.attach_record_voice:
 690						attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
 691						break;
 692					case R.id.attach_location:
 693						attachFile(ATTACHMENT_CHOICE_LOCATION);
 694						break;
 695				}
 696				return false;
 697			}
 698		});
 699		attachFilePopup.show();
 700	}
 701
 702	public void verifyOtrSessionDialog(final Conversation conversation, View view) {
 703		if (!conversation.hasValidOtrSession() || conversation.getOtrSession().getSessionStatus() != SessionStatus.ENCRYPTED) {
 704			Toast.makeText(this, R.string.otr_session_not_started, Toast.LENGTH_LONG).show();
 705			return;
 706		}
 707		if (view == null) {
 708			return;
 709		}
 710		PopupMenu popup = new PopupMenu(this, view);
 711		popup.inflate(R.menu.verification_choices);
 712		popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 713			@Override
 714			public boolean onMenuItemClick(MenuItem menuItem) {
 715				Intent intent = new Intent(ConversationActivity.this, VerifyOTRActivity.class);
 716				intent.setAction(VerifyOTRActivity.ACTION_VERIFY_CONTACT);
 717				intent.putExtra("contact", conversation.getContact().getJid().toBareJid().toString());
 718				intent.putExtra("account", conversation.getAccount().getJid().toBareJid().toString());
 719				switch (menuItem.getItemId()) {
 720					case R.id.scan_fingerprint:
 721						intent.putExtra("mode", VerifyOTRActivity.MODE_SCAN_FINGERPRINT);
 722						break;
 723					case R.id.ask_question:
 724						intent.putExtra("mode", VerifyOTRActivity.MODE_ASK_QUESTION);
 725						break;
 726					case R.id.manual_verification:
 727						intent.putExtra("mode", VerifyOTRActivity.MODE_MANUAL_VERIFICATION);
 728						break;
 729				}
 730				startActivity(intent);
 731				return true;
 732			}
 733		});
 734		popup.show();
 735	}
 736
 737	protected void selectEncryptionDialog(final Conversation conversation) {
 738		View menuItemView = findViewById(R.id.action_security);
 739		if (menuItemView == null) {
 740			return;
 741		}
 742		PopupMenu popup = new PopupMenu(this, menuItemView);
 743		final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
 744			.findFragmentByTag("conversation");
 745		if (fragment != null) {
 746			popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 747
 748				@Override
 749				public boolean onMenuItemClick(MenuItem item) {
 750					switch (item.getItemId()) {
 751						case R.id.encryption_choice_none:
 752							conversation.setNextEncryption(Message.ENCRYPTION_NONE);
 753							item.setChecked(true);
 754							break;
 755						case R.id.encryption_choice_otr:
 756							conversation.setNextEncryption(Message.ENCRYPTION_OTR);
 757							item.setChecked(true);
 758							break;
 759						case R.id.encryption_choice_pgp:
 760							if (hasPgp()) {
 761								if (conversation.getAccount().getKeys().has("pgp_signature")) {
 762									conversation.setNextEncryption(Message.ENCRYPTION_PGP);
 763									item.setChecked(true);
 764								} else {
 765									announcePgp(conversation.getAccount(),conversation);
 766								}
 767							} else {
 768								showInstallPgpDialog();
 769							}
 770							break;
 771						case R.id.encryption_choice_axolotl:
 772							Log.d(Config.LOGTAG, AxolotlService.getLogprefix(conversation.getAccount())
 773									+ "Enabled axolotl for Contact " + conversation.getContact().getJid());
 774							conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
 775							item.setChecked(true);
 776							break;
 777						default:
 778							conversation.setNextEncryption(Message.ENCRYPTION_NONE);
 779							break;
 780					}
 781					xmppConnectionService.databaseBackend.updateConversation(conversation);
 782					fragment.updateChatMsgHint();
 783					invalidateOptionsMenu();
 784					refreshUi();
 785					return true;
 786				}
 787			});
 788			popup.inflate(R.menu.encryption_choices);
 789			MenuItem otr = popup.getMenu().findItem(R.id.encryption_choice_otr);
 790			MenuItem none = popup.getMenu().findItem(R.id.encryption_choice_none);
 791			MenuItem pgp = popup.getMenu().findItem(R.id.encryption_choice_pgp);
 792			MenuItem axolotl = popup.getMenu().findItem(R.id.encryption_choice_axolotl);
 793			pgp.setVisible(!Config.HIDE_PGP_IN_UI);
 794			if (conversation.getMode() == Conversation.MODE_MULTI) {
 795				otr.setVisible(false);
 796				axolotl.setVisible(false);
 797			} else if (!conversation.getAccount().getAxolotlService().isContactAxolotlCapable(conversation.getContact())) {
 798				axolotl.setEnabled(false);
 799			}
 800			switch (conversation.getNextEncryption()) {
 801				case Message.ENCRYPTION_NONE:
 802					none.setChecked(true);
 803					break;
 804				case Message.ENCRYPTION_OTR:
 805					otr.setChecked(true);
 806					break;
 807				case Message.ENCRYPTION_PGP:
 808					pgp.setChecked(true);
 809					break;
 810				case Message.ENCRYPTION_AXOLOTL:
 811					axolotl.setChecked(true);
 812					break;
 813				default:
 814					none.setChecked(true);
 815					break;
 816			}
 817			popup.show();
 818		}
 819	}
 820
 821	protected void muteConversationDialog(final Conversation conversation) {
 822		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 823		builder.setTitle(R.string.disable_notifications);
 824		final int[] durations = getResources().getIntArray(R.array.mute_options_durations);
 825		builder.setItems(R.array.mute_options_descriptions,
 826				new OnClickListener() {
 827
 828					@Override
 829					public void onClick(final DialogInterface dialog, final int which) {
 830						final long till;
 831						if (durations[which] == -1) {
 832							till = Long.MAX_VALUE;
 833						} else {
 834							till = System.currentTimeMillis() + (durations[which] * 1000);
 835						}
 836						conversation.setMutedTill(till);
 837						ConversationActivity.this.xmppConnectionService.databaseBackend
 838								.updateConversation(conversation);
 839						updateConversationList();
 840						ConversationActivity.this.mConversationFragment.updateMessages();
 841						invalidateOptionsMenu();
 842					}
 843				});
 844		builder.create().show();
 845	}
 846
 847	public void unmuteConversation(final Conversation conversation) {
 848		conversation.setMutedTill(0);
 849		this.xmppConnectionService.databaseBackend.updateConversation(conversation);
 850		updateConversationList();
 851		ConversationActivity.this.mConversationFragment.updateMessages();
 852		invalidateOptionsMenu();
 853	}
 854
 855	@Override
 856	public void onBackPressed() {
 857		if (!isConversationsOverviewVisable()) {
 858			showConversationsOverview();
 859		} else {
 860			moveTaskToBack(true);
 861		}
 862	}
 863
 864	@Override
 865	public boolean onKeyUp(int key, KeyEvent event) {
 866		int rotation = getWindowManager().getDefaultDisplay().getRotation();
 867		final int upKey;
 868		final int downKey;
 869		switch(rotation) {
 870			case Surface.ROTATION_90:
 871				upKey = KeyEvent.KEYCODE_DPAD_LEFT;
 872				downKey = KeyEvent.KEYCODE_DPAD_RIGHT;
 873				break;
 874			case Surface.ROTATION_180:
 875				upKey = KeyEvent.KEYCODE_DPAD_DOWN;
 876				downKey = KeyEvent.KEYCODE_DPAD_UP;
 877				break;
 878			case Surface.ROTATION_270:
 879				upKey = KeyEvent.KEYCODE_DPAD_RIGHT;
 880				downKey = KeyEvent.KEYCODE_DPAD_LEFT;
 881				break;
 882			default:
 883				upKey = KeyEvent.KEYCODE_DPAD_UP;
 884				downKey = KeyEvent.KEYCODE_DPAD_DOWN;
 885		}
 886		final boolean modifier = event.isCtrlPressed();
 887		if (modifier && key == KeyEvent.KEYCODE_TAB && isConversationsOverviewHideable()) {
 888			toggleConversationsOverview();
 889			return true;
 890		} else if (modifier && key == downKey) {
 891			if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
 892				showConversationsOverview();;
 893			}
 894			selectDownConversation();
 895			return true;
 896		} else if (modifier && key == upKey) {
 897			if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
 898				showConversationsOverview();;
 899			}
 900			selectUpConversation();
 901			return true;
 902		} else {
 903			return super.onKeyUp(key, event);
 904		}
 905	}
 906
 907	private void toggleConversationsOverview() {
 908		if (isConversationsOverviewVisable()) {
 909			hideConversationsOverview();
 910			if (mConversationFragment != null) {
 911				mConversationFragment.setFocusOnInputField();
 912			}
 913		} else {
 914			showConversationsOverview();
 915		}
 916	}
 917
 918	private void selectUpConversation() {
 919		Log.d(Config.LOGTAG,"select up conversation");
 920		if (this.mSelectedConversation != null) {
 921			int index = this.conversationList.indexOf(this.mSelectedConversation);
 922			if (index > 0) {
 923				int next = index - 1;
 924				this.conversationWasSelectedByKeyboard = true;
 925				setSelectedConversation(this.conversationList.get(next));
 926				this.mConversationFragment.reInit(getSelectedConversation());
 927				if (next > listView.getLastVisiblePosition() -1  || next < listView.getFirstVisiblePosition() + 1) {
 928					this.listView.setSelection(next);
 929				}
 930				openConversation();
 931			}
 932		}
 933	}
 934
 935	private void selectDownConversation() {
 936		Log.d(Config.LOGTAG, "select down conversation");
 937		if (this.mSelectedConversation != null) {
 938			int index = this.conversationList.indexOf(this.mSelectedConversation);
 939			if (index != -1 && index < this.conversationList.size() - 1) {
 940				int next = index + 1;
 941				this.conversationWasSelectedByKeyboard = true;
 942				setSelectedConversation(this.conversationList.get(next));
 943				this.mConversationFragment.reInit(getSelectedConversation());
 944				if (next > listView.getLastVisiblePosition() -1 || next < listView.getFirstVisiblePosition() + 1) {
 945					this.listView.setSelection(next);
 946				}
 947				openConversation();
 948			}
 949		}
 950	}
 951
 952	@Override
 953	protected void onNewIntent(final Intent intent) {
 954		if (xmppConnectionServiceBound) {
 955			if (intent != null && VIEW_CONVERSATION.equals(intent.getType())) {
 956				handleViewConversationIntent(intent);
 957			}
 958		} else {
 959			setIntent(intent);
 960		}
 961	}
 962
 963	@Override
 964	public void onStart() {
 965		super.onStart();
 966		this.mRedirected = false;
 967		if (this.xmppConnectionServiceBound) {
 968			this.onBackendConnected();
 969		}
 970		if (conversationList.size() >= 1) {
 971			this.onConversationUpdate();
 972		}
 973	}
 974
 975	@Override
 976	public void onPause() {
 977		listView.discardUndo();
 978		super.onPause();
 979		this.mActivityPaused = true;
 980		if (this.xmppConnectionServiceBound) {
 981			this.xmppConnectionService.getNotificationService().setIsInForeground(false);
 982		}
 983	}
 984
 985	@Override
 986	public void onResume() {
 987		super.onResume();
 988		final int theme = findTheme();
 989		final boolean usingEnterKey = usingEnterKey();
 990		if (this.mTheme != theme || usingEnterKey != mUsingEnterKey) {
 991			recreate();
 992		}
 993		this.mActivityPaused = false;
 994		if (this.xmppConnectionServiceBound) {
 995			this.xmppConnectionService.getNotificationService().setIsInForeground(true);
 996		}
 997
 998		if (!isConversationsOverviewVisable() || !isConversationsOverviewHideable()) {
 999			sendReadMarkerIfNecessary(getSelectedConversation());
1000		}
1001
1002	}
1003
1004	@Override
1005	public void onSaveInstanceState(final Bundle savedInstanceState) {
1006		Conversation conversation = getSelectedConversation();
1007		if (conversation != null) {
1008			savedInstanceState.putString(STATE_OPEN_CONVERSATION,
1009					conversation.getUuid());
1010		}
1011		savedInstanceState.putBoolean(STATE_PANEL_OPEN,
1012				isConversationsOverviewVisable());
1013		if (this.mPendingImageUris.size() >= 1) {
1014			savedInstanceState.putString(STATE_PENDING_URI, this.mPendingImageUris.get(0).toString());
1015		}
1016		super.onSaveInstanceState(savedInstanceState);
1017	}
1018
1019	@Override
1020	void onBackendConnected() {
1021		this.xmppConnectionService.getNotificationService().setIsInForeground(true);
1022		updateConversationList();
1023
1024		if (mPendingConferenceInvite != null) {
1025			mPendingConferenceInvite.execute(this);
1026			mPendingConferenceInvite = null;
1027		}
1028
1029		if (xmppConnectionService.getAccounts().size() == 0) {
1030			if (!mRedirected) {
1031				this.mRedirected = true;
1032				startActivity(new Intent(this, EditAccountActivity.class));
1033				finish();
1034			}
1035		} else if (conversationList.size() <= 0) {
1036			if (!mRedirected) {
1037				this.mRedirected = true;
1038				Intent intent = new Intent(this, StartConversationActivity.class);
1039				intent.putExtra("init",true);
1040				startActivity(intent);
1041				finish();
1042			}
1043		} else if (getIntent() != null && VIEW_CONVERSATION.equals(getIntent().getType())) {
1044			handleViewConversationIntent(getIntent());
1045		} else if (selectConversationByUuid(mOpenConverstaion)) {
1046			if (mPanelOpen) {
1047				showConversationsOverview();
1048			} else {
1049				if (isConversationsOverviewHideable()) {
1050					openConversation();
1051				}
1052			}
1053			this.mConversationFragment.reInit(getSelectedConversation());
1054			mOpenConverstaion = null;
1055		} else if (getSelectedConversation() == null) {
1056			showConversationsOverview();
1057			mPendingImageUris.clear();
1058			mPendingFileUris.clear();
1059			mPendingGeoUri = null;
1060			setSelectedConversation(conversationList.get(0));
1061			this.mConversationFragment.reInit(getSelectedConversation());
1062		} else {
1063			this.mConversationFragment.messageListAdapter.updatePreferences();
1064			this.mConversationFragment.messagesView.invalidateViews();
1065			this.mConversationFragment.setupIme();
1066		}
1067
1068		if(!forbidProcessingPendings) {
1069			for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1070				Uri foo = i.next();
1071				attachImageToConversation(getSelectedConversation(), foo);
1072			}
1073
1074			for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1075				attachFileToConversation(getSelectedConversation(), i.next());
1076			}
1077
1078			if (mPendingGeoUri != null) {
1079				attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1080				mPendingGeoUri = null;
1081			}
1082		}
1083		forbidProcessingPendings = false;
1084
1085		ExceptionHelper.checkForCrash(this, this.xmppConnectionService);
1086		setIntent(new Intent());
1087	}
1088
1089	private void handleViewConversationIntent(final Intent intent) {
1090		final String uuid = intent.getStringExtra(CONVERSATION);
1091		final String downloadUuid = intent.getStringExtra(MESSAGE);
1092		final String text = intent.getStringExtra(TEXT);
1093		final String nick = intent.getStringExtra(NICK);
1094		final boolean pm = intent.getBooleanExtra(PRIVATE_MESSAGE,false);
1095		if (selectConversationByUuid(uuid)) {
1096			this.mConversationFragment.reInit(getSelectedConversation());
1097			if (nick != null) {
1098				if (pm) {
1099					Jid jid = getSelectedConversation().getJid();
1100					try {
1101						Jid next = Jid.fromParts(jid.getLocalpart(),jid.getDomainpart(),nick);
1102						this.mConversationFragment.privateMessageWith(next);
1103					} catch (final InvalidJidException ignored) {
1104						//do nothing
1105					}
1106				} else {
1107					this.mConversationFragment.highlightInConference(nick);
1108				}
1109			} else {
1110				this.mConversationFragment.appendText(text);
1111			}
1112			hideConversationsOverview();
1113			openConversation();
1114			if (mContentView instanceof SlidingPaneLayout) {
1115				updateActionBarTitle(true); //fixes bug where slp isn't properly closed yet
1116			}
1117			if (downloadUuid != null) {
1118				final Message message = mSelectedConversation.findMessageWithFileAndUuid(downloadUuid);
1119				if (message != null) {
1120					mConversationFragment.messageListAdapter.startDownloadable(message);
1121				}
1122			}
1123		}
1124	}
1125
1126	private boolean selectConversationByUuid(String uuid) {
1127		if (uuid == null) {
1128			return false;
1129		}
1130		for (Conversation aConversationList : conversationList) {
1131			if (aConversationList.getUuid().equals(uuid)) {
1132				setSelectedConversation(aConversationList);
1133				return true;
1134			}
1135		}
1136		return false;
1137	}
1138
1139	@Override
1140	protected void unregisterListeners() {
1141		super.unregisterListeners();
1142		xmppConnectionService.getNotificationService().setOpenConversation(null);
1143	}
1144
1145	@SuppressLint("NewApi")
1146	private static List<Uri> extractUriFromIntent(final Intent intent) {
1147		List<Uri> uris = new ArrayList<>();
1148		Uri uri = intent.getData();
1149		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && uri == null) {
1150			ClipData clipData = intent.getClipData();
1151			for(int i = 0; i < clipData.getItemCount(); ++i) {
1152				uris.add(clipData.getItemAt(i).getUri());
1153			}
1154		} else {
1155			uris.add(uri);
1156		}
1157		return uris;
1158	}
1159
1160	@Override
1161	protected void onActivityResult(int requestCode, int resultCode,
1162			final Intent data) {
1163		super.onActivityResult(requestCode, resultCode, data);
1164		if (resultCode == RESULT_OK) {
1165			if (requestCode == REQUEST_DECRYPT_PGP) {
1166				mConversationFragment.hideSnackbar();
1167				mConversationFragment.updateMessages();
1168			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
1169				mPendingImageUris.clear();
1170				mPendingImageUris.addAll(extractUriFromIntent(data));
1171				if (xmppConnectionServiceBound) {
1172					for(Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1173						attachImageToConversation(getSelectedConversation(),i.next());
1174					}
1175				}
1176			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_FILE || requestCode == ATTACHMENT_CHOICE_RECORD_VOICE) {
1177				mPendingFileUris.clear();
1178				mPendingFileUris.addAll(extractUriFromIntent(data));
1179				if (xmppConnectionServiceBound) {
1180					for(Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1181						attachFileToConversation(getSelectedConversation(), i.next());
1182					}
1183				}
1184			} else if (requestCode == ATTACHMENT_CHOICE_TAKE_PHOTO) {
1185				if (mPendingImageUris.size() == 1) {
1186					Uri uri = mPendingImageUris.get(0);
1187					if (xmppConnectionServiceBound) {
1188						attachImageToConversation(getSelectedConversation(), uri);
1189						mPendingImageUris.clear();
1190					}
1191					Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1192					intent.setData(uri);
1193					sendBroadcast(intent);
1194				} else {
1195					mPendingImageUris.clear();
1196				}
1197			} else if (requestCode == ATTACHMENT_CHOICE_LOCATION) {
1198				double latitude = data.getDoubleExtra("latitude",0);
1199				double longitude = data.getDoubleExtra("longitude",0);
1200				this.mPendingGeoUri = Uri.parse("geo:"+String.valueOf(latitude)+","+String.valueOf(longitude));
1201				if (xmppConnectionServiceBound) {
1202					attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1203					this.mPendingGeoUri = null;
1204				}
1205			} else if (requestCode == REQUEST_TRUST_KEYS_TEXT || requestCode == REQUEST_TRUST_KEYS_MENU) {
1206				this.forbidProcessingPendings = !xmppConnectionServiceBound;
1207				mConversationFragment.onActivityResult(requestCode, resultCode, data);
1208			}
1209		} else {
1210			mPendingImageUris.clear();
1211			mPendingFileUris.clear();
1212		}
1213	}
1214
1215	private void attachLocationToConversation(Conversation conversation, Uri uri) {
1216		if (conversation == null) {
1217			return;
1218		}
1219		xmppConnectionService.attachLocationToConversation(conversation,uri, new UiCallback<Message>() {
1220
1221			@Override
1222			public void success(Message message) {
1223				xmppConnectionService.sendMessage(message);
1224			}
1225
1226			@Override
1227			public void error(int errorCode, Message object) {
1228
1229			}
1230
1231			@Override
1232			public void userInputRequried(PendingIntent pi, Message object) {
1233
1234			}
1235		});
1236	}
1237
1238	private void attachFileToConversation(Conversation conversation, Uri uri) {
1239		if (conversation == null) {
1240			return;
1241		}
1242		prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_file), Toast.LENGTH_LONG);
1243		prepareFileToast.show();
1244		xmppConnectionService.attachFileToConversation(conversation, uri, new UiCallback<Message>() {
1245			@Override
1246			public void success(Message message) {
1247				hidePrepareFileToast();
1248				xmppConnectionService.sendMessage(message);
1249			}
1250
1251			@Override
1252			public void error(int errorCode, Message message) {
1253				displayErrorDialog(errorCode);
1254			}
1255
1256			@Override
1257			public void userInputRequried(PendingIntent pi, Message message) {
1258
1259			}
1260		});
1261	}
1262
1263	private void attachImageToConversation(Conversation conversation, Uri uri) {
1264		if (conversation == null) {
1265			return;
1266		}
1267		prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_image), Toast.LENGTH_LONG);
1268		prepareFileToast.show();
1269		xmppConnectionService.attachImageToConversation(conversation, uri,
1270				new UiCallback<Message>() {
1271
1272					@Override
1273					public void userInputRequried(PendingIntent pi,
1274												  Message object) {
1275						hidePrepareFileToast();
1276					}
1277
1278					@Override
1279					public void success(Message message) {
1280						xmppConnectionService.sendMessage(message);
1281					}
1282
1283					@Override
1284					public void error(int error, Message message) {
1285						hidePrepareFileToast();
1286						displayErrorDialog(error);
1287					}
1288				});
1289	}
1290
1291	private void hidePrepareFileToast() {
1292		if (prepareFileToast != null) {
1293			runOnUiThread(new Runnable() {
1294
1295				@Override
1296				public void run() {
1297					prepareFileToast.cancel();
1298				}
1299			});
1300		}
1301	}
1302
1303	public void updateConversationList() {
1304		xmppConnectionService
1305			.populateWithOrderedConversations(conversationList);
1306		if (swipedConversation != null) {
1307			if (swipedConversation.isRead()) {
1308				conversationList.remove(swipedConversation);
1309			} else {
1310				listView.discardUndo();
1311			}
1312		}
1313		listAdapter.notifyDataSetChanged();
1314	}
1315
1316	public void runIntent(PendingIntent pi, int requestCode) {
1317		try {
1318			this.startIntentSenderForResult(pi.getIntentSender(), requestCode,
1319					null, 0, 0, 0);
1320		} catch (final SendIntentException ignored) {
1321		}
1322	}
1323
1324	public void encryptTextMessage(Message message) {
1325		xmppConnectionService.getPgpEngine().encrypt(message,
1326				new UiCallback<Message>() {
1327
1328					@Override
1329					public void userInputRequried(PendingIntent pi,
1330							Message message) {
1331						ConversationActivity.this.runIntent(pi,
1332								ConversationActivity.REQUEST_SEND_MESSAGE);
1333					}
1334
1335					@Override
1336					public void success(Message message) {
1337						message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1338						xmppConnectionService.sendMessage(message);
1339					}
1340
1341					@Override
1342					public void error(int error, Message message) {
1343
1344					}
1345				});
1346	}
1347
1348	public boolean useSendButtonToIndicateStatus() {
1349		return getPreferences().getBoolean("send_button_status", false);
1350	}
1351
1352	public boolean indicateReceived() {
1353		return getPreferences().getBoolean("indicate_received", false);
1354	}
1355
1356	public boolean useWhiteBackground() {
1357		return getPreferences().getBoolean("use_white_background",false);
1358	}
1359
1360	protected boolean trustKeysIfNeeded(int requestCode) {
1361		return trustKeysIfNeeded(requestCode, ATTACHMENT_CHOICE_INVALID);
1362	}
1363
1364	protected boolean trustKeysIfNeeded(int requestCode, int attachmentChoice) {
1365		AxolotlService axolotlService = mSelectedConversation.getAccount().getAxolotlService();
1366		boolean hasPendingKeys = !axolotlService.getKeysWithTrust(XmppAxolotlSession.Trust.UNDECIDED,
1367				mSelectedConversation.getContact()).isEmpty()
1368				|| !axolotlService.findDevicesWithoutSession(mSelectedConversation).isEmpty();
1369		boolean hasNoTrustedKeys = axolotlService.getNumTrustedKeys(mSelectedConversation.getContact()) == 0;
1370		if( hasPendingKeys || hasNoTrustedKeys) {
1371			axolotlService.createSessionsIfNeeded(mSelectedConversation);
1372			Intent intent = new Intent(getApplicationContext(), TrustKeysActivity.class);
1373			intent.putExtra("contact", mSelectedConversation.getContact().getJid().toBareJid().toString());
1374			intent.putExtra("account", mSelectedConversation.getAccount().getJid().toBareJid().toString());
1375			intent.putExtra("choice", attachmentChoice);
1376			intent.putExtra("has_no_trusted", hasNoTrustedKeys);
1377			startActivityForResult(intent, requestCode);
1378			return true;
1379		} else {
1380			return false;
1381		}
1382	}
1383
1384	@Override
1385	protected void refreshUiReal() {
1386		updateConversationList();
1387		if (xmppConnectionService != null && xmppConnectionService.getAccounts().size() == 0) {
1388			if (!mRedirected) {
1389				this.mRedirected = true;
1390				startActivity(new Intent(this, EditAccountActivity.class));
1391				finish();
1392			}
1393		} else if (conversationList.size() == 0) {
1394			if (!mRedirected) {
1395				this.mRedirected = true;
1396				Intent intent = new Intent(this, StartConversationActivity.class);
1397				intent.putExtra("init",true);
1398				startActivity(intent);
1399				finish();
1400			}
1401		} else {
1402			ConversationActivity.this.mConversationFragment.updateMessages();
1403			updateActionBarTitle();
1404		}
1405		invalidateOptionsMenu();
1406	}
1407
1408	@Override
1409	public void onAccountUpdate() {
1410		this.refreshUi();
1411	}
1412
1413	@Override
1414	public void onConversationUpdate() {
1415		this.refreshUi();
1416	}
1417
1418	@Override
1419	public void onRosterUpdate() {
1420		this.refreshUi();
1421	}
1422
1423	@Override
1424	public void OnUpdateBlocklist(Status status) {
1425		this.refreshUi();
1426	}
1427
1428	public void unblockConversation(final Blockable conversation) {
1429		xmppConnectionService.sendUnblockRequest(conversation);
1430	}
1431
1432	public boolean enterIsSend() {
1433		return getPreferences().getBoolean("enter_is_send",false);
1434	}
1435
1436	@Override
1437	public void onShowErrorToast(final int resId) {
1438		runOnUiThread(new Runnable() {
1439			@Override
1440			public void run() {
1441				Toast.makeText(ConversationActivity.this,resId,Toast.LENGTH_SHORT).show();
1442			}
1443		});
1444	}
1445
1446	public boolean highlightSelectedConversations() {
1447		return !isConversationsOverviewHideable() || this.conversationWasSelectedByKeyboard;
1448	}
1449}