ConversationActivity.java

   1package eu.siacs.conversations.ui;
   2
   3import android.annotation.SuppressLint;
   4import android.support.v7.app.AlertDialog;
   5import android.app.FragmentTransaction;
   6import android.app.PendingIntent;
   7import android.content.ActivityNotFoundException;
   8import android.content.ClipData;
   9import android.content.DialogInterface;
  10import android.content.DialogInterface.OnClickListener;
  11import android.content.Intent;
  12import android.content.IntentSender.SendIntentException;
  13import android.content.pm.PackageManager;
  14import android.net.Uri;
  15import android.os.Build;
  16import android.os.Bundle;
  17import android.os.Handler;
  18import android.provider.MediaStore;
  19import android.provider.Settings;
  20import android.support.v4.widget.SlidingPaneLayout;
  21import android.support.v4.widget.SlidingPaneLayout.PanelSlideListener;
  22import android.support.v7.app.ActionBar;
  23import android.util.Log;
  24import android.util.Pair;
  25import android.view.Gravity;
  26import android.view.KeyEvent;
  27import android.view.Menu;
  28import android.view.MenuItem;
  29import android.view.Surface;
  30import android.view.View;
  31import android.widget.AdapterView;
  32import android.widget.AdapterView.OnItemClickListener;
  33import android.widget.ArrayAdapter;
  34import android.widget.CheckBox;
  35import android.widget.PopupMenu;
  36import android.widget.PopupMenu.OnMenuItemClickListener;
  37import android.widget.Toast;
  38
  39import net.java.otr4j.session.SessionStatus;
  40
  41import org.openintents.openpgp.util.OpenPgpApi;
  42
  43import java.util.ArrayList;
  44import java.util.Iterator;
  45import java.util.List;
  46import java.util.concurrent.atomic.AtomicBoolean;
  47
  48import de.timroes.android.listview.EnhancedListView;
  49import eu.siacs.conversations.Config;
  50import eu.siacs.conversations.R;
  51import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  52import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
  53import eu.siacs.conversations.entities.Account;
  54import eu.siacs.conversations.entities.Blockable;
  55import eu.siacs.conversations.entities.Contact;
  56import eu.siacs.conversations.entities.Conversation;
  57import eu.siacs.conversations.entities.Message;
  58import eu.siacs.conversations.entities.Transferable;
  59import eu.siacs.conversations.persistance.FileBackend;
  60import eu.siacs.conversations.services.XmppConnectionService;
  61import eu.siacs.conversations.services.XmppConnectionService.OnAccountUpdate;
  62import eu.siacs.conversations.services.XmppConnectionService.OnConversationUpdate;
  63import eu.siacs.conversations.services.XmppConnectionService.OnRosterUpdate;
  64import eu.siacs.conversations.ui.adapter.ConversationAdapter;
  65import eu.siacs.conversations.ui.service.EmojiService;
  66import eu.siacs.conversations.utils.ExceptionHelper;
  67import eu.siacs.conversations.utils.UIHelper;
  68import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
  69import eu.siacs.conversations.xmpp.XmppConnection;
  70import eu.siacs.conversations.xmpp.jid.InvalidJidException;
  71import eu.siacs.conversations.xmpp.jid.Jid;
  72
  73public class ConversationActivity extends XmppActivity
  74	implements OnAccountUpdate, OnConversationUpdate, OnRosterUpdate, OnUpdateBlocklist, XmppConnectionService.OnShowErrorToast {
  75
  76	public static final String RECENTLY_USED_QUICK_ACTION = "recently_used_quick_action";
  77
  78	public static final String ACTION_VIEW_CONVERSATION = "eu.siacs.conversations.action.VIEW";
  79	public static final String CONVERSATION = "conversationUuid";
  80	public static final String EXTRA_DOWNLOAD_UUID = "eu.siacs.conversations.download_uuid";
  81	public static final String TEXT = "text";
  82	public static final String NICK = "nick";
  83	public static final String PRIVATE_MESSAGE = "pm";
  84
  85	public static final int REQUEST_SEND_MESSAGE = 0x0201;
  86	public static final int REQUEST_DECRYPT_PGP = 0x0202;
  87	public static final int REQUEST_ENCRYPT_MESSAGE = 0x0207;
  88	public static final int REQUEST_TRUST_KEYS_TEXT = 0x0208;
  89	public static final int REQUEST_TRUST_KEYS_MENU = 0x0209;
  90	public static final int REQUEST_START_DOWNLOAD = 0x0210;
  91	public static final int REQUEST_ADD_EDITOR_CONTENT = 0x0211;
  92	public static final int ATTACHMENT_CHOICE_CHOOSE_IMAGE = 0x0301;
  93	public static final int ATTACHMENT_CHOICE_TAKE_PHOTO = 0x0302;
  94	public static final int ATTACHMENT_CHOICE_CHOOSE_FILE = 0x0303;
  95	public static final int ATTACHMENT_CHOICE_RECORD_VOICE = 0x0304;
  96	public static final int ATTACHMENT_CHOICE_LOCATION = 0x0305;
  97	public static final int ATTACHMENT_CHOICE_INVALID = 0x0306;
  98	public static final int ATTACHMENT_CHOICE_RECORD_VIDEO = 0x0307;
  99	private static final String STATE_OPEN_CONVERSATION = "state_open_conversation";
 100	private static final String STATE_PANEL_OPEN = "state_panel_open";
 101	private static final String STATE_PENDING_URI = "state_pending_uri";
 102	private static final String STATE_FIRST_VISIBLE = "first_visible";
 103	private static final String STATE_OFFSET_FROM_TOP = "offset_from_top";
 104
 105	private String mOpenConversation = null;
 106	private boolean mPanelOpen = true;
 107	private AtomicBoolean mShouldPanelBeOpen = new AtomicBoolean(false);
 108	private Pair<Integer,Integer> mScrollPosition = null;
 109	final private List<Uri> mPendingImageUris = new ArrayList<>();
 110	final private List<Uri> mPendingFileUris = new ArrayList<>();
 111	private Uri mPendingGeoUri = null;
 112	private boolean forbidProcessingPendings = false;
 113	private Message mPendingDownloadableMessage = null;
 114
 115	private boolean conversationWasSelectedByKeyboard = false;
 116
 117	private View mContentView;
 118
 119	private List<Conversation> conversationList = new ArrayList<>();
 120	private Conversation swipedConversation = null;
 121	private Conversation mSelectedConversation = null;
 122	private EnhancedListView listView;
 123	private ConversationFragment mConversationFragment;
 124
 125	private ArrayAdapter<Conversation> listAdapter;
 126
 127	private boolean mActivityPaused = false;
 128	private AtomicBoolean mRedirected = new AtomicBoolean(false);
 129	private Pair<Integer, Intent> mPostponedActivityResult;
 130	private boolean mUnprocessedNewIntent = false;
 131	public Uri mPendingEditorContent = null;
 132
 133	public Conversation getSelectedConversation() {
 134		return this.mSelectedConversation;
 135	}
 136
 137	public void setSelectedConversation(Conversation conversation) {
 138		this.mSelectedConversation = conversation;
 139	}
 140
 141	public void showConversationsOverview() {
 142		if (mConversationFragment != null) {
 143			mConversationFragment.stopScrolling();
 144		}
 145		if (mContentView instanceof SlidingPaneLayout) {
 146			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 147			mShouldPanelBeOpen.set(true);
 148			mSlidingPaneLayout.openPane();
 149		}
 150	}
 151
 152	@Override
 153	protected String getShareableUri() {
 154		Conversation conversation = getSelectedConversation();
 155		if (conversation != null) {
 156			return conversation.getAccount().getShareableUri();
 157		} else {
 158			return "";
 159		}
 160	}
 161
 162	public void hideConversationsOverview() {
 163		if (mContentView instanceof SlidingPaneLayout) {
 164			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 165			mShouldPanelBeOpen.set(false);
 166			mSlidingPaneLayout.closePane();
 167		}
 168	}
 169
 170	public boolean isConversationsOverviewHideable() {
 171		return mContentView instanceof SlidingPaneLayout;
 172	}
 173
 174	public boolean isConversationsOverviewVisable() {
 175		if (mContentView instanceof SlidingPaneLayout) {
 176			return mShouldPanelBeOpen.get();
 177		} else {
 178			return true;
 179		}
 180	}
 181
 182	@Override
 183	protected void onCreate(final Bundle savedInstanceState) {
 184		super.onCreate(savedInstanceState);
 185		new EmojiService(this).init();
 186		if (savedInstanceState != null) {
 187			mOpenConversation = savedInstanceState.getString(STATE_OPEN_CONVERSATION, null);
 188			mPanelOpen = savedInstanceState.getBoolean(STATE_PANEL_OPEN, true);
 189			int pos = savedInstanceState.getInt(STATE_FIRST_VISIBLE, -1);
 190			int offset = savedInstanceState.getInt(STATE_OFFSET_FROM_TOP, 1);
 191			if (pos >= 0 && offset <= 0) {
 192				Log.d(Config.LOGTAG,"retrieved scroll position from instanceState "+pos+":"+offset);
 193				mScrollPosition = new Pair<>(pos,offset);
 194			} else {
 195				mScrollPosition = null;
 196			}
 197			String pending = savedInstanceState.getString(STATE_PENDING_URI, null);
 198			if (pending != null) {
 199				Log.d(Config.LOGTAG,"ConversationsActivity.onCreate() - restoring pending image uri");
 200				mPendingImageUris.clear();
 201				mPendingImageUris.add(Uri.parse(pending));
 202			}
 203		}
 204
 205		setContentView(R.layout.fragment_conversations_overview);
 206
 207		this.mConversationFragment = new ConversationFragment();
 208		FragmentTransaction transaction = getFragmentManager().beginTransaction();
 209		transaction.replace(R.id.selected_conversation, this.mConversationFragment, "conversation");
 210		transaction.commit();
 211
 212		this.listView = findViewById(R.id.list);
 213		this.listAdapter = new ConversationAdapter(this, conversationList);
 214		this.listView.setAdapter(this.listAdapter);
 215		this.listView.setSwipeDirection(EnhancedListView.SwipeDirection.END);
 216
 217		final ActionBar actionBar = getSupportActionBar();
 218		if (actionBar != null) {
 219			actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE);
 220		}
 221
 222		listView.setOnItemClickListener(new OnItemClickListener() {
 223
 224			@Override
 225			public void onItemClick(AdapterView<?> arg0, View clickedView,
 226									int position, long arg3) {
 227				if (getSelectedConversation() != conversationList.get(position)) {
 228					ConversationActivity.this.mConversationFragment.stopScrolling();
 229					setSelectedConversation(conversationList.get(position));
 230					ConversationActivity.this.mConversationFragment.reInit(getSelectedConversation());
 231					conversationWasSelectedByKeyboard = false;
 232				}
 233				hideConversationsOverview();
 234				openConversation();
 235			}
 236		});
 237
 238		listView.setDismissCallback(new EnhancedListView.OnDismissCallback() {
 239
 240			@Override
 241			public EnhancedListView.Undoable onDismiss(final EnhancedListView enhancedListView, final int position) {
 242
 243				final int index = listView.getFirstVisiblePosition();
 244				View v = listView.getChildAt(0);
 245				final int top = (v == null) ? 0 : (v.getTop() - listView.getPaddingTop());
 246
 247				try {
 248					swipedConversation = listAdapter.getItem(position);
 249				} catch (IndexOutOfBoundsException e) {
 250					return null;
 251				}
 252				listAdapter.remove(swipedConversation);
 253				xmppConnectionService.markRead(swipedConversation);
 254
 255				final boolean formerlySelected = (getSelectedConversation() == swipedConversation);
 256				if (position == 0 && listAdapter.getCount() == 0) {
 257					endConversation(swipedConversation, false, true);
 258					return null;
 259				} else if (formerlySelected) {
 260					setSelectedConversation(listAdapter.getItem(0));
 261					ConversationActivity.this.mConversationFragment
 262							.reInit(getSelectedConversation());
 263				}
 264
 265				return new EnhancedListView.Undoable() {
 266
 267					@Override
 268					public void undo() {
 269						listAdapter.insert(swipedConversation, position);
 270						if (formerlySelected) {
 271							setSelectedConversation(swipedConversation);
 272							ConversationActivity.this.mConversationFragment
 273									.reInit(getSelectedConversation());
 274						}
 275						swipedConversation = null;
 276						listView.setSelectionFromTop(index + (listView.getChildCount() < position ? 1 : 0), top);
 277					}
 278
 279					@Override
 280					public void discard() {
 281						if (!swipedConversation.isRead()
 282								&& swipedConversation.getMode() == Conversation.MODE_SINGLE) {
 283							swipedConversation = null;
 284							return;
 285						}
 286						endConversation(swipedConversation, false, false);
 287						swipedConversation = null;
 288					}
 289
 290					@Override
 291					public String getTitle() {
 292						if (swipedConversation.getMode() == Conversation.MODE_MULTI) {
 293							return getResources().getString(R.string.title_undo_swipe_out_muc);
 294						} else {
 295							return getResources().getString(R.string.title_undo_swipe_out_conversation);
 296						}
 297					}
 298				};
 299			}
 300		});
 301		listView.enableSwipeToDismiss();
 302		listView.setSwipingLayout(R.id.swipeable_item);
 303		listView.setUndoStyle(EnhancedListView.UndoStyle.SINGLE_POPUP);
 304		listView.setUndoHideDelay(5000);
 305		listView.setRequireTouchBeforeDismiss(false);
 306
 307		mContentView = findViewById(R.id.content_view_spl);
 308		if (mContentView == null) {
 309			mContentView = findViewById(R.id.content_view_ll);
 310		}
 311		if (mContentView instanceof SlidingPaneLayout) {
 312			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 313			mSlidingPaneLayout.setShadowResource(R.drawable.es_slidingpane_shadow);
 314			mSlidingPaneLayout.setSliderFadeColor(0);
 315			mSlidingPaneLayout.setPanelSlideListener(new PanelSlideListener() {
 316
 317				@Override
 318				public void onPanelOpened(View arg0) {
 319					mShouldPanelBeOpen.set(true);
 320					updateActionBarTitle();
 321					invalidateOptionsMenu();
 322					hideKeyboard();
 323					if (xmppConnectionServiceBound) {
 324						xmppConnectionService.getNotificationService().setOpenConversation(null);
 325					}
 326					closeContextMenu();
 327				}
 328
 329				@Override
 330				public void onPanelClosed(View arg0) {
 331					mShouldPanelBeOpen.set(false);
 332					listView.discardUndo();
 333					openConversation();
 334				}
 335
 336				@Override
 337				public void onPanelSlide(View arg0, float arg1) {
 338					// TODO Auto-generated method stub
 339
 340				}
 341			});
 342		}
 343	}
 344
 345	@Override
 346	public void switchToConversation(Conversation conversation) {
 347		setSelectedConversation(conversation);
 348		runOnUiThread(new Runnable() {
 349			@Override
 350			public void run() {
 351				ConversationActivity.this.mConversationFragment.reInit(getSelectedConversation());
 352				openConversation();
 353			}
 354		});
 355	}
 356
 357	private void updateActionBarTitle() {
 358		updateActionBarTitle(isConversationsOverviewHideable() && !isConversationsOverviewVisable());
 359	}
 360
 361	private void updateActionBarTitle(boolean titleShouldBeName) {
 362		final ActionBar ab = getSupportActionBar();
 363		final Conversation conversation = getSelectedConversation();
 364		if (ab != null) {
 365			if (titleShouldBeName && conversation != null) {
 366				if ((ab.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) != ActionBar.DISPLAY_HOME_AS_UP) {
 367					ab.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_TITLE);
 368				}
 369				if (conversation.getMode() == Conversation.MODE_SINGLE || useSubjectToIdentifyConference()) {
 370					ab.setTitle(conversation.getName());
 371				} else {
 372					ab.setTitle(conversation.getJid().toBareJid().toString());
 373				}
 374			} else {
 375				if ((ab.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) == ActionBar.DISPLAY_HOME_AS_UP) {
 376					ab.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE);
 377				}
 378				ab.setTitle(R.string.app_name);
 379			}
 380		}
 381	}
 382
 383	private void openConversation() {
 384		this.updateActionBarTitle();
 385		this.invalidateOptionsMenu();
 386		if (xmppConnectionServiceBound) {
 387			final Conversation conversation = getSelectedConversation();
 388			xmppConnectionService.getNotificationService().setOpenConversation(conversation);
 389			sendReadMarkerIfNecessary(conversation);
 390		}
 391		listAdapter.notifyDataSetChanged();
 392	}
 393
 394	public void sendReadMarkerIfNecessary(final Conversation conversation) {
 395		if (!mActivityPaused && !mUnprocessedNewIntent && conversation != null) {
 396			xmppConnectionService.sendReadMarker(conversation);
 397		}
 398	}
 399
 400	@Override
 401	public boolean onCreateOptionsMenu(Menu menu) {
 402		getMenuInflater().inflate(R.menu.conversations, menu);
 403		final MenuItem menuSecure = menu.findItem(R.id.action_security);
 404		final MenuItem menuArchive = menu.findItem(R.id.action_archive);
 405		final MenuItem menuMucDetails = menu.findItem(R.id.action_muc_details);
 406		final MenuItem menuContactDetails = menu.findItem(R.id.action_contact_details);
 407		final MenuItem menuAttach = menu.findItem(R.id.action_attach_file);
 408		final MenuItem menuClearHistory = menu.findItem(R.id.action_clear_history);
 409		final MenuItem menuAdd = menu.findItem(R.id.action_add);
 410		final MenuItem menuInviteContact = menu.findItem(R.id.action_invite);
 411		final MenuItem menuMute = menu.findItem(R.id.action_mute);
 412		final MenuItem menuUnmute = menu.findItem(R.id.action_unmute);
 413
 414		if (isConversationsOverviewVisable() && isConversationsOverviewHideable()) {
 415			menuArchive.setVisible(false);
 416			menuMucDetails.setVisible(false);
 417			menuContactDetails.setVisible(false);
 418			menuSecure.setVisible(false);
 419			menuInviteContact.setVisible(false);
 420			menuAttach.setVisible(false);
 421			menuClearHistory.setVisible(false);
 422			menuMute.setVisible(false);
 423			menuUnmute.setVisible(false);
 424		} else {
 425			menuAdd.setVisible(!isConversationsOverviewHideable());
 426			if (this.getSelectedConversation() != null) {
 427				if (this.getSelectedConversation().getNextEncryption() != Message.ENCRYPTION_NONE) {
 428					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
 429						menuSecure.setIcon(R.drawable.ic_lock_white_24dp);
 430					} else {
 431						menuSecure.setIcon(R.drawable.ic_action_secure);
 432					}
 433				}
 434				if (this.getSelectedConversation().getMode() == Conversation.MODE_MULTI) {
 435					menuContactDetails.setVisible(false);
 436					menuAttach.setVisible(getSelectedConversation().getAccount().httpUploadAvailable() && getSelectedConversation().getMucOptions().participating());
 437					menuInviteContact.setVisible(getSelectedConversation().getMucOptions().canInvite());
 438					menuSecure.setVisible((Config.supportOpenPgp() || Config.supportOmemo()) && Config.multipleEncryptionChoices()); //only if pgp is supported we have a choice
 439				} else {
 440					menuContactDetails.setVisible(!this.getSelectedConversation().withSelf());
 441					menuMucDetails.setVisible(false);
 442					menuSecure.setVisible(Config.multipleEncryptionChoices());
 443					menuInviteContact.setVisible(xmppConnectionService != null && xmppConnectionService.findConferenceServer(getSelectedConversation().getAccount()) != null);
 444				}
 445				if (this.getSelectedConversation().isMuted()) {
 446					menuMute.setVisible(false);
 447				} else {
 448					menuUnmute.setVisible(false);
 449				}
 450			}
 451		}
 452		if (Config.supportOmemo()) {
 453			new Handler().post(addOmemoDebuggerRunnable);
 454		}
 455		return super.onCreateOptionsMenu(menu);
 456	}
 457
 458	private Runnable addOmemoDebuggerRunnable = new Runnable() {
 459		@Override
 460		public void run() {
 461			View view = findViewById(R.id.action_security);
 462			if (view != null) {
 463				view.setOnLongClickListener(new View.OnLongClickListener() {
 464					@Override
 465					public boolean onLongClick(View v) {
 466						return v.getId() == R.id.action_security && quickOmemoDebugger(getSelectedConversation());
 467					}
 468				});
 469			}
 470		}
 471	};
 472
 473	private boolean quickOmemoDebugger(Conversation c) {
 474		if (c != null) {
 475			boolean single = c.getMode() == Conversation.MODE_SINGLE;
 476			AxolotlService axolotlService = c.getAccount().getAxolotlService();
 477			Pair<AxolotlService.AxolotlCapability,Jid> capabilityJidPair = axolotlService.isConversationAxolotlCapableDetailed(c);
 478			switch (capabilityJidPair.first) {
 479				case MISSING_PRESENCE:
 480					Toast.makeText(ConversationActivity.this,single ? getString(R.string.missing_presence_subscription) : getString(R.string.missing_presence_subscription_with_x,capabilityJidPair.second.toBareJid().toString()),Toast.LENGTH_SHORT).show();
 481					return true;
 482				case MISSING_KEYS:
 483					Toast.makeText(ConversationActivity.this,single ? getString(R.string.missing_omemo_keys) : getString(R.string.missing_keys_from_x,capabilityJidPair.second.toBareJid().toString()),Toast.LENGTH_SHORT).show();
 484					return true;
 485				case WRONG_CONFIGURATION:
 486					Toast.makeText(ConversationActivity.this,R.string.wrong_conference_configuration, Toast.LENGTH_SHORT).show();
 487					return true;
 488				case NO_MEMBERS:
 489					Toast.makeText(ConversationActivity.this,R.string.this_conference_has_no_members, Toast.LENGTH_SHORT).show();
 490					return true;
 491			}
 492		}
 493		return false;
 494	}
 495
 496	protected void selectPresenceToAttachFile(final int attachmentChoice, final int encryption) {
 497		final Conversation conversation = getSelectedConversation();
 498		final Account account = conversation.getAccount();
 499		final OnPresenceSelected callback = new OnPresenceSelected() {
 500
 501			@Override
 502			public void onPresenceSelected() {
 503				Intent intent = new Intent();
 504				boolean chooser = false;
 505				String fallbackPackageId = null;
 506				switch (attachmentChoice) {
 507					case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
 508						intent.setAction(Intent.ACTION_GET_CONTENT);
 509						if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
 510							intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
 511						}
 512						intent.setType("image/*");
 513						chooser = true;
 514						break;
 515					case ATTACHMENT_CHOICE_RECORD_VIDEO:
 516						intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
 517						break;
 518					case ATTACHMENT_CHOICE_TAKE_PHOTO:
 519						Uri uri = xmppConnectionService.getFileBackend().getTakePhotoUri();
 520						mPendingImageUris.clear();
 521						mPendingImageUris.add(uri);
 522						intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
 523						intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
 524						intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
 525						intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
 526						break;
 527					case ATTACHMENT_CHOICE_CHOOSE_FILE:
 528						chooser = true;
 529						intent.setType("*/*");
 530						intent.addCategory(Intent.CATEGORY_OPENABLE);
 531						intent.setAction(Intent.ACTION_GET_CONTENT);
 532						break;
 533					case ATTACHMENT_CHOICE_RECORD_VOICE:
 534						intent.setAction(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
 535						fallbackPackageId = "eu.siacs.conversations.voicerecorder";
 536						break;
 537					case ATTACHMENT_CHOICE_LOCATION:
 538						intent.setAction("eu.siacs.conversations.location.request");
 539						fallbackPackageId = "eu.siacs.conversations.sharelocation";
 540						break;
 541				}
 542				if (intent.resolveActivity(getPackageManager()) != null) {
 543					if (chooser) {
 544						startActivityForResult(
 545								Intent.createChooser(intent, getString(R.string.perform_action_with)),
 546								attachmentChoice);
 547					} else {
 548						startActivityForResult(intent, attachmentChoice);
 549					}
 550				} else if (fallbackPackageId != null) {
 551					startActivity(getInstallApkIntent(fallbackPackageId));
 552				}
 553			}
 554		};
 555		if ((account.httpUploadAvailable() || attachmentChoice == ATTACHMENT_CHOICE_LOCATION) && encryption != Message.ENCRYPTION_OTR) {
 556			conversation.setNextCounterpart(null);
 557			callback.onPresenceSelected();
 558		} else {
 559			selectPresence(conversation, callback);
 560		}
 561	}
 562
 563	private Intent getInstallApkIntent(final String packageId) {
 564		Intent intent = new Intent(Intent.ACTION_VIEW);
 565		intent.setData(Uri.parse("market://details?id=" + packageId));
 566		if (intent.resolveActivity(getPackageManager()) != null) {
 567			return intent;
 568		} else {
 569			intent.setData(Uri.parse("http://play.google.com/store/apps/details?id=" + packageId));
 570			return intent;
 571		}
 572	}
 573
 574	public void attachFile(final int attachmentChoice) {
 575		if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
 576			if (!Config.ONLY_INTERNAL_STORAGE && !hasStoragePermission(attachmentChoice)) {
 577				return;
 578			}
 579		}
 580		final ConversationFragment.SendButtonAction action;
 581		switch (attachmentChoice) {
 582			case ATTACHMENT_CHOICE_LOCATION:
 583				action = ConversationFragment.SendButtonAction.SEND_LOCATION;
 584				break;
 585			case ATTACHMENT_CHOICE_RECORD_VOICE:
 586				action = ConversationFragment.SendButtonAction.RECORD_VOICE;
 587				break;
 588			case ATTACHMENT_CHOICE_RECORD_VIDEO:
 589				action = ConversationFragment.SendButtonAction.RECORD_VIDEO;
 590				break;
 591			case ATTACHMENT_CHOICE_TAKE_PHOTO:
 592				action = ConversationFragment.SendButtonAction.TAKE_PHOTO;
 593				break;
 594			case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
 595				action = ConversationFragment.SendButtonAction.CHOOSE_PICTURE;
 596				break;
 597			default:
 598				action = null;
 599				break;
 600		}
 601		if (action != null) {
 602			getPreferences().edit().putString(RECENTLY_USED_QUICK_ACTION,action.toString()).apply();
 603		}
 604		final Conversation conversation = getSelectedConversation();
 605		final int encryption = conversation.getNextEncryption();
 606		final int mode = conversation.getMode();
 607		if (encryption == Message.ENCRYPTION_PGP) {
 608			if (hasPgp()) {
 609				if (mode == Conversation.MODE_SINGLE && conversation.getContact().getPgpKeyId() != 0) {
 610					xmppConnectionService.getPgpEngine().hasKey(
 611							conversation.getContact(),
 612							new UiCallback<Contact>() {
 613
 614								@Override
 615								public void userInputRequried(PendingIntent pi, Contact contact) {
 616									ConversationActivity.this.runIntent(pi, attachmentChoice);
 617								}
 618
 619								@Override
 620								public void success(Contact contact) {
 621									selectPresenceToAttachFile(attachmentChoice, encryption);
 622								}
 623
 624								@Override
 625								public void error(int error, Contact contact) {
 626									replaceToast(getString(error));
 627								}
 628							});
 629				} else if (mode == Conversation.MODE_MULTI && conversation.getMucOptions().pgpKeysInUse()) {
 630					if (!conversation.getMucOptions().everybodyHasKeys()) {
 631						Toast warning = Toast
 632								.makeText(this,
 633										R.string.missing_public_keys,
 634										Toast.LENGTH_LONG);
 635						warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
 636						warning.show();
 637					}
 638					selectPresenceToAttachFile(attachmentChoice, encryption);
 639				} else {
 640					final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
 641							.findFragmentByTag("conversation");
 642					if (fragment != null) {
 643						fragment.showNoPGPKeyDialog(false,
 644								new OnClickListener() {
 645
 646									@Override
 647									public void onClick(DialogInterface dialog,
 648														int which) {
 649										conversation.setNextEncryption(Message.ENCRYPTION_NONE);
 650										xmppConnectionService.updateConversation(conversation);
 651										selectPresenceToAttachFile(attachmentChoice, Message.ENCRYPTION_NONE);
 652									}
 653								});
 654					}
 655				}
 656			} else {
 657				showInstallPgpDialog();
 658			}
 659		} else {
 660			if (encryption != Message.ENCRYPTION_AXOLOTL || !trustKeysIfNeeded(REQUEST_TRUST_KEYS_MENU, attachmentChoice)) {
 661				selectPresenceToAttachFile(attachmentChoice, encryption);
 662			}
 663		}
 664	}
 665
 666	@Override
 667	public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
 668		if (grantResults.length > 0)
 669			if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
 670				if (requestCode == REQUEST_START_DOWNLOAD) {
 671					if (this.mPendingDownloadableMessage != null) {
 672						startDownloadable(this.mPendingDownloadableMessage);
 673					}
 674				} else if (requestCode == REQUEST_ADD_EDITOR_CONTENT) {
 675					if (this.mPendingEditorContent != null) {
 676						attachImageToConversation(this.mPendingEditorContent);
 677					}
 678				} else {
 679					attachFile(requestCode);
 680				}
 681			} else {
 682				Toast.makeText(this, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
 683			}
 684	}
 685
 686	public void startDownloadable(Message message) {
 687		if (!Config.ONLY_INTERNAL_STORAGE && !hasStoragePermission(ConversationActivity.REQUEST_START_DOWNLOAD)) {
 688			this.mPendingDownloadableMessage = message;
 689			return;
 690		}
 691		Transferable transferable = message.getTransferable();
 692		if (transferable != null) {
 693			if (!transferable.start()) {
 694				Toast.makeText(this, R.string.not_connected_try_again, Toast.LENGTH_SHORT).show();
 695			}
 696		} else if (message.treatAsDownloadable()) {
 697			xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message, true);
 698		}
 699	}
 700
 701	@Override
 702	public boolean onOptionsItemSelected(final MenuItem item) {
 703		if (item.getItemId() == android.R.id.home) {
 704			showConversationsOverview();
 705			return true;
 706		} else if (item.getItemId() == R.id.action_add) {
 707			startActivity(new Intent(this, StartConversationActivity.class));
 708			return true;
 709		} else if (getSelectedConversation() != null) {
 710			switch (item.getItemId()) {
 711				case R.id.action_attach_file:
 712					attachFileDialog();
 713					break;
 714				case R.id.action_archive:
 715					this.endConversation(getSelectedConversation());
 716					break;
 717				case R.id.action_contact_details:
 718					switchToContactDetails(getSelectedConversation().getContact());
 719					break;
 720				case R.id.action_muc_details:
 721					Intent intent = new Intent(this,
 722							ConferenceDetailsActivity.class);
 723					intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
 724					intent.putExtra("uuid", getSelectedConversation().getUuid());
 725					startActivity(intent);
 726					break;
 727				case R.id.action_invite:
 728					inviteToConversation(getSelectedConversation());
 729					break;
 730				case R.id.action_security:
 731					selectEncryptionDialog(getSelectedConversation());
 732					break;
 733				case R.id.action_clear_history:
 734					clearHistoryDialog(getSelectedConversation());
 735					break;
 736				case R.id.action_mute:
 737					muteConversationDialog(getSelectedConversation());
 738					break;
 739				case R.id.action_unmute:
 740					unmuteConversation(getSelectedConversation());
 741					break;
 742				case R.id.action_block:
 743					BlockContactDialog.show(this, getSelectedConversation());
 744					break;
 745				case R.id.action_unblock:
 746					BlockContactDialog.show(this, getSelectedConversation());
 747					break;
 748				default:
 749					break;
 750			}
 751			return super.onOptionsItemSelected(item);
 752		} else {
 753			return super.onOptionsItemSelected(item);
 754		}
 755	}
 756
 757	public void endConversation(Conversation conversation) {
 758		endConversation(conversation, true, true);
 759	}
 760
 761	public void endConversation(Conversation conversation, boolean showOverview, boolean reinit) {
 762		if (showOverview) {
 763			showConversationsOverview();
 764		}
 765		xmppConnectionService.archiveConversation(conversation);
 766		if (reinit) {
 767			if (conversationList.size() > 0) {
 768				setSelectedConversation(conversationList.get(0));
 769				this.mConversationFragment.reInit(getSelectedConversation());
 770			} else {
 771				setSelectedConversation(null);
 772				if (mRedirected.compareAndSet(false, true)) {
 773					Intent intent = new Intent(this, StartConversationActivity.class);
 774					intent.putExtra("init", true);
 775					startActivity(intent);
 776					finish();
 777				}
 778			}
 779		}
 780	}
 781
 782	@SuppressLint("InflateParams")
 783	protected void clearHistoryDialog(final Conversation conversation) {
 784		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 785		builder.setTitle(getString(R.string.clear_conversation_history));
 786		View dialogView = getLayoutInflater().inflate(
 787				R.layout.dialog_clear_history, null);
 788		final CheckBox endConversationCheckBox = (CheckBox) dialogView
 789				.findViewById(R.id.end_conversation_checkbox);
 790		builder.setView(dialogView);
 791		builder.setNegativeButton(getString(R.string.cancel), null);
 792		builder.setPositiveButton(getString(R.string.delete_messages),
 793				new OnClickListener() {
 794
 795					@Override
 796					public void onClick(DialogInterface dialog, int which) {
 797						ConversationActivity.this.xmppConnectionService.clearConversationHistory(conversation);
 798						if (endConversationCheckBox.isChecked()) {
 799							endConversation(conversation);
 800						} else {
 801							updateConversationList();
 802							ConversationActivity.this.mConversationFragment.updateMessages();
 803						}
 804					}
 805				});
 806		builder.create().show();
 807	}
 808
 809	protected void attachFileDialog() {
 810		View menuAttachFile = findViewById(R.id.action_attach_file);
 811		if (menuAttachFile == null) {
 812			return;
 813		}
 814		PopupMenu attachFilePopup = new PopupMenu(this, menuAttachFile);
 815		attachFilePopup.inflate(R.menu.attachment_choices);
 816		if (new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION).resolveActivity(getPackageManager()) == null) {
 817			attachFilePopup.getMenu().findItem(R.id.attach_record_voice).setVisible(false);
 818		}
 819		if (new Intent("eu.siacs.conversations.location.request").resolveActivity(getPackageManager()) == null) {
 820			attachFilePopup.getMenu().findItem(R.id.attach_location).setVisible(false);
 821		}
 822		attachFilePopup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 823
 824			@Override
 825			public boolean onMenuItemClick(MenuItem item) {
 826				switch (item.getItemId()) {
 827					case R.id.attach_choose_picture:
 828						attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
 829						break;
 830					case R.id.attach_take_picture:
 831						attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
 832						break;
 833					case R.id.attach_record_video:
 834						attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO);
 835						break;
 836					case R.id.attach_choose_file:
 837						attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
 838						break;
 839					case R.id.attach_record_voice:
 840						attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
 841						break;
 842					case R.id.attach_location:
 843						attachFile(ATTACHMENT_CHOICE_LOCATION);
 844						break;
 845				}
 846				return false;
 847			}
 848		});
 849		UIHelper.showIconsInPopup(attachFilePopup);
 850		attachFilePopup.show();
 851	}
 852
 853	public void verifyOtrSessionDialog(final Conversation conversation, View view) {
 854		if (!conversation.hasValidOtrSession() || conversation.getOtrSession().getSessionStatus() != SessionStatus.ENCRYPTED) {
 855			Toast.makeText(this, R.string.otr_session_not_started, Toast.LENGTH_LONG).show();
 856			return;
 857		}
 858		if (view == null) {
 859			return;
 860		}
 861		PopupMenu popup = new PopupMenu(this, view);
 862		popup.inflate(R.menu.verification_choices);
 863		popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 864			@Override
 865			public boolean onMenuItemClick(MenuItem menuItem) {
 866				Intent intent = new Intent(ConversationActivity.this, VerifyOTRActivity.class);
 867				intent.setAction(VerifyOTRActivity.ACTION_VERIFY_CONTACT);
 868				intent.putExtra("contact", conversation.getContact().getJid().toBareJid().toString());
 869				intent.putExtra(EXTRA_ACCOUNT, conversation.getAccount().getJid().toBareJid().toString());
 870				switch (menuItem.getItemId()) {
 871					case R.id.scan_fingerprint:
 872						intent.putExtra("mode", VerifyOTRActivity.MODE_SCAN_FINGERPRINT);
 873						break;
 874					case R.id.ask_question:
 875						intent.putExtra("mode", VerifyOTRActivity.MODE_ASK_QUESTION);
 876						break;
 877					case R.id.manual_verification:
 878						intent.putExtra("mode", VerifyOTRActivity.MODE_MANUAL_VERIFICATION);
 879						break;
 880				}
 881				startActivity(intent);
 882				return true;
 883			}
 884		});
 885		popup.show();
 886	}
 887
 888	protected void selectEncryptionDialog(final Conversation conversation) {
 889		View menuItemView = findViewById(R.id.action_security);
 890		if (menuItemView == null) {
 891			return;
 892		}
 893		PopupMenu popup = new PopupMenu(this, menuItemView);
 894		final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
 895				.findFragmentByTag("conversation");
 896		if (fragment != null) {
 897			popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 898
 899				@Override
 900				public boolean onMenuItemClick(MenuItem item) {
 901					switch (item.getItemId()) {
 902						case R.id.encryption_choice_none:
 903							conversation.setNextEncryption(Message.ENCRYPTION_NONE);
 904							item.setChecked(true);
 905							break;
 906						case R.id.encryption_choice_otr:
 907							conversation.setNextEncryption(Message.ENCRYPTION_OTR);
 908							item.setChecked(true);
 909							break;
 910						case R.id.encryption_choice_pgp:
 911							if (hasPgp()) {
 912								if (conversation.getAccount().getPgpSignature() != null) {
 913									conversation.setNextEncryption(Message.ENCRYPTION_PGP);
 914									item.setChecked(true);
 915								} else {
 916									announcePgp(conversation.getAccount(), conversation,null, onOpenPGPKeyPublished);
 917								}
 918							} else {
 919								showInstallPgpDialog();
 920							}
 921							break;
 922						case R.id.encryption_choice_axolotl:
 923							Log.d(Config.LOGTAG, AxolotlService.getLogprefix(conversation.getAccount())
 924									+ "Enabled axolotl for Contact " + conversation.getContact().getJid());
 925							conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
 926							item.setChecked(true);
 927							break;
 928						default:
 929							conversation.setNextEncryption(Message.ENCRYPTION_NONE);
 930							break;
 931					}
 932					xmppConnectionService.updateConversation(conversation);
 933					fragment.updateChatMsgHint();
 934					invalidateOptionsMenu();
 935					refreshUi();
 936					return true;
 937				}
 938			});
 939			popup.inflate(R.menu.encryption_choices);
 940			MenuItem otr = popup.getMenu().findItem(R.id.encryption_choice_otr);
 941			MenuItem none = popup.getMenu().findItem(R.id.encryption_choice_none);
 942			MenuItem pgp = popup.getMenu().findItem(R.id.encryption_choice_pgp);
 943			MenuItem axolotl = popup.getMenu().findItem(R.id.encryption_choice_axolotl);
 944			pgp.setVisible(Config.supportOpenPgp());
 945			none.setVisible(Config.supportUnencrypted() || conversation.getMode() == Conversation.MODE_MULTI);
 946			otr.setVisible(Config.supportOtr());
 947			axolotl.setVisible(Config.supportOmemo());
 948			if (conversation.getMode() == Conversation.MODE_MULTI) {
 949				otr.setVisible(false);
 950			}
 951			if (!conversation.getAccount().getAxolotlService().isConversationAxolotlCapable(conversation)) {
 952				axolotl.setEnabled(false);
 953			}
 954			switch (conversation.getNextEncryption()) {
 955				case Message.ENCRYPTION_NONE:
 956					none.setChecked(true);
 957					break;
 958				case Message.ENCRYPTION_OTR:
 959					otr.setChecked(true);
 960					break;
 961				case Message.ENCRYPTION_PGP:
 962					pgp.setChecked(true);
 963					break;
 964				case Message.ENCRYPTION_AXOLOTL:
 965					axolotl.setChecked(true);
 966					break;
 967				default:
 968					none.setChecked(true);
 969					break;
 970			}
 971			popup.show();
 972		}
 973	}
 974
 975	protected void muteConversationDialog(final Conversation conversation) {
 976		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 977		builder.setTitle(R.string.disable_notifications);
 978		final int[] durations = getResources().getIntArray(R.array.mute_options_durations);
 979		builder.setItems(R.array.mute_options_descriptions,
 980				new OnClickListener() {
 981
 982					@Override
 983					public void onClick(final DialogInterface dialog, final int which) {
 984						final long till;
 985						if (durations[which] == -1) {
 986							till = Long.MAX_VALUE;
 987						} else {
 988							till = System.currentTimeMillis() + (durations[which] * 1000);
 989						}
 990						conversation.setMutedTill(till);
 991						ConversationActivity.this.xmppConnectionService.updateConversation(conversation);
 992						updateConversationList();
 993						ConversationActivity.this.mConversationFragment.updateMessages();
 994						invalidateOptionsMenu();
 995					}
 996				});
 997		builder.create().show();
 998	}
 999
1000	public void unmuteConversation(final Conversation conversation) {
1001		conversation.setMutedTill(0);
1002		this.xmppConnectionService.updateConversation(conversation);
1003		updateConversationList();
1004		ConversationActivity.this.mConversationFragment.updateMessages();
1005		invalidateOptionsMenu();
1006	}
1007
1008	@Override
1009	public void onBackPressed() {
1010		if (!isConversationsOverviewVisable()) {
1011			showConversationsOverview();
1012		} else {
1013			super.onBackPressed();
1014		}
1015	}
1016
1017	@Override
1018	public boolean onKeyUp(int key, KeyEvent event) {
1019		int rotation = getWindowManager().getDefaultDisplay().getRotation();
1020		final int upKey;
1021		final int downKey;
1022		switch (rotation) {
1023			case Surface.ROTATION_90:
1024				upKey = KeyEvent.KEYCODE_DPAD_LEFT;
1025				downKey = KeyEvent.KEYCODE_DPAD_RIGHT;
1026				break;
1027			case Surface.ROTATION_180:
1028				upKey = KeyEvent.KEYCODE_DPAD_DOWN;
1029				downKey = KeyEvent.KEYCODE_DPAD_UP;
1030				break;
1031			case Surface.ROTATION_270:
1032				upKey = KeyEvent.KEYCODE_DPAD_RIGHT;
1033				downKey = KeyEvent.KEYCODE_DPAD_LEFT;
1034				break;
1035			case Surface.ROTATION_0:
1036			default:
1037				upKey = KeyEvent.KEYCODE_DPAD_UP;
1038				downKey = KeyEvent.KEYCODE_DPAD_DOWN;
1039		}
1040		final boolean modifier = event.isCtrlPressed() || (event.getMetaState() & KeyEvent.META_ALT_LEFT_ON) != 0;
1041		if (modifier && key == KeyEvent.KEYCODE_TAB && isConversationsOverviewHideable()) {
1042			toggleConversationsOverview();
1043			return true;
1044		} else if (modifier && key == KeyEvent.KEYCODE_SPACE) {
1045			startActivity(new Intent(this, StartConversationActivity.class));
1046			return true;
1047		} else if (modifier && key == downKey) {
1048			if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
1049				showConversationsOverview();
1050				;
1051			}
1052			return selectDownConversation();
1053		} else if (modifier && key == upKey) {
1054			if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
1055				showConversationsOverview();
1056			}
1057			return selectUpConversation();
1058		} else if (modifier && key == KeyEvent.KEYCODE_1) {
1059			return openConversationByIndex(0);
1060		} else if (modifier && key == KeyEvent.KEYCODE_2) {
1061			return openConversationByIndex(1);
1062		} else if (modifier && key == KeyEvent.KEYCODE_3) {
1063			return openConversationByIndex(2);
1064		} else if (modifier && key == KeyEvent.KEYCODE_4) {
1065			return openConversationByIndex(3);
1066		} else if (modifier && key == KeyEvent.KEYCODE_5) {
1067			return openConversationByIndex(4);
1068		} else if (modifier && key == KeyEvent.KEYCODE_6) {
1069			return openConversationByIndex(5);
1070		} else if (modifier && key == KeyEvent.KEYCODE_7) {
1071			return openConversationByIndex(6);
1072		} else if (modifier && key == KeyEvent.KEYCODE_8) {
1073			return openConversationByIndex(7);
1074		} else if (modifier && key == KeyEvent.KEYCODE_9) {
1075			return openConversationByIndex(8);
1076		} else if (modifier && key == KeyEvent.KEYCODE_0) {
1077			return openConversationByIndex(9);
1078		} else {
1079			return super.onKeyUp(key, event);
1080		}
1081	}
1082
1083	private void toggleConversationsOverview() {
1084		if (isConversationsOverviewVisable()) {
1085			hideConversationsOverview();
1086			if (mConversationFragment != null) {
1087				mConversationFragment.setFocusOnInputField();
1088			}
1089		} else {
1090			showConversationsOverview();
1091		}
1092	}
1093
1094	private boolean selectUpConversation() {
1095		if (this.mSelectedConversation != null) {
1096			int index = this.conversationList.indexOf(this.mSelectedConversation);
1097			if (index > 0) {
1098				return openConversationByIndex(index - 1);
1099			}
1100		}
1101		return false;
1102	}
1103
1104	private boolean selectDownConversation() {
1105		if (this.mSelectedConversation != null) {
1106			int index = this.conversationList.indexOf(this.mSelectedConversation);
1107			if (index != -1 && index < this.conversationList.size() - 1) {
1108				return openConversationByIndex(index + 1);
1109			}
1110		}
1111		return false;
1112	}
1113
1114	private boolean openConversationByIndex(int index) {
1115		try {
1116			this.conversationWasSelectedByKeyboard = true;
1117			this.mConversationFragment.stopScrolling();
1118			setSelectedConversation(this.conversationList.get(index));
1119			this.mConversationFragment.reInit(getSelectedConversation());
1120			if (index > listView.getLastVisiblePosition() - 1 || index < listView.getFirstVisiblePosition() + 1) {
1121				this.listView.setSelection(index);
1122			}
1123			openConversation();
1124			return true;
1125		} catch (IndexOutOfBoundsException e) {
1126			return false;
1127		}
1128	}
1129
1130	@Override
1131	protected void onNewIntent(final Intent intent) {
1132		if (intent != null && ACTION_VIEW_CONVERSATION.equals(intent.getAction())) {
1133			mOpenConversation = null;
1134			mUnprocessedNewIntent = true;
1135			if (xmppConnectionServiceBound) {
1136				handleViewConversationIntent(intent);
1137				intent.setAction(Intent.ACTION_MAIN);
1138			} else {
1139				setIntent(intent);
1140			}
1141		}
1142	}
1143
1144	@Override
1145	public void onStart() {
1146		super.onStart();
1147		this.mRedirected.set(false);
1148		if (this.xmppConnectionServiceBound) {
1149			this.onBackendConnected();
1150		}
1151		if (conversationList.size() >= 1) {
1152			this.onConversationUpdate();
1153		}
1154	}
1155
1156	@Override
1157	public void onPause() {
1158		listView.discardUndo();
1159		super.onPause();
1160		this.mActivityPaused = true;
1161	}
1162
1163	@Override
1164	public void onResume() {
1165		super.onResume();
1166		final int theme = findTheme();
1167		final boolean usingEnterKey = usingEnterKey();
1168		if (this.mTheme != theme || usingEnterKey != mUsingEnterKey) {
1169			recreate();
1170		}
1171		this.mActivityPaused = false;
1172
1173
1174		if (!isConversationsOverviewVisable() || !isConversationsOverviewHideable()) {
1175			sendReadMarkerIfNecessary(getSelectedConversation());
1176		}
1177
1178	}
1179
1180	@Override
1181	public void onSaveInstanceState(final Bundle savedInstanceState) {
1182		Conversation conversation = getSelectedConversation();
1183		if (conversation != null) {
1184			savedInstanceState.putString(STATE_OPEN_CONVERSATION, conversation.getUuid());
1185			Pair<Integer,Integer> scrollPosition = mConversationFragment.getScrollPosition();
1186			if (scrollPosition != null) {
1187				savedInstanceState.putInt(STATE_FIRST_VISIBLE, scrollPosition.first);
1188				savedInstanceState.putInt(STATE_OFFSET_FROM_TOP, scrollPosition.second);
1189			}
1190		} else {
1191			savedInstanceState.remove(STATE_OPEN_CONVERSATION);
1192		}
1193		savedInstanceState.putBoolean(STATE_PANEL_OPEN, isConversationsOverviewVisable());
1194		if (this.mPendingImageUris.size() >= 1) {
1195			Log.d(Config.LOGTAG,"ConversationsActivity.onSaveInstanceState() - saving pending image uri");
1196			savedInstanceState.putString(STATE_PENDING_URI, this.mPendingImageUris.get(0).toString());
1197		} else {
1198			savedInstanceState.remove(STATE_PENDING_URI);
1199		}
1200		super.onSaveInstanceState(savedInstanceState);
1201	}
1202
1203	private void clearPending() {
1204		mPendingImageUris.clear();
1205		mPendingFileUris.clear();
1206		mPendingGeoUri = null;
1207		mPostponedActivityResult = null;
1208	}
1209
1210	private void redirectToStartConversationActivity(boolean noAnimation) {
1211		Account pendingAccount = xmppConnectionService.getPendingAccount();
1212		if (pendingAccount == null) {
1213			Intent startConversationActivity = new Intent(this, StartConversationActivity.class);
1214			startConversationActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
1215			if (noAnimation) {
1216				startConversationActivity.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
1217			}
1218			startConversationActivity.putExtra("init", true);
1219			startActivity(startConversationActivity);
1220			if (noAnimation) {
1221				overridePendingTransition(0,0);
1222			}
1223		} else {
1224			switchToAccount(pendingAccount, true);
1225		}
1226	}
1227
1228	@Override
1229	void onBackendConnected() {
1230		this.xmppConnectionService.getNotificationService().setIsInForeground(true);
1231		updateConversationList();
1232
1233		if (mPendingConferenceInvite != null) {
1234			if (mPendingConferenceInvite.execute(this)) {
1235				mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
1236				mToast.show();
1237			}
1238			mPendingConferenceInvite = null;
1239		}
1240
1241		final Intent intent = getIntent();
1242
1243		if (xmppConnectionService.getAccounts().size() == 0) {
1244			if (mRedirected.compareAndSet(false, true)) {
1245				if (Config.X509_VERIFICATION) {
1246					Intent redirectionIntent = new Intent(this, ManageAccountActivity.class);
1247					redirectionIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
1248					startActivity(redirectionIntent);
1249					overridePendingTransition(0,0);
1250				} else if (Config.MAGIC_CREATE_DOMAIN != null) {
1251					WelcomeActivity.launch(this);
1252				} else {
1253					Intent editAccount = new Intent(this, EditAccountActivity.class);
1254					editAccount.putExtra("init",true);
1255					editAccount.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
1256					startActivity(editAccount);
1257					overridePendingTransition(0,0);
1258				}
1259			}
1260		} else if (conversationList.size() <= 0) {
1261			if (mRedirected.compareAndSet(false, true)) {
1262				redirectToStartConversationActivity(true);
1263			}
1264		} else if (selectConversationByUuid(mOpenConversation)) {
1265			if (mPanelOpen) {
1266				showConversationsOverview();
1267			} else {
1268				if (isConversationsOverviewHideable()) {
1269					openConversation();
1270					updateActionBarTitle(true);
1271				}
1272			}
1273			if (this.mConversationFragment.reInit(getSelectedConversation())) {
1274				Log.d(Config.LOGTAG,"setting scroll position on fragment");
1275				this.mConversationFragment.setScrollPosition(mScrollPosition);
1276			}
1277			mOpenConversation = null;
1278		} else if (intent != null && ACTION_VIEW_CONVERSATION.equals(intent.getAction())) {
1279			clearPending();
1280			handleViewConversationIntent(intent);
1281			intent.setAction(Intent.ACTION_MAIN);
1282		} else if (getSelectedConversation() == null) {
1283			reInitLatestConversation();
1284		} else {
1285			this.mConversationFragment.messageListAdapter.updatePreferences();
1286			this.mConversationFragment.messagesView.invalidateViews();
1287			this.mConversationFragment.setupIme();
1288		}
1289
1290		if (this.mPostponedActivityResult != null) {
1291			this.onActivityResult(mPostponedActivityResult.first, RESULT_OK, mPostponedActivityResult.second);
1292		}
1293
1294		final boolean stopping = isStopping();
1295
1296		if (!forbidProcessingPendings) {
1297			for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1298				Uri foo = i.next();
1299				Log.d(Config.LOGTAG,"ConversationsActivity.onBackendConnected() - attaching image to conversations. stopping="+Boolean.toString(stopping));
1300				attachImageToConversation(getSelectedConversation(), foo);
1301			}
1302
1303			for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1304				Log.d(Config.LOGTAG,"ConversationsActivity.onBackendConnected() - attaching file to conversations. stopping="+Boolean.toString(stopping));
1305				attachFileToConversation(getSelectedConversation(), i.next());
1306			}
1307
1308			if (mPendingGeoUri != null) {
1309				attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1310				mPendingGeoUri = null;
1311			}
1312		}
1313		forbidProcessingPendings = false;
1314
1315		if (!ExceptionHelper.checkForCrash(this, this.xmppConnectionService) && !mRedirected.get()) {
1316			openBatteryOptimizationDialogIfNeeded();
1317		}
1318		if (isConversationsOverviewVisable() && isConversationsOverviewHideable()) {
1319			xmppConnectionService.getNotificationService().setOpenConversation(null);
1320		} else {
1321			xmppConnectionService.getNotificationService().setOpenConversation(getSelectedConversation());
1322		}
1323	}
1324
1325	private boolean isStopping() {
1326		if (Build.VERSION.SDK_INT >= 17) {
1327			return isFinishing() || isDestroyed();
1328		} else {
1329			return isFinishing();
1330		}
1331	}
1332
1333	private void reInitLatestConversation() {
1334		showConversationsOverview();
1335		clearPending();
1336		setSelectedConversation(conversationList.get(0));
1337		this.mConversationFragment.reInit(getSelectedConversation());
1338	}
1339
1340	private void handleViewConversationIntent(final Intent intent) {
1341		final String uuid = intent.getStringExtra(CONVERSATION);
1342		final String downloadUuid = intent.getStringExtra(EXTRA_DOWNLOAD_UUID);
1343		final String text = intent.getStringExtra(TEXT);
1344		final String nick = intent.getStringExtra(NICK);
1345		final boolean pm = intent.getBooleanExtra(PRIVATE_MESSAGE, false);
1346		this.mConversationFragment.stopScrolling();
1347		if (selectConversationByUuid(uuid)) {
1348			this.mConversationFragment.reInit(getSelectedConversation());
1349			if (nick != null) {
1350				if (pm) {
1351					Jid jid = getSelectedConversation().getJid();
1352					try {
1353						Jid next = Jid.fromParts(jid.getLocalpart(), jid.getDomainpart(), nick);
1354						this.mConversationFragment.privateMessageWith(next);
1355					} catch (final InvalidJidException ignored) {
1356						//do nothing
1357					}
1358				} else {
1359					this.mConversationFragment.highlightInConference(nick);
1360				}
1361			} else {
1362				this.mConversationFragment.appendText(text);
1363			}
1364			hideConversationsOverview();
1365			mUnprocessedNewIntent = false;
1366			openConversation();
1367			if (mContentView instanceof SlidingPaneLayout) {
1368				updateActionBarTitle(true); //fixes bug where slp isn't properly closed yet
1369			}
1370			if (downloadUuid != null) {
1371				final Message message = mSelectedConversation.findMessageWithFileAndUuid(downloadUuid);
1372				if (message != null) {
1373					startDownloadable(message);
1374				}
1375			}
1376		} else {
1377			mUnprocessedNewIntent = false;
1378		}
1379	}
1380
1381	private boolean selectConversationByUuid(String uuid) {
1382		if (uuid == null) {
1383			return false;
1384		}
1385		for (Conversation aConversationList : conversationList) {
1386			if (aConversationList.getUuid().equals(uuid)) {
1387				setSelectedConversation(aConversationList);
1388				return true;
1389			}
1390		}
1391		return false;
1392	}
1393
1394	@Override
1395	protected void unregisterListeners() {
1396		super.unregisterListeners();
1397		xmppConnectionService.getNotificationService().setOpenConversation(null);
1398	}
1399
1400	@SuppressLint("NewApi")
1401	private static List<Uri> extractUriFromIntent(final Intent intent) {
1402		List<Uri> uris = new ArrayList<>();
1403		if (intent == null) {
1404			return uris;
1405		}
1406		Uri uri = intent.getData();
1407		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && uri == null) {
1408			final ClipData clipData = intent.getClipData();
1409			if (clipData != null) {
1410				for (int i = 0; i < clipData.getItemCount(); ++i) {
1411					uris.add(clipData.getItemAt(i).getUri());
1412				}
1413			}
1414		} else {
1415			uris.add(uri);
1416		}
1417		return uris;
1418	}
1419
1420	@Override
1421	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
1422		super.onActivityResult(requestCode, resultCode, data);
1423		if (resultCode == RESULT_OK) {
1424			if (requestCode == REQUEST_DECRYPT_PGP) {
1425				mConversationFragment.onActivityResult(requestCode, resultCode, data);
1426			} else if (requestCode == REQUEST_CHOOSE_PGP_ID) {
1427				// the user chose OpenPGP for encryption and selected his key in the PGP provider
1428				if (xmppConnectionServiceBound) {
1429					if (data.getExtras().containsKey(OpenPgpApi.EXTRA_SIGN_KEY_ID)) {
1430						// associate selected PGP keyId with the account
1431						mSelectedConversation.getAccount().setPgpSignId(data.getExtras().getLong(OpenPgpApi.EXTRA_SIGN_KEY_ID));
1432						// we need to announce the key as described in XEP-027
1433						announcePgp(mSelectedConversation.getAccount(), null, null, onOpenPGPKeyPublished);
1434					} else {
1435						choosePgpSignId(mSelectedConversation.getAccount());
1436					}
1437					this.mPostponedActivityResult = null;
1438				} else {
1439					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1440				}
1441			} else if (requestCode == REQUEST_ANNOUNCE_PGP) {
1442				if (xmppConnectionServiceBound) {
1443					announcePgp(mSelectedConversation.getAccount(), mSelectedConversation,data, onOpenPGPKeyPublished);
1444					this.mPostponedActivityResult = null;
1445				} else {
1446					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1447				}
1448			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
1449				mPendingImageUris.clear();
1450				mPendingImageUris.addAll(extractUriFromIntent(data));
1451				if (xmppConnectionServiceBound) {
1452					for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1453						Log.d(Config.LOGTAG,"ConversationsActivity.onActivityResult() - attaching image to conversations. CHOOSE_IMAGE");
1454						attachImageToConversation(getSelectedConversation(), i.next());
1455					}
1456				}
1457			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_FILE || requestCode == ATTACHMENT_CHOICE_RECORD_VOICE || requestCode == ATTACHMENT_CHOICE_RECORD_VIDEO) {
1458				final List<Uri> uris = extractUriFromIntent(data);
1459				Log.d(Config.LOGTAG,"uris "+uris.toString());
1460				final Conversation c = getSelectedConversation();
1461				final OnPresenceSelected callback = new OnPresenceSelected() {
1462					@Override
1463					public void onPresenceSelected() {
1464						mPendingFileUris.clear();
1465						mPendingFileUris.addAll(uris);
1466						if (xmppConnectionServiceBound) {
1467							for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1468								Log.d(Config.LOGTAG,"ConversationsActivity.onActivityResult() - attaching file to conversations. CHOOSE_FILE/RECORD_VOICE/RECORD_VIDEO");
1469								attachFileToConversation(c, i.next());
1470							}
1471						}
1472					}
1473				};
1474				if (c == null || c.getMode() == Conversation.MODE_MULTI
1475						|| FileBackend.allFilesUnderSize(this, uris, getMaxHttpUploadSize(c))
1476						|| c.getNextEncryption() == Message.ENCRYPTION_OTR) {
1477					callback.onPresenceSelected();
1478				} else {
1479					selectPresence(c, callback);
1480				}
1481			} else if (requestCode == ATTACHMENT_CHOICE_TAKE_PHOTO) {
1482				if (mPendingImageUris.size() == 1) {
1483					Uri uri = FileBackend.getIndexableTakePhotoUri(mPendingImageUris.get(0));
1484					mPendingImageUris.set(0, uri);
1485					if (xmppConnectionServiceBound) {
1486						Log.d(Config.LOGTAG,"ConversationsActivity.onActivityResult() - attaching image to conversations. TAKE_PHOTO");
1487						attachImageToConversation(getSelectedConversation(), uri);
1488						mPendingImageUris.clear();
1489					}
1490					if (!Config.ONLY_INTERNAL_STORAGE) {
1491						Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1492						intent.setData(uri);
1493						sendBroadcast(intent);
1494					}
1495				} else {
1496					mPendingImageUris.clear();
1497				}
1498			} else if (requestCode == ATTACHMENT_CHOICE_LOCATION) {
1499				double latitude = data.getDoubleExtra("latitude", 0);
1500				double longitude = data.getDoubleExtra("longitude", 0);
1501				this.mPendingGeoUri = Uri.parse("geo:" + String.valueOf(latitude) + "," + String.valueOf(longitude));
1502				if (xmppConnectionServiceBound) {
1503					attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1504					this.mPendingGeoUri = null;
1505				}
1506			} else if (requestCode == REQUEST_TRUST_KEYS_TEXT || requestCode == REQUEST_TRUST_KEYS_MENU) {
1507				this.forbidProcessingPendings = true;
1508				if (xmppConnectionServiceBound) {
1509					mConversationFragment.onActivityResult(requestCode, resultCode, data);
1510					this.mPostponedActivityResult = null;
1511				} else {
1512					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1513				}
1514
1515			}
1516		} else {
1517			mPendingImageUris.clear();
1518			mPendingFileUris.clear();
1519			if (requestCode == ConversationActivity.REQUEST_DECRYPT_PGP) {
1520				mConversationFragment.onActivityResult(requestCode, resultCode, data);
1521			}
1522			if (requestCode == REQUEST_BATTERY_OP) {
1523				setNeverAskForBatteryOptimizationsAgain();
1524			}
1525		}
1526	}
1527
1528	private long getMaxHttpUploadSize(Conversation conversation) {
1529		final XmppConnection connection = conversation.getAccount().getXmppConnection();
1530		return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
1531	}
1532
1533	private String getBatteryOptimizationPreferenceKey() {
1534		@SuppressLint("HardwareIds") String device = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
1535		return "show_battery_optimization"+(device == null ? "" : device);
1536	}
1537
1538	private void setNeverAskForBatteryOptimizationsAgain() {
1539		getPreferences().edit().putBoolean(getBatteryOptimizationPreferenceKey(), false).apply();
1540	}
1541
1542	private void openBatteryOptimizationDialogIfNeeded() {
1543		if (hasAccountWithoutPush()
1544				&& isOptimizingBattery()
1545				&& getPreferences().getBoolean(getBatteryOptimizationPreferenceKey(), true)) {
1546			AlertDialog.Builder builder = new AlertDialog.Builder(this);
1547			builder.setTitle(R.string.battery_optimizations_enabled);
1548			builder.setMessage(R.string.battery_optimizations_enabled_dialog);
1549			builder.setPositiveButton(R.string.next, new OnClickListener() {
1550				@Override
1551				public void onClick(DialogInterface dialog, int which) {
1552					Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
1553					Uri uri = Uri.parse("package:" + getPackageName());
1554					intent.setData(uri);
1555					try {
1556						startActivityForResult(intent, REQUEST_BATTERY_OP);
1557					} catch (ActivityNotFoundException e) {
1558						Toast.makeText(ConversationActivity.this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
1559					}
1560				}
1561			});
1562			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1563				builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
1564					@Override
1565					public void onDismiss(DialogInterface dialog) {
1566						setNeverAskForBatteryOptimizationsAgain();
1567					}
1568				});
1569			}
1570			AlertDialog dialog = builder.create();
1571			dialog.setCanceledOnTouchOutside(false);
1572			dialog.show();
1573		}
1574	}
1575
1576	private boolean hasAccountWithoutPush() {
1577		for(Account account : xmppConnectionService.getAccounts()) {
1578			if (account.getStatus() == Account.State.ONLINE && !xmppConnectionService.getPushManagementService().available(account)) {
1579				return true;
1580			}
1581		}
1582		return false;
1583	}
1584
1585	private void attachLocationToConversation(Conversation conversation, Uri uri) {
1586		if (conversation == null) {
1587			return;
1588		}
1589		xmppConnectionService.attachLocationToConversation(conversation,uri, new UiCallback<Message>() {
1590
1591			@Override
1592			public void success(Message message) {
1593				xmppConnectionService.sendMessage(message);
1594			}
1595
1596			@Override
1597			public void error(int errorCode, Message object) {
1598
1599			}
1600
1601			@Override
1602			public void userInputRequried(PendingIntent pi, Message object) {
1603
1604			}
1605		});
1606	}
1607
1608	private void attachFileToConversation(Conversation conversation, Uri uri) {
1609		if (conversation == null) {
1610			return;
1611		}
1612		final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_file), Toast.LENGTH_LONG);
1613		prepareFileToast.show();
1614		delegateUriPermissionsToService(uri);
1615		xmppConnectionService.attachFileToConversation(conversation, uri, new UiInformableCallback<Message>() {
1616			@Override
1617			public void inform(final String text) {
1618				hidePrepareFileToast(prepareFileToast);
1619				runOnUiThread(new Runnable() {
1620					@Override
1621					public void run() {
1622						replaceToast(text);
1623					}
1624				});
1625			}
1626
1627			@Override
1628			public void success(Message message) {
1629				runOnUiThread(new Runnable() {
1630					@Override
1631					public void run() {
1632						hideToast();
1633					}
1634				});
1635				hidePrepareFileToast(prepareFileToast);
1636				xmppConnectionService.sendMessage(message);
1637			}
1638
1639			@Override
1640			public void error(final int errorCode, Message message) {
1641				hidePrepareFileToast(prepareFileToast);
1642				runOnUiThread(new Runnable() {
1643					@Override
1644					public void run() {
1645						replaceToast(getString(errorCode));
1646					}
1647				});
1648
1649			}
1650
1651			@Override
1652			public void userInputRequried(PendingIntent pi, Message message) {
1653				hidePrepareFileToast(prepareFileToast);
1654			}
1655		});
1656	}
1657
1658	public void attachImageToConversation(Uri uri) {
1659		this.attachImageToConversation(getSelectedConversation(), uri);
1660	}
1661
1662	private void attachImageToConversation(Conversation conversation, Uri uri) {
1663		if (conversation == null) {
1664			return;
1665		}
1666		final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_image), Toast.LENGTH_LONG);
1667		prepareFileToast.show();
1668		delegateUriPermissionsToService(uri);
1669		xmppConnectionService.attachImageToConversation(conversation, uri,
1670				new UiCallback<Message>() {
1671
1672					@Override
1673					public void userInputRequried(PendingIntent pi, Message object) {
1674						hidePrepareFileToast(prepareFileToast);
1675					}
1676
1677					@Override
1678					public void success(Message message) {
1679						hidePrepareFileToast(prepareFileToast);
1680						xmppConnectionService.sendMessage(message);
1681					}
1682
1683					@Override
1684					public void error(final int error, Message message) {
1685						hidePrepareFileToast(prepareFileToast);
1686						runOnUiThread(new Runnable() {
1687							@Override
1688							public void run() {
1689								replaceToast(getString(error));
1690							}
1691						});
1692					}
1693				});
1694	}
1695
1696	private void hidePrepareFileToast(final Toast prepareFileToast) {
1697		if (prepareFileToast != null) {
1698			runOnUiThread(new Runnable() {
1699
1700				@Override
1701				public void run() {
1702					prepareFileToast.cancel();
1703				}
1704			});
1705		}
1706	}
1707
1708	public void updateConversationList() {
1709		xmppConnectionService.populateWithOrderedConversations(conversationList);
1710		if (!conversationList.contains(mSelectedConversation)) {
1711			mSelectedConversation = null;
1712		}
1713		if (swipedConversation != null) {
1714			if (swipedConversation.isRead()) {
1715				conversationList.remove(swipedConversation);
1716			} else {
1717				listView.discardUndo();
1718			}
1719		}
1720		listAdapter.notifyDataSetChanged();
1721	}
1722
1723	public void runIntent(PendingIntent pi, int requestCode) {
1724		try {
1725			this.startIntentSenderForResult(pi.getIntentSender(), requestCode,
1726					null, 0, 0, 0);
1727		} catch (final SendIntentException ignored) {
1728		}
1729	}
1730
1731	public void encryptTextMessage(Message message) {
1732		xmppConnectionService.getPgpEngine().encrypt(message,
1733				new UiCallback<Message>() {
1734
1735					@Override
1736					public void userInputRequried(PendingIntent pi,Message message) {
1737						ConversationActivity.this.runIntent(pi,ConversationActivity.REQUEST_SEND_MESSAGE);
1738					}
1739
1740					@Override
1741					public void success(Message message) {
1742						message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1743						xmppConnectionService.sendMessage(message);
1744						runOnUiThread(new Runnable() {
1745							@Override
1746							public void run() {
1747								mConversationFragment.messageSent();
1748							}
1749						});
1750					}
1751
1752					@Override
1753					public void error(final int error, Message message) {
1754						runOnUiThread(new Runnable() {
1755							@Override
1756							public void run() {
1757								mConversationFragment.doneSendingPgpMessage();
1758								Toast.makeText(ConversationActivity.this,
1759										R.string.unable_to_connect_to_keychain,
1760										Toast.LENGTH_SHORT
1761								).show();
1762							}
1763						});
1764
1765					}
1766				});
1767	}
1768
1769	public boolean useSendButtonToIndicateStatus() {
1770		return getPreferences().getBoolean("send_button_status", getResources().getBoolean(R.bool.send_button_status));
1771	}
1772
1773	public boolean indicateReceived() {
1774		return getPreferences().getBoolean("indicate_received", getResources().getBoolean(R.bool.indicate_received));
1775	}
1776
1777	public boolean useGreenBackground() {
1778		return getPreferences().getBoolean("use_green_background",getResources().getBoolean(R.bool.use_green_background));
1779	}
1780
1781	protected boolean trustKeysIfNeeded(int requestCode) {
1782		return trustKeysIfNeeded(requestCode, ATTACHMENT_CHOICE_INVALID);
1783	}
1784
1785	protected boolean trustKeysIfNeeded(int requestCode, int attachmentChoice) {
1786		AxolotlService axolotlService = mSelectedConversation.getAccount().getAxolotlService();
1787		final List<Jid> targets = axolotlService.getCryptoTargets(mSelectedConversation);
1788		boolean hasUnaccepted = !mSelectedConversation.getAcceptedCryptoTargets().containsAll(targets);
1789		boolean hasUndecidedOwn = !axolotlService.getKeysWithTrust(FingerprintStatus.createActiveUndecided()).isEmpty();
1790		boolean hasUndecidedContacts = !axolotlService.getKeysWithTrust(FingerprintStatus.createActiveUndecided(), targets).isEmpty();
1791		boolean hasPendingKeys = !axolotlService.findDevicesWithoutSession(mSelectedConversation).isEmpty();
1792		boolean hasNoTrustedKeys = axolotlService.anyTargetHasNoTrustedKeys(targets);
1793		if(hasUndecidedOwn || hasUndecidedContacts || hasPendingKeys || hasNoTrustedKeys || hasUnaccepted) {
1794			axolotlService.createSessionsIfNeeded(mSelectedConversation);
1795			Intent intent = new Intent(getApplicationContext(), TrustKeysActivity.class);
1796			String[] contacts = new String[targets.size()];
1797			for(int i = 0; i < contacts.length; ++i) {
1798				contacts[i] = targets.get(i).toString();
1799			}
1800			intent.putExtra("contacts", contacts);
1801			intent.putExtra(EXTRA_ACCOUNT, mSelectedConversation.getAccount().getJid().toBareJid().toString());
1802			intent.putExtra("choice", attachmentChoice);
1803			intent.putExtra("conversation",mSelectedConversation.getUuid());
1804			startActivityForResult(intent, requestCode);
1805			return true;
1806		} else {
1807			return false;
1808		}
1809	}
1810
1811	@Override
1812	protected void refreshUiReal() {
1813		updateConversationList();
1814		if (conversationList.size() > 0) {
1815			if (!this.mConversationFragment.isAdded()) {
1816				Log.d(Config.LOGTAG,"fragment NOT added to activity. detached="+Boolean.toString(mConversationFragment.isDetached()));
1817			}
1818			if (getSelectedConversation() == null) {
1819				reInitLatestConversation();
1820			} else {
1821				ConversationActivity.this.mConversationFragment.updateMessages();
1822				updateActionBarTitle();
1823				invalidateOptionsMenu();
1824			}
1825		} else {
1826			if (!isStopping() && mRedirected.compareAndSet(false, true)) {
1827				redirectToStartConversationActivity(false);
1828			}
1829			Log.d(Config.LOGTAG,"not updating conversations fragment because conversations list size was 0");
1830		}
1831	}
1832
1833	@Override
1834	public void onAccountUpdate() {
1835		this.refreshUi();
1836	}
1837
1838	@Override
1839	public void onConversationUpdate() {
1840		this.refreshUi();
1841	}
1842
1843	@Override
1844	public void onRosterUpdate() {
1845		this.refreshUi();
1846	}
1847
1848	@Override
1849	public void OnUpdateBlocklist(Status status) {
1850		this.refreshUi();
1851	}
1852
1853	public void unblockConversation(final Blockable conversation) {
1854		xmppConnectionService.sendUnblockRequest(conversation);
1855	}
1856
1857	public boolean enterIsSend() {
1858		return getPreferences().getBoolean("enter_is_send",getResources().getBoolean(R.bool.enter_is_send));
1859	}
1860
1861	@Override
1862	public void onShowErrorToast(final int resId) {
1863		runOnUiThread(new Runnable() {
1864			@Override
1865			public void run() {
1866				Toast.makeText(ConversationActivity.this,resId,Toast.LENGTH_SHORT).show();
1867			}
1868		});
1869	}
1870
1871	public boolean highlightSelectedConversations() {
1872		return !isConversationsOverviewHideable() || this.conversationWasSelectedByKeyboard;
1873	}
1874}