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					menuSecure.setIcon(R.drawable.ic_lock_white_24dp);
 429				}
 430				if (this.getSelectedConversation().getMode() == Conversation.MODE_MULTI) {
 431					menuContactDetails.setVisible(false);
 432					menuAttach.setVisible(getSelectedConversation().getAccount().httpUploadAvailable() && getSelectedConversation().getMucOptions().participating());
 433					menuInviteContact.setVisible(getSelectedConversation().getMucOptions().canInvite());
 434					menuSecure.setVisible((Config.supportOpenPgp() || Config.supportOmemo()) && Config.multipleEncryptionChoices()); //only if pgp is supported we have a choice
 435				} else {
 436					menuContactDetails.setVisible(!this.getSelectedConversation().withSelf());
 437					menuMucDetails.setVisible(false);
 438					menuSecure.setVisible(Config.multipleEncryptionChoices());
 439					menuInviteContact.setVisible(xmppConnectionService != null && xmppConnectionService.findConferenceServer(getSelectedConversation().getAccount()) != null);
 440				}
 441				if (this.getSelectedConversation().isMuted()) {
 442					menuMute.setVisible(false);
 443				} else {
 444					menuUnmute.setVisible(false);
 445				}
 446			}
 447		}
 448		if (Config.supportOmemo()) {
 449			new Handler().post(addOmemoDebuggerRunnable);
 450		}
 451		return super.onCreateOptionsMenu(menu);
 452	}
 453
 454	private Runnable addOmemoDebuggerRunnable = new Runnable() {
 455		@Override
 456		public void run() {
 457			View view = findViewById(R.id.action_security);
 458			if (view != null) {
 459				view.setOnLongClickListener(new View.OnLongClickListener() {
 460					@Override
 461					public boolean onLongClick(View v) {
 462						return v.getId() == R.id.action_security && quickOmemoDebugger(getSelectedConversation());
 463					}
 464				});
 465			}
 466		}
 467	};
 468
 469	private boolean quickOmemoDebugger(Conversation c) {
 470		if (c != null) {
 471			boolean single = c.getMode() == Conversation.MODE_SINGLE;
 472			AxolotlService axolotlService = c.getAccount().getAxolotlService();
 473			Pair<AxolotlService.AxolotlCapability,Jid> capabilityJidPair = axolotlService.isConversationAxolotlCapableDetailed(c);
 474			switch (capabilityJidPair.first) {
 475				case MISSING_PRESENCE:
 476					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();
 477					return true;
 478				case MISSING_KEYS:
 479					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();
 480					return true;
 481				case WRONG_CONFIGURATION:
 482					Toast.makeText(ConversationActivity.this,R.string.wrong_conference_configuration, Toast.LENGTH_SHORT).show();
 483					return true;
 484				case NO_MEMBERS:
 485					Toast.makeText(ConversationActivity.this,R.string.this_conference_has_no_members, Toast.LENGTH_SHORT).show();
 486					return true;
 487			}
 488		}
 489		return false;
 490	}
 491
 492	protected void selectPresenceToAttachFile(final int attachmentChoice, final int encryption) {
 493		final Conversation conversation = getSelectedConversation();
 494		final Account account = conversation.getAccount();
 495		final OnPresenceSelected callback = new OnPresenceSelected() {
 496
 497			@Override
 498			public void onPresenceSelected() {
 499				Intent intent = new Intent();
 500				boolean chooser = false;
 501				String fallbackPackageId = null;
 502				switch (attachmentChoice) {
 503					case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
 504						intent.setAction(Intent.ACTION_GET_CONTENT);
 505						if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
 506							intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
 507						}
 508						intent.setType("image/*");
 509						chooser = true;
 510						break;
 511					case ATTACHMENT_CHOICE_RECORD_VIDEO:
 512						intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
 513						break;
 514					case ATTACHMENT_CHOICE_TAKE_PHOTO:
 515						Uri uri = xmppConnectionService.getFileBackend().getTakePhotoUri();
 516						mPendingImageUris.clear();
 517						mPendingImageUris.add(uri);
 518						intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
 519						intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
 520						intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
 521						intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
 522						break;
 523					case ATTACHMENT_CHOICE_CHOOSE_FILE:
 524						chooser = true;
 525						intent.setType("*/*");
 526						intent.addCategory(Intent.CATEGORY_OPENABLE);
 527						intent.setAction(Intent.ACTION_GET_CONTENT);
 528						break;
 529					case ATTACHMENT_CHOICE_RECORD_VOICE:
 530						intent.setAction(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
 531						fallbackPackageId = "eu.siacs.conversations.voicerecorder";
 532						break;
 533					case ATTACHMENT_CHOICE_LOCATION:
 534						intent.setAction("eu.siacs.conversations.location.request");
 535						fallbackPackageId = "eu.siacs.conversations.sharelocation";
 536						break;
 537				}
 538				if (intent.resolveActivity(getPackageManager()) != null) {
 539					if (chooser) {
 540						startActivityForResult(
 541								Intent.createChooser(intent, getString(R.string.perform_action_with)),
 542								attachmentChoice);
 543					} else {
 544						startActivityForResult(intent, attachmentChoice);
 545					}
 546				} else if (fallbackPackageId != null) {
 547					startActivity(getInstallApkIntent(fallbackPackageId));
 548				}
 549			}
 550		};
 551		if ((account.httpUploadAvailable() || attachmentChoice == ATTACHMENT_CHOICE_LOCATION) && encryption != Message.ENCRYPTION_OTR) {
 552			conversation.setNextCounterpart(null);
 553			callback.onPresenceSelected();
 554		} else {
 555			selectPresence(conversation, callback);
 556		}
 557	}
 558
 559	private Intent getInstallApkIntent(final String packageId) {
 560		Intent intent = new Intent(Intent.ACTION_VIEW);
 561		intent.setData(Uri.parse("market://details?id=" + packageId));
 562		if (intent.resolveActivity(getPackageManager()) != null) {
 563			return intent;
 564		} else {
 565			intent.setData(Uri.parse("http://play.google.com/store/apps/details?id=" + packageId));
 566			return intent;
 567		}
 568	}
 569
 570	public void attachFile(final int attachmentChoice) {
 571		if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
 572			if (!Config.ONLY_INTERNAL_STORAGE && !hasStoragePermission(attachmentChoice)) {
 573				return;
 574			}
 575		}
 576		final ConversationFragment.SendButtonAction action;
 577		switch (attachmentChoice) {
 578			case ATTACHMENT_CHOICE_LOCATION:
 579				action = ConversationFragment.SendButtonAction.SEND_LOCATION;
 580				break;
 581			case ATTACHMENT_CHOICE_RECORD_VOICE:
 582				action = ConversationFragment.SendButtonAction.RECORD_VOICE;
 583				break;
 584			case ATTACHMENT_CHOICE_RECORD_VIDEO:
 585				action = ConversationFragment.SendButtonAction.RECORD_VIDEO;
 586				break;
 587			case ATTACHMENT_CHOICE_TAKE_PHOTO:
 588				action = ConversationFragment.SendButtonAction.TAKE_PHOTO;
 589				break;
 590			case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
 591				action = ConversationFragment.SendButtonAction.CHOOSE_PICTURE;
 592				break;
 593			default:
 594				action = null;
 595				break;
 596		}
 597		if (action != null) {
 598			getPreferences().edit().putString(RECENTLY_USED_QUICK_ACTION,action.toString()).apply();
 599		}
 600		final Conversation conversation = getSelectedConversation();
 601		final int encryption = conversation.getNextEncryption();
 602		final int mode = conversation.getMode();
 603		if (encryption == Message.ENCRYPTION_PGP) {
 604			if (hasPgp()) {
 605				if (mode == Conversation.MODE_SINGLE && conversation.getContact().getPgpKeyId() != 0) {
 606					xmppConnectionService.getPgpEngine().hasKey(
 607							conversation.getContact(),
 608							new UiCallback<Contact>() {
 609
 610								@Override
 611								public void userInputRequried(PendingIntent pi, Contact contact) {
 612									ConversationActivity.this.runIntent(pi, attachmentChoice);
 613								}
 614
 615								@Override
 616								public void success(Contact contact) {
 617									selectPresenceToAttachFile(attachmentChoice, encryption);
 618								}
 619
 620								@Override
 621								public void error(int error, Contact contact) {
 622									replaceToast(getString(error));
 623								}
 624							});
 625				} else if (mode == Conversation.MODE_MULTI && conversation.getMucOptions().pgpKeysInUse()) {
 626					if (!conversation.getMucOptions().everybodyHasKeys()) {
 627						Toast warning = Toast
 628								.makeText(this,
 629										R.string.missing_public_keys,
 630										Toast.LENGTH_LONG);
 631						warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
 632						warning.show();
 633					}
 634					selectPresenceToAttachFile(attachmentChoice, encryption);
 635				} else {
 636					final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
 637							.findFragmentByTag("conversation");
 638					if (fragment != null) {
 639						fragment.showNoPGPKeyDialog(false,
 640								new OnClickListener() {
 641
 642									@Override
 643									public void onClick(DialogInterface dialog,
 644														int which) {
 645										conversation.setNextEncryption(Message.ENCRYPTION_NONE);
 646										xmppConnectionService.updateConversation(conversation);
 647										selectPresenceToAttachFile(attachmentChoice, Message.ENCRYPTION_NONE);
 648									}
 649								});
 650					}
 651				}
 652			} else {
 653				showInstallPgpDialog();
 654			}
 655		} else {
 656			if (encryption != Message.ENCRYPTION_AXOLOTL || !trustKeysIfNeeded(REQUEST_TRUST_KEYS_MENU, attachmentChoice)) {
 657				selectPresenceToAttachFile(attachmentChoice, encryption);
 658			}
 659		}
 660	}
 661
 662	@Override
 663	public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
 664		if (grantResults.length > 0)
 665			if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
 666				if (requestCode == REQUEST_START_DOWNLOAD) {
 667					if (this.mPendingDownloadableMessage != null) {
 668						startDownloadable(this.mPendingDownloadableMessage);
 669					}
 670				} else if (requestCode == REQUEST_ADD_EDITOR_CONTENT) {
 671					if (this.mPendingEditorContent != null) {
 672						attachImageToConversation(this.mPendingEditorContent);
 673					}
 674				} else {
 675					attachFile(requestCode);
 676				}
 677			} else {
 678				Toast.makeText(this, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
 679			}
 680	}
 681
 682	public void startDownloadable(Message message) {
 683		if (!Config.ONLY_INTERNAL_STORAGE && !hasStoragePermission(ConversationActivity.REQUEST_START_DOWNLOAD)) {
 684			this.mPendingDownloadableMessage = message;
 685			return;
 686		}
 687		Transferable transferable = message.getTransferable();
 688		if (transferable != null) {
 689			if (!transferable.start()) {
 690				Toast.makeText(this, R.string.not_connected_try_again, Toast.LENGTH_SHORT).show();
 691			}
 692		} else if (message.treatAsDownloadable()) {
 693			xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message, true);
 694		}
 695	}
 696
 697	@Override
 698	public boolean onOptionsItemSelected(final MenuItem item) {
 699		if (item.getItemId() == android.R.id.home) {
 700			showConversationsOverview();
 701			return true;
 702		} else if (item.getItemId() == R.id.action_add) {
 703			startActivity(new Intent(this, StartConversationActivity.class));
 704			return true;
 705		} else if (getSelectedConversation() != null) {
 706			switch (item.getItemId()) {
 707				case R.id.action_attach_file:
 708					attachFileDialog();
 709					break;
 710				case R.id.action_archive:
 711					this.endConversation(getSelectedConversation());
 712					break;
 713				case R.id.action_contact_details:
 714					switchToContactDetails(getSelectedConversation().getContact());
 715					break;
 716				case R.id.action_muc_details:
 717					Intent intent = new Intent(this,
 718							ConferenceDetailsActivity.class);
 719					intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
 720					intent.putExtra("uuid", getSelectedConversation().getUuid());
 721					startActivity(intent);
 722					break;
 723				case R.id.action_invite:
 724					inviteToConversation(getSelectedConversation());
 725					break;
 726				case R.id.action_security:
 727					selectEncryptionDialog(getSelectedConversation());
 728					break;
 729				case R.id.action_clear_history:
 730					clearHistoryDialog(getSelectedConversation());
 731					break;
 732				case R.id.action_mute:
 733					muteConversationDialog(getSelectedConversation());
 734					break;
 735				case R.id.action_unmute:
 736					unmuteConversation(getSelectedConversation());
 737					break;
 738				case R.id.action_block:
 739					BlockContactDialog.show(this, getSelectedConversation());
 740					break;
 741				case R.id.action_unblock:
 742					BlockContactDialog.show(this, getSelectedConversation());
 743					break;
 744				default:
 745					break;
 746			}
 747			return super.onOptionsItemSelected(item);
 748		} else {
 749			return super.onOptionsItemSelected(item);
 750		}
 751	}
 752
 753	public void endConversation(Conversation conversation) {
 754		endConversation(conversation, true, true);
 755	}
 756
 757	public void endConversation(Conversation conversation, boolean showOverview, boolean reinit) {
 758		if (showOverview) {
 759			showConversationsOverview();
 760		}
 761		xmppConnectionService.archiveConversation(conversation);
 762		if (reinit) {
 763			if (conversationList.size() > 0) {
 764				setSelectedConversation(conversationList.get(0));
 765				this.mConversationFragment.reInit(getSelectedConversation());
 766			} else {
 767				setSelectedConversation(null);
 768				if (mRedirected.compareAndSet(false, true)) {
 769					Intent intent = new Intent(this, StartConversationActivity.class);
 770					intent.putExtra("init", true);
 771					startActivity(intent);
 772					finish();
 773				}
 774			}
 775		}
 776	}
 777
 778	@SuppressLint("InflateParams")
 779	protected void clearHistoryDialog(final Conversation conversation) {
 780		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 781		builder.setTitle(getString(R.string.clear_conversation_history));
 782		View dialogView = getLayoutInflater().inflate(
 783				R.layout.dialog_clear_history, null);
 784		final CheckBox endConversationCheckBox = (CheckBox) dialogView
 785				.findViewById(R.id.end_conversation_checkbox);
 786		builder.setView(dialogView);
 787		builder.setNegativeButton(getString(R.string.cancel), null);
 788		builder.setPositiveButton(getString(R.string.delete_messages),
 789				new OnClickListener() {
 790
 791					@Override
 792					public void onClick(DialogInterface dialog, int which) {
 793						ConversationActivity.this.xmppConnectionService.clearConversationHistory(conversation);
 794						if (endConversationCheckBox.isChecked()) {
 795							endConversation(conversation);
 796						} else {
 797							updateConversationList();
 798							ConversationActivity.this.mConversationFragment.updateMessages();
 799						}
 800					}
 801				});
 802		builder.create().show();
 803	}
 804
 805	protected void attachFileDialog() {
 806		View menuAttachFile = findViewById(R.id.action_attach_file);
 807		if (menuAttachFile == null) {
 808			return;
 809		}
 810		PopupMenu attachFilePopup = new PopupMenu(this, menuAttachFile);
 811		attachFilePopup.inflate(R.menu.attachment_choices);
 812		if (new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION).resolveActivity(getPackageManager()) == null) {
 813			attachFilePopup.getMenu().findItem(R.id.attach_record_voice).setVisible(false);
 814		}
 815		if (new Intent("eu.siacs.conversations.location.request").resolveActivity(getPackageManager()) == null) {
 816			attachFilePopup.getMenu().findItem(R.id.attach_location).setVisible(false);
 817		}
 818		attachFilePopup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 819
 820			@Override
 821			public boolean onMenuItemClick(MenuItem item) {
 822				switch (item.getItemId()) {
 823					case R.id.attach_choose_picture:
 824						attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
 825						break;
 826					case R.id.attach_take_picture:
 827						attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
 828						break;
 829					case R.id.attach_record_video:
 830						attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO);
 831						break;
 832					case R.id.attach_choose_file:
 833						attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
 834						break;
 835					case R.id.attach_record_voice:
 836						attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
 837						break;
 838					case R.id.attach_location:
 839						attachFile(ATTACHMENT_CHOICE_LOCATION);
 840						break;
 841				}
 842				return false;
 843			}
 844		});
 845		UIHelper.showIconsInPopup(attachFilePopup);
 846		attachFilePopup.show();
 847	}
 848
 849	public void verifyOtrSessionDialog(final Conversation conversation, View view) {
 850		if (!conversation.hasValidOtrSession() || conversation.getOtrSession().getSessionStatus() != SessionStatus.ENCRYPTED) {
 851			Toast.makeText(this, R.string.otr_session_not_started, Toast.LENGTH_LONG).show();
 852			return;
 853		}
 854		if (view == null) {
 855			return;
 856		}
 857		PopupMenu popup = new PopupMenu(this, view);
 858		popup.inflate(R.menu.verification_choices);
 859		popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 860			@Override
 861			public boolean onMenuItemClick(MenuItem menuItem) {
 862				Intent intent = new Intent(ConversationActivity.this, VerifyOTRActivity.class);
 863				intent.setAction(VerifyOTRActivity.ACTION_VERIFY_CONTACT);
 864				intent.putExtra("contact", conversation.getContact().getJid().toBareJid().toString());
 865				intent.putExtra(EXTRA_ACCOUNT, conversation.getAccount().getJid().toBareJid().toString());
 866				switch (menuItem.getItemId()) {
 867					case R.id.scan_fingerprint:
 868						intent.putExtra("mode", VerifyOTRActivity.MODE_SCAN_FINGERPRINT);
 869						break;
 870					case R.id.ask_question:
 871						intent.putExtra("mode", VerifyOTRActivity.MODE_ASK_QUESTION);
 872						break;
 873					case R.id.manual_verification:
 874						intent.putExtra("mode", VerifyOTRActivity.MODE_MANUAL_VERIFICATION);
 875						break;
 876				}
 877				startActivity(intent);
 878				return true;
 879			}
 880		});
 881		popup.show();
 882	}
 883
 884	protected void selectEncryptionDialog(final Conversation conversation) {
 885		View menuItemView = findViewById(R.id.action_security);
 886		if (menuItemView == null) {
 887			return;
 888		}
 889		PopupMenu popup = new PopupMenu(this, menuItemView);
 890		final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
 891				.findFragmentByTag("conversation");
 892		if (fragment != null) {
 893			popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 894
 895				@Override
 896				public boolean onMenuItemClick(MenuItem item) {
 897					switch (item.getItemId()) {
 898						case R.id.encryption_choice_none:
 899							conversation.setNextEncryption(Message.ENCRYPTION_NONE);
 900							item.setChecked(true);
 901							break;
 902						case R.id.encryption_choice_otr:
 903							conversation.setNextEncryption(Message.ENCRYPTION_OTR);
 904							item.setChecked(true);
 905							break;
 906						case R.id.encryption_choice_pgp:
 907							if (hasPgp()) {
 908								if (conversation.getAccount().getPgpSignature() != null) {
 909									conversation.setNextEncryption(Message.ENCRYPTION_PGP);
 910									item.setChecked(true);
 911								} else {
 912									announcePgp(conversation.getAccount(), conversation,null, onOpenPGPKeyPublished);
 913								}
 914							} else {
 915								showInstallPgpDialog();
 916							}
 917							break;
 918						case R.id.encryption_choice_axolotl:
 919							Log.d(Config.LOGTAG, AxolotlService.getLogprefix(conversation.getAccount())
 920									+ "Enabled axolotl for Contact " + conversation.getContact().getJid());
 921							conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
 922							item.setChecked(true);
 923							break;
 924						default:
 925							conversation.setNextEncryption(Message.ENCRYPTION_NONE);
 926							break;
 927					}
 928					xmppConnectionService.updateConversation(conversation);
 929					fragment.updateChatMsgHint();
 930					invalidateOptionsMenu();
 931					refreshUi();
 932					return true;
 933				}
 934			});
 935			popup.inflate(R.menu.encryption_choices);
 936			MenuItem otr = popup.getMenu().findItem(R.id.encryption_choice_otr);
 937			MenuItem none = popup.getMenu().findItem(R.id.encryption_choice_none);
 938			MenuItem pgp = popup.getMenu().findItem(R.id.encryption_choice_pgp);
 939			MenuItem axolotl = popup.getMenu().findItem(R.id.encryption_choice_axolotl);
 940			pgp.setVisible(Config.supportOpenPgp());
 941			none.setVisible(Config.supportUnencrypted() || conversation.getMode() == Conversation.MODE_MULTI);
 942			otr.setVisible(Config.supportOtr());
 943			axolotl.setVisible(Config.supportOmemo());
 944			if (conversation.getMode() == Conversation.MODE_MULTI) {
 945				otr.setVisible(false);
 946			}
 947			if (!conversation.getAccount().getAxolotlService().isConversationAxolotlCapable(conversation)) {
 948				axolotl.setEnabled(false);
 949			}
 950			switch (conversation.getNextEncryption()) {
 951				case Message.ENCRYPTION_NONE:
 952					none.setChecked(true);
 953					break;
 954				case Message.ENCRYPTION_OTR:
 955					otr.setChecked(true);
 956					break;
 957				case Message.ENCRYPTION_PGP:
 958					pgp.setChecked(true);
 959					break;
 960				case Message.ENCRYPTION_AXOLOTL:
 961					axolotl.setChecked(true);
 962					break;
 963				default:
 964					none.setChecked(true);
 965					break;
 966			}
 967			popup.show();
 968		}
 969	}
 970
 971	protected void muteConversationDialog(final Conversation conversation) {
 972		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 973		builder.setTitle(R.string.disable_notifications);
 974		final int[] durations = getResources().getIntArray(R.array.mute_options_durations);
 975		builder.setItems(R.array.mute_options_descriptions,
 976				new OnClickListener() {
 977
 978					@Override
 979					public void onClick(final DialogInterface dialog, final int which) {
 980						final long till;
 981						if (durations[which] == -1) {
 982							till = Long.MAX_VALUE;
 983						} else {
 984							till = System.currentTimeMillis() + (durations[which] * 1000);
 985						}
 986						conversation.setMutedTill(till);
 987						ConversationActivity.this.xmppConnectionService.updateConversation(conversation);
 988						updateConversationList();
 989						ConversationActivity.this.mConversationFragment.updateMessages();
 990						invalidateOptionsMenu();
 991					}
 992				});
 993		builder.create().show();
 994	}
 995
 996	public void unmuteConversation(final Conversation conversation) {
 997		conversation.setMutedTill(0);
 998		this.xmppConnectionService.updateConversation(conversation);
 999		updateConversationList();
1000		ConversationActivity.this.mConversationFragment.updateMessages();
1001		invalidateOptionsMenu();
1002	}
1003
1004	@Override
1005	public void onBackPressed() {
1006		if (!isConversationsOverviewVisable()) {
1007			showConversationsOverview();
1008		} else {
1009			super.onBackPressed();
1010		}
1011	}
1012
1013	@Override
1014	public boolean onKeyUp(int key, KeyEvent event) {
1015		int rotation = getWindowManager().getDefaultDisplay().getRotation();
1016		final int upKey;
1017		final int downKey;
1018		switch (rotation) {
1019			case Surface.ROTATION_90:
1020				upKey = KeyEvent.KEYCODE_DPAD_LEFT;
1021				downKey = KeyEvent.KEYCODE_DPAD_RIGHT;
1022				break;
1023			case Surface.ROTATION_180:
1024				upKey = KeyEvent.KEYCODE_DPAD_DOWN;
1025				downKey = KeyEvent.KEYCODE_DPAD_UP;
1026				break;
1027			case Surface.ROTATION_270:
1028				upKey = KeyEvent.KEYCODE_DPAD_RIGHT;
1029				downKey = KeyEvent.KEYCODE_DPAD_LEFT;
1030				break;
1031			case Surface.ROTATION_0:
1032			default:
1033				upKey = KeyEvent.KEYCODE_DPAD_UP;
1034				downKey = KeyEvent.KEYCODE_DPAD_DOWN;
1035		}
1036		final boolean modifier = event.isCtrlPressed() || (event.getMetaState() & KeyEvent.META_ALT_LEFT_ON) != 0;
1037		if (modifier && key == KeyEvent.KEYCODE_TAB && isConversationsOverviewHideable()) {
1038			toggleConversationsOverview();
1039			return true;
1040		} else if (modifier && key == KeyEvent.KEYCODE_SPACE) {
1041			startActivity(new Intent(this, StartConversationActivity.class));
1042			return true;
1043		} else if (modifier && key == downKey) {
1044			if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
1045				showConversationsOverview();
1046				;
1047			}
1048			return selectDownConversation();
1049		} else if (modifier && key == upKey) {
1050			if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
1051				showConversationsOverview();
1052			}
1053			return selectUpConversation();
1054		} else if (modifier && key == KeyEvent.KEYCODE_1) {
1055			return openConversationByIndex(0);
1056		} else if (modifier && key == KeyEvent.KEYCODE_2) {
1057			return openConversationByIndex(1);
1058		} else if (modifier && key == KeyEvent.KEYCODE_3) {
1059			return openConversationByIndex(2);
1060		} else if (modifier && key == KeyEvent.KEYCODE_4) {
1061			return openConversationByIndex(3);
1062		} else if (modifier && key == KeyEvent.KEYCODE_5) {
1063			return openConversationByIndex(4);
1064		} else if (modifier && key == KeyEvent.KEYCODE_6) {
1065			return openConversationByIndex(5);
1066		} else if (modifier && key == KeyEvent.KEYCODE_7) {
1067			return openConversationByIndex(6);
1068		} else if (modifier && key == KeyEvent.KEYCODE_8) {
1069			return openConversationByIndex(7);
1070		} else if (modifier && key == KeyEvent.KEYCODE_9) {
1071			return openConversationByIndex(8);
1072		} else if (modifier && key == KeyEvent.KEYCODE_0) {
1073			return openConversationByIndex(9);
1074		} else {
1075			return super.onKeyUp(key, event);
1076		}
1077	}
1078
1079	private void toggleConversationsOverview() {
1080		if (isConversationsOverviewVisable()) {
1081			hideConversationsOverview();
1082			if (mConversationFragment != null) {
1083				mConversationFragment.setFocusOnInputField();
1084			}
1085		} else {
1086			showConversationsOverview();
1087		}
1088	}
1089
1090	private boolean selectUpConversation() {
1091		if (this.mSelectedConversation != null) {
1092			int index = this.conversationList.indexOf(this.mSelectedConversation);
1093			if (index > 0) {
1094				return openConversationByIndex(index - 1);
1095			}
1096		}
1097		return false;
1098	}
1099
1100	private boolean selectDownConversation() {
1101		if (this.mSelectedConversation != null) {
1102			int index = this.conversationList.indexOf(this.mSelectedConversation);
1103			if (index != -1 && index < this.conversationList.size() - 1) {
1104				return openConversationByIndex(index + 1);
1105			}
1106		}
1107		return false;
1108	}
1109
1110	private boolean openConversationByIndex(int index) {
1111		try {
1112			this.conversationWasSelectedByKeyboard = true;
1113			this.mConversationFragment.stopScrolling();
1114			setSelectedConversation(this.conversationList.get(index));
1115			this.mConversationFragment.reInit(getSelectedConversation());
1116			if (index > listView.getLastVisiblePosition() - 1 || index < listView.getFirstVisiblePosition() + 1) {
1117				this.listView.setSelection(index);
1118			}
1119			openConversation();
1120			return true;
1121		} catch (IndexOutOfBoundsException e) {
1122			return false;
1123		}
1124	}
1125
1126	@Override
1127	protected void onNewIntent(final Intent intent) {
1128		if (intent != null && ACTION_VIEW_CONVERSATION.equals(intent.getAction())) {
1129			mOpenConversation = null;
1130			mUnprocessedNewIntent = true;
1131			if (xmppConnectionServiceBound) {
1132				handleViewConversationIntent(intent);
1133				intent.setAction(Intent.ACTION_MAIN);
1134			} else {
1135				setIntent(intent);
1136			}
1137		}
1138	}
1139
1140	@Override
1141	public void onStart() {
1142		super.onStart();
1143		this.mRedirected.set(false);
1144		if (this.xmppConnectionServiceBound) {
1145			this.onBackendConnected();
1146		}
1147		if (conversationList.size() >= 1) {
1148			this.onConversationUpdate();
1149		}
1150	}
1151
1152	@Override
1153	public void onPause() {
1154		listView.discardUndo();
1155		super.onPause();
1156		this.mActivityPaused = true;
1157	}
1158
1159	@Override
1160	public void onResume() {
1161		super.onResume();
1162		final int theme = findTheme();
1163		final boolean usingEnterKey = usingEnterKey();
1164		if (this.mTheme != theme || usingEnterKey != mUsingEnterKey) {
1165			recreate();
1166		}
1167		this.mActivityPaused = false;
1168
1169
1170		if (!isConversationsOverviewVisable() || !isConversationsOverviewHideable()) {
1171			sendReadMarkerIfNecessary(getSelectedConversation());
1172		}
1173
1174	}
1175
1176	@Override
1177	public void onSaveInstanceState(final Bundle savedInstanceState) {
1178		Conversation conversation = getSelectedConversation();
1179		if (conversation != null) {
1180			savedInstanceState.putString(STATE_OPEN_CONVERSATION, conversation.getUuid());
1181			Pair<Integer,Integer> scrollPosition = mConversationFragment.getScrollPosition();
1182			if (scrollPosition != null) {
1183				savedInstanceState.putInt(STATE_FIRST_VISIBLE, scrollPosition.first);
1184				savedInstanceState.putInt(STATE_OFFSET_FROM_TOP, scrollPosition.second);
1185			}
1186		} else {
1187			savedInstanceState.remove(STATE_OPEN_CONVERSATION);
1188		}
1189		savedInstanceState.putBoolean(STATE_PANEL_OPEN, isConversationsOverviewVisable());
1190		if (this.mPendingImageUris.size() >= 1) {
1191			Log.d(Config.LOGTAG,"ConversationsActivity.onSaveInstanceState() - saving pending image uri");
1192			savedInstanceState.putString(STATE_PENDING_URI, this.mPendingImageUris.get(0).toString());
1193		} else {
1194			savedInstanceState.remove(STATE_PENDING_URI);
1195		}
1196		super.onSaveInstanceState(savedInstanceState);
1197	}
1198
1199	private void clearPending() {
1200		mPendingImageUris.clear();
1201		mPendingFileUris.clear();
1202		mPendingGeoUri = null;
1203		mPostponedActivityResult = null;
1204	}
1205
1206	private void redirectToStartConversationActivity(boolean noAnimation) {
1207		Account pendingAccount = xmppConnectionService.getPendingAccount();
1208		if (pendingAccount == null) {
1209			Intent startConversationActivity = new Intent(this, StartConversationActivity.class);
1210			startConversationActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
1211			if (noAnimation) {
1212				startConversationActivity.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
1213			}
1214			startConversationActivity.putExtra("init", true);
1215			startActivity(startConversationActivity);
1216			if (noAnimation) {
1217				overridePendingTransition(0,0);
1218			}
1219		} else {
1220			switchToAccount(pendingAccount, true);
1221		}
1222	}
1223
1224	@Override
1225	void onBackendConnected() {
1226		this.xmppConnectionService.getNotificationService().setIsInForeground(true);
1227		updateConversationList();
1228
1229		if (mPendingConferenceInvite != null) {
1230			if (mPendingConferenceInvite.execute(this)) {
1231				mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
1232				mToast.show();
1233			}
1234			mPendingConferenceInvite = null;
1235		}
1236
1237		final Intent intent = getIntent();
1238
1239		if (xmppConnectionService.getAccounts().size() == 0) {
1240			if (mRedirected.compareAndSet(false, true)) {
1241				if (Config.X509_VERIFICATION) {
1242					Intent redirectionIntent = new Intent(this, ManageAccountActivity.class);
1243					redirectionIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
1244					startActivity(redirectionIntent);
1245					overridePendingTransition(0,0);
1246				} else if (Config.MAGIC_CREATE_DOMAIN != null) {
1247					WelcomeActivity.launch(this);
1248				} else {
1249					Intent editAccount = new Intent(this, EditAccountActivity.class);
1250					editAccount.putExtra("init",true);
1251					editAccount.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
1252					startActivity(editAccount);
1253					overridePendingTransition(0,0);
1254				}
1255			}
1256		} else if (conversationList.size() <= 0) {
1257			if (mRedirected.compareAndSet(false, true)) {
1258				redirectToStartConversationActivity(true);
1259			}
1260		} else if (selectConversationByUuid(mOpenConversation)) {
1261			if (mPanelOpen) {
1262				showConversationsOverview();
1263			} else {
1264				if (isConversationsOverviewHideable()) {
1265					openConversation();
1266					updateActionBarTitle(true);
1267				}
1268			}
1269			if (this.mConversationFragment.reInit(getSelectedConversation())) {
1270				Log.d(Config.LOGTAG,"setting scroll position on fragment");
1271				this.mConversationFragment.setScrollPosition(mScrollPosition);
1272			}
1273			mOpenConversation = null;
1274		} else if (intent != null && ACTION_VIEW_CONVERSATION.equals(intent.getAction())) {
1275			clearPending();
1276			handleViewConversationIntent(intent);
1277			intent.setAction(Intent.ACTION_MAIN);
1278		} else if (getSelectedConversation() == null) {
1279			reInitLatestConversation();
1280		} else {
1281			this.mConversationFragment.messageListAdapter.updatePreferences();
1282			this.mConversationFragment.messagesView.invalidateViews();
1283			this.mConversationFragment.setupIme();
1284		}
1285
1286		if (this.mPostponedActivityResult != null) {
1287			this.onActivityResult(mPostponedActivityResult.first, RESULT_OK, mPostponedActivityResult.second);
1288		}
1289
1290		final boolean stopping = isStopping();
1291
1292		if (!forbidProcessingPendings) {
1293			for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1294				Uri foo = i.next();
1295				Log.d(Config.LOGTAG,"ConversationsActivity.onBackendConnected() - attaching image to conversations. stopping="+Boolean.toString(stopping));
1296				attachImageToConversation(getSelectedConversation(), foo);
1297			}
1298
1299			for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1300				Log.d(Config.LOGTAG,"ConversationsActivity.onBackendConnected() - attaching file to conversations. stopping="+Boolean.toString(stopping));
1301				attachFileToConversation(getSelectedConversation(), i.next());
1302			}
1303
1304			if (mPendingGeoUri != null) {
1305				attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1306				mPendingGeoUri = null;
1307			}
1308		}
1309		forbidProcessingPendings = false;
1310
1311		if (!ExceptionHelper.checkForCrash(this, this.xmppConnectionService) && !mRedirected.get()) {
1312			openBatteryOptimizationDialogIfNeeded();
1313		}
1314		if (isConversationsOverviewVisable() && isConversationsOverviewHideable()) {
1315			xmppConnectionService.getNotificationService().setOpenConversation(null);
1316		} else {
1317			xmppConnectionService.getNotificationService().setOpenConversation(getSelectedConversation());
1318		}
1319	}
1320
1321	private boolean isStopping() {
1322		if (Build.VERSION.SDK_INT >= 17) {
1323			return isFinishing() || isDestroyed();
1324		} else {
1325			return isFinishing();
1326		}
1327	}
1328
1329	private void reInitLatestConversation() {
1330		showConversationsOverview();
1331		clearPending();
1332		setSelectedConversation(conversationList.get(0));
1333		this.mConversationFragment.reInit(getSelectedConversation());
1334	}
1335
1336	private void handleViewConversationIntent(final Intent intent) {
1337		final String uuid = intent.getStringExtra(CONVERSATION);
1338		final String downloadUuid = intent.getStringExtra(EXTRA_DOWNLOAD_UUID);
1339		final String text = intent.getStringExtra(TEXT);
1340		final String nick = intent.getStringExtra(NICK);
1341		final boolean pm = intent.getBooleanExtra(PRIVATE_MESSAGE, false);
1342		this.mConversationFragment.stopScrolling();
1343		if (selectConversationByUuid(uuid)) {
1344			this.mConversationFragment.reInit(getSelectedConversation());
1345			if (nick != null) {
1346				if (pm) {
1347					Jid jid = getSelectedConversation().getJid();
1348					try {
1349						Jid next = Jid.fromParts(jid.getLocalpart(), jid.getDomainpart(), nick);
1350						this.mConversationFragment.privateMessageWith(next);
1351					} catch (final InvalidJidException ignored) {
1352						//do nothing
1353					}
1354				} else {
1355					this.mConversationFragment.highlightInConference(nick);
1356				}
1357			} else {
1358				this.mConversationFragment.appendText(text);
1359			}
1360			hideConversationsOverview();
1361			mUnprocessedNewIntent = false;
1362			openConversation();
1363			if (mContentView instanceof SlidingPaneLayout) {
1364				updateActionBarTitle(true); //fixes bug where slp isn't properly closed yet
1365			}
1366			if (downloadUuid != null) {
1367				final Message message = mSelectedConversation.findMessageWithFileAndUuid(downloadUuid);
1368				if (message != null) {
1369					startDownloadable(message);
1370				}
1371			}
1372		} else {
1373			mUnprocessedNewIntent = false;
1374		}
1375	}
1376
1377	private boolean selectConversationByUuid(String uuid) {
1378		if (uuid == null) {
1379			return false;
1380		}
1381		for (Conversation aConversationList : conversationList) {
1382			if (aConversationList.getUuid().equals(uuid)) {
1383				setSelectedConversation(aConversationList);
1384				return true;
1385			}
1386		}
1387		return false;
1388	}
1389
1390	@Override
1391	protected void unregisterListeners() {
1392		super.unregisterListeners();
1393		xmppConnectionService.getNotificationService().setOpenConversation(null);
1394	}
1395
1396	@SuppressLint("NewApi")
1397	private static List<Uri> extractUriFromIntent(final Intent intent) {
1398		List<Uri> uris = new ArrayList<>();
1399		if (intent == null) {
1400			return uris;
1401		}
1402		Uri uri = intent.getData();
1403		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && uri == null) {
1404			final ClipData clipData = intent.getClipData();
1405			if (clipData != null) {
1406				for (int i = 0; i < clipData.getItemCount(); ++i) {
1407					uris.add(clipData.getItemAt(i).getUri());
1408				}
1409			}
1410		} else {
1411			uris.add(uri);
1412		}
1413		return uris;
1414	}
1415
1416	@Override
1417	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
1418		super.onActivityResult(requestCode, resultCode, data);
1419		if (resultCode == RESULT_OK) {
1420			if (requestCode == REQUEST_DECRYPT_PGP) {
1421				mConversationFragment.onActivityResult(requestCode, resultCode, data);
1422			} else if (requestCode == REQUEST_CHOOSE_PGP_ID) {
1423				// the user chose OpenPGP for encryption and selected his key in the PGP provider
1424				if (xmppConnectionServiceBound) {
1425					if (data.getExtras().containsKey(OpenPgpApi.EXTRA_SIGN_KEY_ID)) {
1426						// associate selected PGP keyId with the account
1427						mSelectedConversation.getAccount().setPgpSignId(data.getExtras().getLong(OpenPgpApi.EXTRA_SIGN_KEY_ID));
1428						// we need to announce the key as described in XEP-027
1429						announcePgp(mSelectedConversation.getAccount(), null, null, onOpenPGPKeyPublished);
1430					} else {
1431						choosePgpSignId(mSelectedConversation.getAccount());
1432					}
1433					this.mPostponedActivityResult = null;
1434				} else {
1435					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1436				}
1437			} else if (requestCode == REQUEST_ANNOUNCE_PGP) {
1438				if (xmppConnectionServiceBound) {
1439					announcePgp(mSelectedConversation.getAccount(), mSelectedConversation,data, onOpenPGPKeyPublished);
1440					this.mPostponedActivityResult = null;
1441				} else {
1442					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1443				}
1444			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
1445				mPendingImageUris.clear();
1446				mPendingImageUris.addAll(extractUriFromIntent(data));
1447				if (xmppConnectionServiceBound) {
1448					for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1449						Log.d(Config.LOGTAG,"ConversationsActivity.onActivityResult() - attaching image to conversations. CHOOSE_IMAGE");
1450						attachImageToConversation(getSelectedConversation(), i.next());
1451					}
1452				}
1453			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_FILE || requestCode == ATTACHMENT_CHOICE_RECORD_VOICE || requestCode == ATTACHMENT_CHOICE_RECORD_VIDEO) {
1454				final List<Uri> uris = extractUriFromIntent(data);
1455				Log.d(Config.LOGTAG,"uris "+uris.toString());
1456				final Conversation c = getSelectedConversation();
1457				final OnPresenceSelected callback = new OnPresenceSelected() {
1458					@Override
1459					public void onPresenceSelected() {
1460						mPendingFileUris.clear();
1461						mPendingFileUris.addAll(uris);
1462						if (xmppConnectionServiceBound) {
1463							for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1464								Log.d(Config.LOGTAG,"ConversationsActivity.onActivityResult() - attaching file to conversations. CHOOSE_FILE/RECORD_VOICE/RECORD_VIDEO");
1465								attachFileToConversation(c, i.next());
1466							}
1467						}
1468					}
1469				};
1470				if (c == null || c.getMode() == Conversation.MODE_MULTI
1471						|| FileBackend.allFilesUnderSize(this, uris, getMaxHttpUploadSize(c))
1472						|| c.getNextEncryption() == Message.ENCRYPTION_OTR) {
1473					callback.onPresenceSelected();
1474				} else {
1475					selectPresence(c, callback);
1476				}
1477			} else if (requestCode == ATTACHMENT_CHOICE_TAKE_PHOTO) {
1478				if (mPendingImageUris.size() == 1) {
1479					Uri uri = FileBackend.getIndexableTakePhotoUri(mPendingImageUris.get(0));
1480					mPendingImageUris.set(0, uri);
1481					if (xmppConnectionServiceBound) {
1482						Log.d(Config.LOGTAG,"ConversationsActivity.onActivityResult() - attaching image to conversations. TAKE_PHOTO");
1483						attachImageToConversation(getSelectedConversation(), uri);
1484						mPendingImageUris.clear();
1485					}
1486					if (!Config.ONLY_INTERNAL_STORAGE) {
1487						Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1488						intent.setData(uri);
1489						sendBroadcast(intent);
1490					}
1491				} else {
1492					mPendingImageUris.clear();
1493				}
1494			} else if (requestCode == ATTACHMENT_CHOICE_LOCATION) {
1495				double latitude = data.getDoubleExtra("latitude", 0);
1496				double longitude = data.getDoubleExtra("longitude", 0);
1497				this.mPendingGeoUri = Uri.parse("geo:" + String.valueOf(latitude) + "," + String.valueOf(longitude));
1498				if (xmppConnectionServiceBound) {
1499					attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1500					this.mPendingGeoUri = null;
1501				}
1502			} else if (requestCode == REQUEST_TRUST_KEYS_TEXT || requestCode == REQUEST_TRUST_KEYS_MENU) {
1503				this.forbidProcessingPendings = true;
1504				if (xmppConnectionServiceBound) {
1505					mConversationFragment.onActivityResult(requestCode, resultCode, data);
1506					this.mPostponedActivityResult = null;
1507				} else {
1508					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1509				}
1510
1511			}
1512		} else {
1513			mPendingImageUris.clear();
1514			mPendingFileUris.clear();
1515			if (requestCode == ConversationActivity.REQUEST_DECRYPT_PGP) {
1516				mConversationFragment.onActivityResult(requestCode, resultCode, data);
1517			}
1518			if (requestCode == REQUEST_BATTERY_OP) {
1519				setNeverAskForBatteryOptimizationsAgain();
1520			}
1521		}
1522	}
1523
1524	private long getMaxHttpUploadSize(Conversation conversation) {
1525		final XmppConnection connection = conversation.getAccount().getXmppConnection();
1526		return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
1527	}
1528
1529	private String getBatteryOptimizationPreferenceKey() {
1530		@SuppressLint("HardwareIds") String device = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
1531		return "show_battery_optimization"+(device == null ? "" : device);
1532	}
1533
1534	private void setNeverAskForBatteryOptimizationsAgain() {
1535		getPreferences().edit().putBoolean(getBatteryOptimizationPreferenceKey(), false).apply();
1536	}
1537
1538	private void openBatteryOptimizationDialogIfNeeded() {
1539		if (hasAccountWithoutPush()
1540				&& isOptimizingBattery()
1541				&& getPreferences().getBoolean(getBatteryOptimizationPreferenceKey(), true)) {
1542			AlertDialog.Builder builder = new AlertDialog.Builder(this);
1543			builder.setTitle(R.string.battery_optimizations_enabled);
1544			builder.setMessage(R.string.battery_optimizations_enabled_dialog);
1545			builder.setPositiveButton(R.string.next, new OnClickListener() {
1546				@Override
1547				public void onClick(DialogInterface dialog, int which) {
1548					Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
1549					Uri uri = Uri.parse("package:" + getPackageName());
1550					intent.setData(uri);
1551					try {
1552						startActivityForResult(intent, REQUEST_BATTERY_OP);
1553					} catch (ActivityNotFoundException e) {
1554						Toast.makeText(ConversationActivity.this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
1555					}
1556				}
1557			});
1558			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1559				builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
1560					@Override
1561					public void onDismiss(DialogInterface dialog) {
1562						setNeverAskForBatteryOptimizationsAgain();
1563					}
1564				});
1565			}
1566			AlertDialog dialog = builder.create();
1567			dialog.setCanceledOnTouchOutside(false);
1568			dialog.show();
1569		}
1570	}
1571
1572	private boolean hasAccountWithoutPush() {
1573		for(Account account : xmppConnectionService.getAccounts()) {
1574			if (account.getStatus() == Account.State.ONLINE && !xmppConnectionService.getPushManagementService().available(account)) {
1575				return true;
1576			}
1577		}
1578		return false;
1579	}
1580
1581	private void attachLocationToConversation(Conversation conversation, Uri uri) {
1582		if (conversation == null) {
1583			return;
1584		}
1585		xmppConnectionService.attachLocationToConversation(conversation,uri, new UiCallback<Message>() {
1586
1587			@Override
1588			public void success(Message message) {
1589				xmppConnectionService.sendMessage(message);
1590			}
1591
1592			@Override
1593			public void error(int errorCode, Message object) {
1594
1595			}
1596
1597			@Override
1598			public void userInputRequried(PendingIntent pi, Message object) {
1599
1600			}
1601		});
1602	}
1603
1604	private void attachFileToConversation(Conversation conversation, Uri uri) {
1605		if (conversation == null) {
1606			return;
1607		}
1608		final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_file), Toast.LENGTH_LONG);
1609		prepareFileToast.show();
1610		delegateUriPermissionsToService(uri);
1611		xmppConnectionService.attachFileToConversation(conversation, uri, new UiInformableCallback<Message>() {
1612			@Override
1613			public void inform(final String text) {
1614				hidePrepareFileToast(prepareFileToast);
1615				runOnUiThread(new Runnable() {
1616					@Override
1617					public void run() {
1618						replaceToast(text);
1619					}
1620				});
1621			}
1622
1623			@Override
1624			public void success(Message message) {
1625				runOnUiThread(new Runnable() {
1626					@Override
1627					public void run() {
1628						hideToast();
1629					}
1630				});
1631				hidePrepareFileToast(prepareFileToast);
1632				xmppConnectionService.sendMessage(message);
1633			}
1634
1635			@Override
1636			public void error(final int errorCode, Message message) {
1637				hidePrepareFileToast(prepareFileToast);
1638				runOnUiThread(new Runnable() {
1639					@Override
1640					public void run() {
1641						replaceToast(getString(errorCode));
1642					}
1643				});
1644
1645			}
1646
1647			@Override
1648			public void userInputRequried(PendingIntent pi, Message message) {
1649				hidePrepareFileToast(prepareFileToast);
1650			}
1651		});
1652	}
1653
1654	public void attachImageToConversation(Uri uri) {
1655		this.attachImageToConversation(getSelectedConversation(), uri);
1656	}
1657
1658	private void attachImageToConversation(Conversation conversation, Uri uri) {
1659		if (conversation == null) {
1660			return;
1661		}
1662		final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_image), Toast.LENGTH_LONG);
1663		prepareFileToast.show();
1664		delegateUriPermissionsToService(uri);
1665		xmppConnectionService.attachImageToConversation(conversation, uri,
1666				new UiCallback<Message>() {
1667
1668					@Override
1669					public void userInputRequried(PendingIntent pi, Message object) {
1670						hidePrepareFileToast(prepareFileToast);
1671					}
1672
1673					@Override
1674					public void success(Message message) {
1675						hidePrepareFileToast(prepareFileToast);
1676						xmppConnectionService.sendMessage(message);
1677					}
1678
1679					@Override
1680					public void error(final int error, Message message) {
1681						hidePrepareFileToast(prepareFileToast);
1682						runOnUiThread(new Runnable() {
1683							@Override
1684							public void run() {
1685								replaceToast(getString(error));
1686							}
1687						});
1688					}
1689				});
1690	}
1691
1692	private void hidePrepareFileToast(final Toast prepareFileToast) {
1693		if (prepareFileToast != null) {
1694			runOnUiThread(new Runnable() {
1695
1696				@Override
1697				public void run() {
1698					prepareFileToast.cancel();
1699				}
1700			});
1701		}
1702	}
1703
1704	public void updateConversationList() {
1705		xmppConnectionService.populateWithOrderedConversations(conversationList);
1706		if (!conversationList.contains(mSelectedConversation)) {
1707			mSelectedConversation = null;
1708		}
1709		if (swipedConversation != null) {
1710			if (swipedConversation.isRead()) {
1711				conversationList.remove(swipedConversation);
1712			} else {
1713				listView.discardUndo();
1714			}
1715		}
1716		listAdapter.notifyDataSetChanged();
1717	}
1718
1719	public void runIntent(PendingIntent pi, int requestCode) {
1720		try {
1721			this.startIntentSenderForResult(pi.getIntentSender(), requestCode,
1722					null, 0, 0, 0);
1723		} catch (final SendIntentException ignored) {
1724		}
1725	}
1726
1727	public void encryptTextMessage(Message message) {
1728		xmppConnectionService.getPgpEngine().encrypt(message,
1729				new UiCallback<Message>() {
1730
1731					@Override
1732					public void userInputRequried(PendingIntent pi,Message message) {
1733						ConversationActivity.this.runIntent(pi,ConversationActivity.REQUEST_SEND_MESSAGE);
1734					}
1735
1736					@Override
1737					public void success(Message message) {
1738						message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1739						xmppConnectionService.sendMessage(message);
1740						runOnUiThread(new Runnable() {
1741							@Override
1742							public void run() {
1743								mConversationFragment.messageSent();
1744							}
1745						});
1746					}
1747
1748					@Override
1749					public void error(final int error, Message message) {
1750						runOnUiThread(new Runnable() {
1751							@Override
1752							public void run() {
1753								mConversationFragment.doneSendingPgpMessage();
1754								Toast.makeText(ConversationActivity.this,
1755										R.string.unable_to_connect_to_keychain,
1756										Toast.LENGTH_SHORT
1757								).show();
1758							}
1759						});
1760
1761					}
1762				});
1763	}
1764
1765	public boolean useSendButtonToIndicateStatus() {
1766		return getPreferences().getBoolean("send_button_status", getResources().getBoolean(R.bool.send_button_status));
1767	}
1768
1769	public boolean indicateReceived() {
1770		return getPreferences().getBoolean("indicate_received", getResources().getBoolean(R.bool.indicate_received));
1771	}
1772
1773	public boolean useGreenBackground() {
1774		return getPreferences().getBoolean("use_green_background",getResources().getBoolean(R.bool.use_green_background));
1775	}
1776
1777	protected boolean trustKeysIfNeeded(int requestCode) {
1778		return trustKeysIfNeeded(requestCode, ATTACHMENT_CHOICE_INVALID);
1779	}
1780
1781	protected boolean trustKeysIfNeeded(int requestCode, int attachmentChoice) {
1782		AxolotlService axolotlService = mSelectedConversation.getAccount().getAxolotlService();
1783		final List<Jid> targets = axolotlService.getCryptoTargets(mSelectedConversation);
1784		boolean hasUnaccepted = !mSelectedConversation.getAcceptedCryptoTargets().containsAll(targets);
1785		boolean hasUndecidedOwn = !axolotlService.getKeysWithTrust(FingerprintStatus.createActiveUndecided()).isEmpty();
1786		boolean hasUndecidedContacts = !axolotlService.getKeysWithTrust(FingerprintStatus.createActiveUndecided(), targets).isEmpty();
1787		boolean hasPendingKeys = !axolotlService.findDevicesWithoutSession(mSelectedConversation).isEmpty();
1788		boolean hasNoTrustedKeys = axolotlService.anyTargetHasNoTrustedKeys(targets);
1789		if(hasUndecidedOwn || hasUndecidedContacts || hasPendingKeys || hasNoTrustedKeys || hasUnaccepted) {
1790			axolotlService.createSessionsIfNeeded(mSelectedConversation);
1791			Intent intent = new Intent(getApplicationContext(), TrustKeysActivity.class);
1792			String[] contacts = new String[targets.size()];
1793			for(int i = 0; i < contacts.length; ++i) {
1794				contacts[i] = targets.get(i).toString();
1795			}
1796			intent.putExtra("contacts", contacts);
1797			intent.putExtra(EXTRA_ACCOUNT, mSelectedConversation.getAccount().getJid().toBareJid().toString());
1798			intent.putExtra("choice", attachmentChoice);
1799			intent.putExtra("conversation",mSelectedConversation.getUuid());
1800			startActivityForResult(intent, requestCode);
1801			return true;
1802		} else {
1803			return false;
1804		}
1805	}
1806
1807	@Override
1808	protected void refreshUiReal() {
1809		updateConversationList();
1810		if (conversationList.size() > 0) {
1811			if (!this.mConversationFragment.isAdded()) {
1812				Log.d(Config.LOGTAG,"fragment NOT added to activity. detached="+Boolean.toString(mConversationFragment.isDetached()));
1813			}
1814			if (getSelectedConversation() == null) {
1815				reInitLatestConversation();
1816			} else {
1817				ConversationActivity.this.mConversationFragment.updateMessages();
1818				updateActionBarTitle();
1819				invalidateOptionsMenu();
1820			}
1821		} else {
1822			if (!isStopping() && mRedirected.compareAndSet(false, true)) {
1823				redirectToStartConversationActivity(false);
1824			}
1825			Log.d(Config.LOGTAG,"not updating conversations fragment because conversations list size was 0");
1826		}
1827	}
1828
1829	@Override
1830	public void onAccountUpdate() {
1831		this.refreshUi();
1832	}
1833
1834	@Override
1835	public void onConversationUpdate() {
1836		this.refreshUi();
1837	}
1838
1839	@Override
1840	public void onRosterUpdate() {
1841		this.refreshUi();
1842	}
1843
1844	@Override
1845	public void OnUpdateBlocklist(Status status) {
1846		this.refreshUi();
1847	}
1848
1849	public void unblockConversation(final Blockable conversation) {
1850		xmppConnectionService.sendUnblockRequest(conversation);
1851	}
1852
1853	public boolean enterIsSend() {
1854		return getPreferences().getBoolean("enter_is_send",getResources().getBoolean(R.bool.enter_is_send));
1855	}
1856
1857	@Override
1858	public void onShowErrorToast(final int resId) {
1859		runOnUiThread(new Runnable() {
1860			@Override
1861			public void run() {
1862				Toast.makeText(ConversationActivity.this,resId,Toast.LENGTH_SHORT).show();
1863			}
1864		});
1865	}
1866
1867	public boolean highlightSelectedConversations() {
1868		return !isConversationsOverviewHideable() || this.conversationWasSelectedByKeyboard;
1869	}
1870}