XmppActivity.java

   1package eu.siacs.conversations.ui;
   2
   3import android.Manifest;
   4import android.annotation.SuppressLint;
   5import android.annotation.TargetApi;
   6import android.app.PendingIntent;
   7import android.content.ActivityNotFoundException;
   8import android.content.ClipData;
   9import android.content.ClipboardManager;
  10import android.content.ComponentName;
  11import android.content.Context;
  12import android.content.DialogInterface;
  13import android.content.Intent;
  14import android.content.IntentSender.SendIntentException;
  15import android.content.ServiceConnection;
  16import android.content.SharedPreferences;
  17import android.content.pm.PackageManager;
  18import android.content.pm.ResolveInfo;
  19import android.content.res.Resources;
  20import android.content.res.TypedArray;
  21import android.databinding.DataBindingUtil;
  22import android.graphics.Bitmap;
  23import android.graphics.Color;
  24import android.graphics.Point;
  25import android.graphics.drawable.BitmapDrawable;
  26import android.graphics.drawable.Drawable;
  27import android.net.ConnectivityManager;
  28import android.net.Uri;
  29import android.os.AsyncTask;
  30import android.os.Build;
  31import android.os.Bundle;
  32import android.os.Handler;
  33import android.os.IBinder;
  34import android.os.PowerManager;
  35import android.os.SystemClock;
  36import android.preference.PreferenceManager;
  37import android.support.annotation.BoolRes;
  38import android.support.annotation.StringRes;
  39import android.support.v4.content.ContextCompat;
  40import android.support.v7.app.AlertDialog;
  41import android.support.v7.app.AlertDialog.Builder;
  42import android.support.v7.app.AppCompatDelegate;
  43import android.text.InputType;
  44import android.util.DisplayMetrics;
  45import android.util.Log;
  46import android.view.Menu;
  47import android.view.MenuItem;
  48import android.view.View;
  49import android.widget.EditText;
  50import android.widget.ImageView;
  51import android.widget.Toast;
  52
  53import java.io.IOException;
  54import java.lang.ref.WeakReference;
  55import java.util.ArrayList;
  56import java.util.List;
  57import java.util.concurrent.RejectedExecutionException;
  58import java.util.concurrent.atomic.AtomicBoolean;
  59
  60import eu.siacs.conversations.Config;
  61import eu.siacs.conversations.R;
  62import eu.siacs.conversations.crypto.PgpEngine;
  63import eu.siacs.conversations.databinding.DialogQuickeditBinding;
  64import eu.siacs.conversations.entities.Account;
  65import eu.siacs.conversations.entities.Contact;
  66import eu.siacs.conversations.entities.Conversation;
  67import eu.siacs.conversations.entities.Message;
  68import eu.siacs.conversations.entities.Presences;
  69import eu.siacs.conversations.services.AvatarService;
  70import eu.siacs.conversations.services.BarcodeProvider;
  71import eu.siacs.conversations.services.XmppConnectionService;
  72import eu.siacs.conversations.services.XmppConnectionService.XmppConnectionBinder;
  73import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
  74import eu.siacs.conversations.ui.util.PresenceSelector;
  75import eu.siacs.conversations.ui.util.SoftKeyboardUtils;
  76import eu.siacs.conversations.utils.ExceptionHelper;
  77import eu.siacs.conversations.utils.ThemeHelper;
  78import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
  79import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
  80import rocks.xmpp.addr.Jid;
  81
  82public abstract class XmppActivity extends ActionBarActivity {
  83
  84	public static final String EXTRA_ACCOUNT = "account";
  85	protected static final int REQUEST_ANNOUNCE_PGP = 0x0101;
  86	protected static final int REQUEST_INVITE_TO_CONVERSATION = 0x0102;
  87	protected static final int REQUEST_CHOOSE_PGP_ID = 0x0103;
  88	protected static final int REQUEST_BATTERY_OP = 0x49ff;
  89	public XmppConnectionService xmppConnectionService;
  90	public boolean xmppConnectionServiceBound = false;
  91	protected final AtomicBoolean registeredListeners = new AtomicBoolean(false);
  92
  93	protected int mColorRed;
  94
  95	protected static final String FRAGMENT_TAG_DIALOG = "dialog";
  96
  97	private boolean isCameraFeatureAvailable = false;
  98
  99	protected int mTheme;
 100	protected boolean mUsingEnterKey = false;
 101	protected Toast mToast;
 102	public Runnable onOpenPGPKeyPublished = () -> Toast.makeText(XmppActivity.this, R.string.openpgp_has_been_published, Toast.LENGTH_SHORT).show();
 103	protected ConferenceInvite mPendingConferenceInvite = null;
 104	protected ServiceConnection mConnection = new ServiceConnection() {
 105
 106		@Override
 107		public void onServiceConnected(ComponentName className, IBinder service) {
 108			XmppConnectionBinder binder = (XmppConnectionBinder) service;
 109			xmppConnectionService = binder.getService();
 110			xmppConnectionServiceBound = true;
 111			if (registeredListeners.compareAndSet(false,true)) {
 112				registerListeners();
 113			}
 114			onBackendConnected();
 115		}
 116
 117		@Override
 118		public void onServiceDisconnected(ComponentName arg0) {
 119			xmppConnectionServiceBound = false;
 120		}
 121	};
 122	private DisplayMetrics metrics;
 123	private long mLastUiRefresh = 0;
 124	private Handler mRefreshUiHandler = new Handler();
 125	private Runnable mRefreshUiRunnable = () -> {
 126		mLastUiRefresh = SystemClock.elapsedRealtime();
 127		refreshUiReal();
 128	};
 129	private UiCallback<Conversation> adhocCallback = new UiCallback<Conversation>() {
 130		@Override
 131		public void success(final Conversation conversation) {
 132			runOnUiThread(() -> {
 133				switchToConversation(conversation);
 134				hideToast();
 135			});
 136		}
 137
 138		@Override
 139		public void error(final int errorCode, Conversation object) {
 140			runOnUiThread(() -> replaceToast(getString(errorCode)));
 141		}
 142
 143		@Override
 144		public void userInputRequried(PendingIntent pi, Conversation object) {
 145
 146		}
 147	};
 148	public boolean mSkipBackgroundBinding = false;
 149
 150	public static boolean cancelPotentialWork(Message message, ImageView imageView) {
 151		final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
 152
 153		if (bitmapWorkerTask != null) {
 154			final Message oldMessage = bitmapWorkerTask.message;
 155			if (oldMessage == null || message != oldMessage) {
 156				bitmapWorkerTask.cancel(true);
 157			} else {
 158				return false;
 159			}
 160		}
 161		return true;
 162	}
 163
 164	private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
 165		if (imageView != null) {
 166			final Drawable drawable = imageView.getDrawable();
 167			if (drawable instanceof AsyncDrawable) {
 168				final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
 169				return asyncDrawable.getBitmapWorkerTask();
 170			}
 171		}
 172		return null;
 173	}
 174
 175	protected void hideToast() {
 176		if (mToast != null) {
 177			mToast.cancel();
 178		}
 179	}
 180
 181	protected void replaceToast(String msg) {
 182		replaceToast(msg, true);
 183	}
 184
 185	protected void replaceToast(String msg, boolean showlong) {
 186		hideToast();
 187		mToast = Toast.makeText(this, msg, showlong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT);
 188		mToast.show();
 189	}
 190
 191	protected final void refreshUi() {
 192		final long diff = SystemClock.elapsedRealtime() - mLastUiRefresh;
 193		if (diff > Config.REFRESH_UI_INTERVAL) {
 194			mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
 195			runOnUiThread(mRefreshUiRunnable);
 196		} else {
 197			final long next = Config.REFRESH_UI_INTERVAL - diff;
 198			mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
 199			mRefreshUiHandler.postDelayed(mRefreshUiRunnable, next);
 200		}
 201	}
 202
 203	abstract protected void refreshUiReal();
 204
 205	@Override
 206	protected void onStart() {
 207		super.onStart();
 208		if (!xmppConnectionServiceBound) {
 209			if (this.mSkipBackgroundBinding) {
 210				Log.d(Config.LOGTAG,"skipping background binding");
 211			} else {
 212				connectToBackend();
 213			}
 214		} else {
 215			if (registeredListeners.compareAndSet(false,true)) {
 216				this.registerListeners();
 217			}
 218			this.onBackendConnected();
 219		}
 220	}
 221
 222	public void connectToBackend() {
 223		Intent intent = new Intent(this, XmppConnectionService.class);
 224		intent.setAction("ui");
 225		startService(intent);
 226		bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
 227	}
 228
 229	@Override
 230	protected void onStop() {
 231		super.onStop();
 232		if (xmppConnectionServiceBound) {
 233			if (registeredListeners.compareAndSet(true, false)) {
 234				this.unregisterListeners();
 235			}
 236			unbindService(mConnection);
 237			xmppConnectionServiceBound = false;
 238		}
 239	}
 240
 241
 242	public boolean hasPgp() {
 243		return xmppConnectionService.getPgpEngine() != null;
 244	}
 245
 246	public void showInstallPgpDialog() {
 247		Builder builder = new AlertDialog.Builder(this);
 248		builder.setTitle(getString(R.string.openkeychain_required));
 249		builder.setIconAttribute(android.R.attr.alertDialogIcon);
 250		builder.setMessage(getText(R.string.openkeychain_required_long));
 251		builder.setNegativeButton(getString(R.string.cancel), null);
 252		builder.setNeutralButton(getString(R.string.restart),
 253				(dialog, which) -> {
 254					if (xmppConnectionServiceBound) {
 255						unbindService(mConnection);
 256						xmppConnectionServiceBound = false;
 257					}
 258					stopService(new Intent(XmppActivity.this,
 259							XmppConnectionService.class));
 260					finish();
 261				});
 262		builder.setPositiveButton(getString(R.string.install),
 263				(dialog, which) -> {
 264					Uri uri = Uri
 265							.parse("market://details?id=org.sufficientlysecure.keychain");
 266					Intent marketIntent = new Intent(Intent.ACTION_VIEW,
 267							uri);
 268					PackageManager manager = getApplicationContext()
 269							.getPackageManager();
 270					List<ResolveInfo> infos = manager
 271							.queryIntentActivities(marketIntent, 0);
 272					if (infos.size() > 0) {
 273						startActivity(marketIntent);
 274					} else {
 275						uri = Uri.parse("http://www.openkeychain.org/");
 276						Intent browserIntent = new Intent(
 277								Intent.ACTION_VIEW, uri);
 278						startActivity(browserIntent);
 279					}
 280					finish();
 281				});
 282		builder.create().show();
 283	}
 284
 285	abstract void onBackendConnected();
 286
 287	protected void registerListeners() {
 288		if (this instanceof XmppConnectionService.OnConversationUpdate) {
 289			this.xmppConnectionService.setOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this);
 290		}
 291		if (this instanceof XmppConnectionService.OnAccountUpdate) {
 292			this.xmppConnectionService.setOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this);
 293		}
 294		if (this instanceof XmppConnectionService.OnCaptchaRequested) {
 295			this.xmppConnectionService.setOnCaptchaRequestedListener((XmppConnectionService.OnCaptchaRequested) this);
 296		}
 297		if (this instanceof XmppConnectionService.OnRosterUpdate) {
 298			this.xmppConnectionService.setOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this);
 299		}
 300		if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
 301			this.xmppConnectionService.setOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this);
 302		}
 303		if (this instanceof OnUpdateBlocklist) {
 304			this.xmppConnectionService.setOnUpdateBlocklistListener((OnUpdateBlocklist) this);
 305		}
 306		if (this instanceof XmppConnectionService.OnShowErrorToast) {
 307			this.xmppConnectionService.setOnShowErrorToastListener((XmppConnectionService.OnShowErrorToast) this);
 308		}
 309		if (this instanceof OnKeyStatusUpdated) {
 310			this.xmppConnectionService.setOnKeyStatusUpdatedListener((OnKeyStatusUpdated) this);
 311		}
 312	}
 313
 314	protected void unregisterListeners() {
 315		if (this instanceof XmppConnectionService.OnConversationUpdate) {
 316			this.xmppConnectionService.removeOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this);
 317		}
 318		if (this instanceof XmppConnectionService.OnAccountUpdate) {
 319			this.xmppConnectionService.removeOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this);
 320		}
 321		if (this instanceof XmppConnectionService.OnCaptchaRequested) {
 322			this.xmppConnectionService.removeOnCaptchaRequestedListener((XmppConnectionService.OnCaptchaRequested) this);
 323		}
 324		if (this instanceof XmppConnectionService.OnRosterUpdate) {
 325			this.xmppConnectionService.removeOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this);
 326		}
 327		if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
 328			this.xmppConnectionService.removeOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this);
 329		}
 330		if (this instanceof OnUpdateBlocklist) {
 331			this.xmppConnectionService.removeOnUpdateBlocklistListener((OnUpdateBlocklist) this);
 332		}
 333		if (this instanceof XmppConnectionService.OnShowErrorToast) {
 334			this.xmppConnectionService.removeOnShowErrorToastListener((XmppConnectionService.OnShowErrorToast) this);
 335		}
 336		if (this instanceof OnKeyStatusUpdated) {
 337			this.xmppConnectionService.removeOnNewKeysAvailableListener((OnKeyStatusUpdated) this);
 338		}
 339	}
 340
 341	@Override
 342	public boolean onOptionsItemSelected(final MenuItem item) {
 343		switch (item.getItemId()) {
 344			case R.id.action_settings:
 345				startActivity(new Intent(this, SettingsActivity.class));
 346				break;
 347			case R.id.action_accounts:
 348				startActivity(new Intent(this, ManageAccountActivity.class));
 349				break;
 350			case android.R.id.home:
 351				finish();
 352				break;
 353			case R.id.action_show_qr_code:
 354				showQrCode();
 355				break;
 356		}
 357		return super.onOptionsItemSelected(item);
 358	}
 359
 360	public void selectPresence(final Conversation conversation, final PresenceSelector.OnPresenceSelected listener) {
 361		final Contact contact = conversation.getContact();
 362		if (!contact.showInRoster()) {
 363			showAddToRosterDialog(conversation.getContact());
 364		} else {
 365			final Presences presences = contact.getPresences();
 366			if (presences.size() == 0) {
 367				if (!contact.getOption(Contact.Options.TO)
 368						&& !contact.getOption(Contact.Options.ASKING)
 369						&& contact.getAccount().getStatus() == Account.State.ONLINE) {
 370					showAskForPresenceDialog(contact);
 371				} else if (!contact.getOption(Contact.Options.TO)
 372						|| !contact.getOption(Contact.Options.FROM)) {
 373					PresenceSelector.warnMutualPresenceSubscription(this, conversation, listener);
 374				} else {
 375					conversation.setNextCounterpart(null);
 376					listener.onPresenceSelected();
 377				}
 378			} else if (presences.size() == 1) {
 379				String presence = presences.toResourceArray()[0];
 380				try {
 381					conversation.setNextCounterpart(Jid.of(contact.getJid().getLocal(), contact.getJid().getDomain(), presence));
 382				} catch (IllegalArgumentException e) {
 383					conversation.setNextCounterpart(null);
 384				}
 385				listener.onPresenceSelected();
 386			} else {
 387				PresenceSelector.showPresenceSelectionDialog(this, conversation, listener);
 388			}
 389		}
 390	}
 391
 392	@Override
 393	protected void onCreate(Bundle savedInstanceState) {
 394		super.onCreate(savedInstanceState);
 395		metrics = getResources().getDisplayMetrics();
 396		ExceptionHelper.init(getApplicationContext());
 397		this.isCameraFeatureAvailable = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
 398
 399		mColorRed = ContextCompat.getColor(this, R.color.red800);
 400
 401		this.mTheme = findTheme();
 402		setTheme(this.mTheme);
 403
 404		this.mUsingEnterKey = usingEnterKey();
 405	}
 406
 407	protected boolean isCameraFeatureAvailable() {
 408		return this.isCameraFeatureAvailable;
 409	}
 410
 411	public boolean isDarkTheme() {
 412		return ThemeHelper.isDark(mTheme);
 413	}
 414
 415	public int getThemeResource(int r_attr_name, int r_drawable_def) {
 416		int[] attrs = {r_attr_name};
 417		TypedArray ta = this.getTheme().obtainStyledAttributes(attrs);
 418
 419		int res = ta.getResourceId(0, r_drawable_def);
 420		ta.recycle();
 421
 422		return res;
 423	}
 424
 425	protected boolean isOptimizingBattery() {
 426		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 427			final PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
 428			return pm != null
 429					&& !pm.isIgnoringBatteryOptimizations(getPackageName());
 430		} else {
 431			return false;
 432		}
 433	}
 434
 435	protected boolean isAffectedByDataSaver() {
 436		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 437			final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
 438			return cm != null
 439					&& cm.isActiveNetworkMetered()
 440					&& cm.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
 441		} else {
 442			return false;
 443		}
 444	}
 445
 446	protected boolean usingEnterKey() {
 447		return getBooleanPreference("display_enter_key", R.bool.display_enter_key);
 448	}
 449
 450	protected SharedPreferences getPreferences() {
 451		return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
 452	}
 453
 454	protected boolean getBooleanPreference(String name, @BoolRes int res) {
 455		return getPreferences().getBoolean(name, getResources().getBoolean(res));
 456	}
 457
 458	public void switchToConversation(Conversation conversation) {
 459		switchToConversation(conversation, null, false);
 460	}
 461
 462	public void switchToConversationAndQuote(Conversation conversation, String text) {
 463		switchToConversation(conversation, text, true, null, false, false);
 464	}
 465
 466	public void switchToConversation(Conversation conversation, String text, boolean newTask) {
 467		switchToConversation(conversation, text, false, null, false, newTask);
 468	}
 469
 470	public void highlightInMuc(Conversation conversation, String nick) {
 471		switchToConversation(conversation, null, false, nick, false, false);
 472	}
 473
 474	public void privateMsgInMuc(Conversation conversation, String nick) {
 475		switchToConversation(conversation, null, false, nick, true, false);
 476	}
 477
 478	private void switchToConversation(Conversation conversation, String text, boolean asQuote, String nick, boolean pm, boolean newTask) {
 479		Intent intent = new Intent(this, ConversationsActivity.class);
 480		intent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
 481		intent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid());
 482		if (text != null) {
 483			intent.putExtra(ConversationsActivity.EXTRA_TEXT, text);
 484			if (asQuote) {
 485				intent.putExtra(ConversationsActivity.EXTRA_AS_QUOTE, asQuote);
 486			}
 487		}
 488		if (nick != null) {
 489			intent.putExtra(ConversationsActivity.EXTRA_NICK, nick);
 490			intent.putExtra(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, pm);
 491		}
 492		if (newTask) {
 493			intent.setFlags(intent.getFlags()
 494					| Intent.FLAG_ACTIVITY_NEW_TASK
 495					| Intent.FLAG_ACTIVITY_SINGLE_TOP);
 496		} else {
 497			intent.setFlags(intent.getFlags()
 498					| Intent.FLAG_ACTIVITY_CLEAR_TOP);
 499		}
 500		startActivity(intent);
 501		finish();
 502	}
 503
 504	public void switchToContactDetails(Contact contact) {
 505		switchToContactDetails(contact, null);
 506	}
 507
 508	public void switchToContactDetails(Contact contact, String messageFingerprint) {
 509		Intent intent = new Intent(this, ContactDetailsActivity.class);
 510		intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
 511		intent.putExtra(EXTRA_ACCOUNT, contact.getAccount().getJid().asBareJid().toString());
 512		intent.putExtra("contact", contact.getJid().toString());
 513		intent.putExtra("fingerprint", messageFingerprint);
 514		startActivity(intent);
 515	}
 516
 517	public void switchToAccount(Account account, String fingerprint) {
 518		switchToAccount(account, false, fingerprint);
 519	}
 520
 521	public void switchToAccount(Account account) {
 522		switchToAccount(account, false, null);
 523	}
 524
 525	public void switchToAccount(Account account, boolean init, String fingerprint) {
 526		Intent intent = new Intent(this, EditAccountActivity.class);
 527		intent.putExtra("jid", account.getJid().asBareJid().toString());
 528		intent.putExtra("init", init);
 529		if (init) {
 530			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
 531		}
 532		if (fingerprint != null) {
 533			intent.putExtra("fingerprint", fingerprint);
 534		}
 535		startActivity(intent);
 536		if (init) {
 537			overridePendingTransition(0, 0);
 538		}
 539	}
 540
 541	protected void delegateUriPermissionsToService(Uri uri) {
 542		Intent intent = new Intent(this,XmppConnectionService.class);
 543		intent.setAction(Intent.ACTION_SEND);
 544		intent.setData(uri);
 545		intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
 546		startService(intent);
 547	}
 548
 549	protected void inviteToConversation(Conversation conversation) {
 550		startActivityForResult(ChooseContactActivity.create(this,conversation), REQUEST_INVITE_TO_CONVERSATION);
 551	}
 552
 553	protected void announcePgp(final Account account, final Conversation conversation, Intent intent, final Runnable onSuccess) {
 554		if (account.getPgpId() == 0) {
 555			choosePgpSignId(account);
 556		} else {
 557			String status = null;
 558			if (manuallyChangePresence()) {
 559				status = account.getPresenceStatusMessage();
 560			}
 561			if (status == null) {
 562				status = "";
 563			}
 564			xmppConnectionService.getPgpEngine().generateSignature(intent, account, status, new UiCallback<String>() {
 565
 566				@Override
 567				public void userInputRequried(PendingIntent pi, String signature) {
 568					try {
 569						startIntentSenderForResult(pi.getIntentSender(), REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
 570					} catch (final SendIntentException ignored) {
 571					}
 572				}
 573
 574				@Override
 575				public void success(String signature) {
 576					account.setPgpSignature(signature);
 577					xmppConnectionService.databaseBackend.updateAccount(account);
 578					xmppConnectionService.sendPresence(account);
 579					if (conversation != null) {
 580						conversation.setNextEncryption(Message.ENCRYPTION_PGP);
 581						xmppConnectionService.updateConversation(conversation);
 582						refreshUi();
 583					}
 584					if (onSuccess != null) {
 585						runOnUiThread(onSuccess);
 586					}
 587				}
 588
 589				@Override
 590				public void error(int error, String signature) {
 591					if (error == 0) {
 592						account.setPgpSignId(0);
 593						account.unsetPgpSignature();
 594						xmppConnectionService.databaseBackend.updateAccount(account);
 595						choosePgpSignId(account);
 596					} else {
 597						displayErrorDialog(error);
 598					}
 599				}
 600			});
 601		}
 602	}
 603
 604	protected boolean noAccountUsesPgp() {
 605		if (!hasPgp()) {
 606			return true;
 607		}
 608		for (Account account : xmppConnectionService.getAccounts()) {
 609			if (account.getPgpId() != 0) {
 610				return false;
 611			}
 612		}
 613		return true;
 614	}
 615
 616	@SuppressWarnings("deprecation")
 617	@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
 618	protected void setListItemBackgroundOnView(View view) {
 619		int sdk = android.os.Build.VERSION.SDK_INT;
 620		if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
 621			view.setBackgroundDrawable(getResources().getDrawable(R.drawable.greybackground));
 622		} else {
 623			view.setBackground(getResources().getDrawable(R.drawable.greybackground));
 624		}
 625	}
 626
 627	protected void choosePgpSignId(Account account) {
 628		xmppConnectionService.getPgpEngine().chooseKey(account, new UiCallback<Account>() {
 629			@Override
 630			public void success(Account account1) {
 631			}
 632
 633			@Override
 634			public void error(int errorCode, Account object) {
 635
 636			}
 637
 638			@Override
 639			public void userInputRequried(PendingIntent pi, Account object) {
 640				try {
 641					startIntentSenderForResult(pi.getIntentSender(),
 642							REQUEST_CHOOSE_PGP_ID, null, 0, 0, 0);
 643				} catch (final SendIntentException ignored) {
 644				}
 645			}
 646		});
 647	}
 648
 649	protected void displayErrorDialog(final int errorCode) {
 650		runOnUiThread(() -> {
 651			Builder builder = new Builder(XmppActivity.this);
 652			builder.setIconAttribute(android.R.attr.alertDialogIcon);
 653			builder.setTitle(getString(R.string.error));
 654			builder.setMessage(errorCode);
 655			builder.setNeutralButton(R.string.accept, null);
 656			builder.create().show();
 657		});
 658
 659	}
 660
 661	protected void showAddToRosterDialog(final Contact contact) {
 662		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 663		builder.setTitle(contact.getJid().toString());
 664		builder.setMessage(getString(R.string.not_in_roster));
 665		builder.setNegativeButton(getString(R.string.cancel), null);
 666		builder.setPositiveButton(getString(R.string.add_contact), (dialog, which) -> xmppConnectionService.createContact(contact,true));
 667		builder.create().show();
 668	}
 669
 670	private void showAskForPresenceDialog(final Contact contact) {
 671		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 672		builder.setTitle(contact.getJid().toString());
 673		builder.setMessage(R.string.request_presence_updates);
 674		builder.setNegativeButton(R.string.cancel, null);
 675		builder.setPositiveButton(R.string.request_now,
 676				(dialog, which) -> {
 677					if (xmppConnectionServiceBound) {
 678						xmppConnectionService.sendPresencePacket(contact
 679								.getAccount(), xmppConnectionService
 680								.getPresenceGenerator()
 681								.requestPresenceUpdatesFrom(contact));
 682					}
 683				});
 684		builder.create().show();
 685	}
 686
 687	protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback) {
 688		quickEdit(previousValue, callback, hint, false, false);
 689	}
 690
 691	protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback, boolean permitEmpty) {
 692		quickEdit(previousValue, callback, hint, false, permitEmpty);
 693	}
 694
 695	protected void quickPasswordEdit(String previousValue, OnValueEdited callback) {
 696		quickEdit(previousValue, callback, R.string.password, true, false);
 697	}
 698
 699	@SuppressLint("InflateParams")
 700	private void quickEdit(final String previousValue,
 701	                       final OnValueEdited callback,
 702	                       final @StringRes int hint,
 703	                       boolean password,
 704	                       boolean permitEmpty) {
 705		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 706		DialogQuickeditBinding binding = DataBindingUtil.inflate(getLayoutInflater(),R.layout.dialog_quickedit, null, false);
 707		if (password) {
 708			binding.inputEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
 709		}
 710		builder.setPositiveButton(R.string.accept, null);
 711		if (hint != 0) {
 712			binding.inputLayout.setHint(getString(hint));
 713		}
 714		binding.inputEditText.requestFocus();
 715		if (previousValue != null) {
 716			binding.inputEditText.getText().append(previousValue);
 717		}
 718		builder.setView(binding.getRoot());
 719		builder.setNegativeButton(R.string.cancel, null);
 720		final AlertDialog dialog = builder.create();
 721		dialog.setOnShowListener(d -> SoftKeyboardUtils.showKeyboard(binding.inputEditText));
 722		dialog.show();
 723		View.OnClickListener clickListener = v -> {
 724			String value = binding.inputEditText.getText().toString();
 725			if (!value.equals(previousValue) && (!value.trim().isEmpty() || permitEmpty)) {
 726				String error = callback.onValueEdited(value);
 727				if (error != null) {
 728					binding.inputLayout.setError(error);
 729					return;
 730				}
 731			}
 732			SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
 733			dialog.dismiss();
 734		};
 735		dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(clickListener);
 736		dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setOnClickListener((v -> {
 737			SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
 738			dialog.dismiss();
 739		}));
 740		dialog.setOnDismissListener(dialog1 -> {
 741			SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
 742        });
 743	}
 744
 745	protected boolean hasStoragePermission(int requestCode) {
 746		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 747			if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
 748				requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
 749				return false;
 750			} else {
 751				return true;
 752			}
 753		} else {
 754			return true;
 755		}
 756	}
 757
 758	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
 759		super.onActivityResult(requestCode, resultCode, data);
 760		if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
 761			mPendingConferenceInvite = ConferenceInvite.parse(data);
 762			if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
 763				if (mPendingConferenceInvite.execute(this)) {
 764					mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
 765					mToast.show();
 766				}
 767				mPendingConferenceInvite = null;
 768			}
 769		}
 770	}
 771
 772	public int getWarningTextColor() {
 773		return this.mColorRed;
 774	}
 775
 776	public int getPixel(int dp) {
 777		DisplayMetrics metrics = getResources().getDisplayMetrics();
 778		return ((int) (dp * metrics.density));
 779	}
 780
 781	public boolean copyTextToClipboard(String text, int labelResId) {
 782		ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
 783		String label = getResources().getString(labelResId);
 784		if (mClipBoardManager != null) {
 785			ClipData mClipData = ClipData.newPlainText(label, text);
 786			mClipBoardManager.setPrimaryClip(mClipData);
 787			return true;
 788		}
 789		return false;
 790	}
 791
 792	protected boolean neverCompressPictures() {
 793		return getPreferences().getString("picture_compression", getResources().getString(R.string.picture_compression)).equals("never");
 794	}
 795
 796	protected boolean manuallyChangePresence() {
 797		return getBooleanPreference(SettingsActivity.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
 798	}
 799
 800	protected String getShareableUri() {
 801		return getShareableUri(false);
 802	}
 803
 804	protected String getShareableUri(boolean http) {
 805		return null;
 806	}
 807
 808	protected void shareLink(boolean http) {
 809		String uri = getShareableUri(http);
 810		if (uri == null || uri.isEmpty()) {
 811			return;
 812		}
 813		Intent intent = new Intent(Intent.ACTION_SEND);
 814		intent.setType("text/plain");
 815		intent.putExtra(Intent.EXTRA_TEXT, getShareableUri(http));
 816		try {
 817			startActivity(Intent.createChooser(intent, getText(R.string.share_uri_with)));
 818		} catch (ActivityNotFoundException e) {
 819			Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
 820		}
 821	}
 822
 823	protected void launchOpenKeyChain(long keyId) {
 824		PgpEngine pgp = XmppActivity.this.xmppConnectionService.getPgpEngine();
 825		try {
 826			startIntentSenderForResult(
 827					pgp.getIntentForKey(keyId).getIntentSender(), 0, null, 0,
 828					0, 0);
 829		} catch (Throwable e) {
 830			Toast.makeText(XmppActivity.this, R.string.openpgp_error, Toast.LENGTH_SHORT).show();
 831		}
 832	}
 833
 834	@Override
 835	public void onResume() {
 836		super.onResume();
 837	}
 838
 839	protected int findTheme() {
 840		return ThemeHelper.find(this);
 841	}
 842
 843	@Override
 844	public void onPause() {
 845		super.onPause();
 846	}
 847
 848	@Override
 849	public boolean onMenuOpened(int id, Menu menu) {
 850		if(id == AppCompatDelegate.FEATURE_SUPPORT_ACTION_BAR && menu != null) {
 851			MenuDoubleTabUtil.recordMenuOpen();
 852		}
 853		return super.onMenuOpened(id, menu);
 854	}
 855
 856	protected void showQrCode() {
 857		showQrCode(getShareableUri());
 858	}
 859
 860	protected void showQrCode(final String uri) {
 861		if (uri == null || uri.isEmpty()) {
 862			return;
 863		}
 864		Point size = new Point();
 865		getWindowManager().getDefaultDisplay().getSize(size);
 866		final int width = (size.x < size.y ? size.x : size.y);
 867		Bitmap bitmap = BarcodeProvider.create2dBarcodeBitmap(uri, width);
 868		ImageView view = new ImageView(this);
 869		view.setBackgroundColor(Color.WHITE);
 870		view.setImageBitmap(bitmap);
 871		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 872		builder.setView(view);
 873		builder.create().show();
 874	}
 875
 876	protected Account extractAccount(Intent intent) {
 877		String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null;
 878		try {
 879			return jid != null ? xmppConnectionService.findAccountByJid(Jid.of(jid)) : null;
 880		} catch (IllegalArgumentException e) {
 881			return null;
 882		}
 883	}
 884
 885	public AvatarService avatarService() {
 886		return xmppConnectionService.getAvatarService();
 887	}
 888
 889	public void loadBitmap(Message message, ImageView imageView) {
 890		Bitmap bm;
 891		try {
 892			bm = xmppConnectionService.getFileBackend().getThumbnail(message, (int) (metrics.density * 288), true);
 893		} catch (IOException e) {
 894			bm = null;
 895		}
 896		if (bm != null) {
 897			cancelPotentialWork(message, imageView);
 898			imageView.setImageBitmap(bm);
 899			imageView.setBackgroundColor(0x00000000);
 900		} else {
 901			if (cancelPotentialWork(message, imageView)) {
 902				imageView.setBackgroundColor(0xff333333);
 903				imageView.setImageDrawable(null);
 904				final BitmapWorkerTask task = new BitmapWorkerTask(this, imageView);
 905				final AsyncDrawable asyncDrawable = new AsyncDrawable(
 906						getResources(), null, task);
 907				imageView.setImageDrawable(asyncDrawable);
 908				try {
 909					task.execute(message);
 910				} catch (final RejectedExecutionException ignored) {
 911					ignored.printStackTrace();
 912				}
 913			}
 914		}
 915	}
 916
 917	protected interface OnValueEdited {
 918		String onValueEdited(String value);
 919	}
 920
 921	public static class ConferenceInvite {
 922		private String uuid;
 923		private List<Jid> jids = new ArrayList<>();
 924
 925		public static ConferenceInvite parse(Intent data) {
 926			ConferenceInvite invite = new ConferenceInvite();
 927			invite.uuid = data.getStringExtra(ChooseContactActivity.EXTRA_CONVERSATION);
 928			if (invite.uuid == null) {
 929				return null;
 930			}
 931			invite.jids.addAll(ChooseContactActivity.extractJabberIds(data));
 932			return invite;
 933		}
 934
 935		public boolean execute(XmppActivity activity) {
 936			XmppConnectionService service = activity.xmppConnectionService;
 937			Conversation conversation = service.findConversationByUuid(this.uuid);
 938			if (conversation == null) {
 939				return false;
 940			}
 941			if (conversation.getMode() == Conversation.MODE_MULTI) {
 942				for (Jid jid : jids) {
 943					service.invite(conversation, jid);
 944				}
 945				return false;
 946			} else {
 947				jids.add(conversation.getJid().asBareJid());
 948				return service.createAdhocConference(conversation.getAccount(), null, jids, activity.adhocCallback);
 949			}
 950		}
 951	}
 952
 953	static class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
 954		private final WeakReference<ImageView> imageViewReference;
 955		private final WeakReference<XmppActivity> activity;
 956		private Message message = null;
 957
 958		private BitmapWorkerTask(XmppActivity activity, ImageView imageView) {
 959			this.activity = new WeakReference<>(activity);
 960			this.imageViewReference = new WeakReference<>(imageView);
 961		}
 962
 963		@Override
 964		protected Bitmap doInBackground(Message... params) {
 965			if (isCancelled()) {
 966				return null;
 967			}
 968			message = params[0];
 969			try {
 970				XmppActivity activity = this.activity.get();
 971				if (activity != null && activity.xmppConnectionService != null) {
 972					return activity.xmppConnectionService.getFileBackend().getThumbnail(message, (int) (activity.metrics.density * 288), false);
 973				} else {
 974					return null;
 975				}
 976			} catch (IOException e) {
 977				return null;
 978			}
 979		}
 980
 981		@Override
 982		protected void onPostExecute(Bitmap bitmap) {
 983			if (bitmap != null && !isCancelled()) {
 984				final ImageView imageView = imageViewReference.get();
 985				if (imageView != null) {
 986					imageView.setImageBitmap(bitmap);
 987					imageView.setBackgroundColor(0x00000000);
 988				}
 989			}
 990		}
 991	}
 992
 993	private static class AsyncDrawable extends BitmapDrawable {
 994		private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
 995
 996		private AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
 997			super(res, bitmap);
 998			bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
 999		}
1000
1001		private BitmapWorkerTask getBitmapWorkerTask() {
1002			return bitmapWorkerTaskReference.get();
1003		}
1004	}
1005}