ConversationActivity.java

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