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