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