XmppActivity.java

   1package eu.siacs.conversations.ui;
   2
   3import android.annotation.SuppressLint;
   4import android.annotation.TargetApi;
   5import android.app.ActionBar;
   6import android.app.Activity;
   7import android.app.AlertDialog;
   8import android.app.AlertDialog.Builder;
   9import android.app.PendingIntent;
  10import android.content.ClipData;
  11import android.content.ClipboardManager;
  12import android.content.ComponentName;
  13import android.content.Context;
  14import android.content.DialogInterface;
  15import android.content.DialogInterface.OnClickListener;
  16import android.content.Intent;
  17import android.content.IntentSender.SendIntentException;
  18import android.content.ServiceConnection;
  19import android.content.SharedPreferences;
  20import android.content.pm.PackageManager;
  21import android.content.pm.ResolveInfo;
  22import android.content.res.Resources;
  23import android.graphics.Bitmap;
  24import android.graphics.Color;
  25import android.graphics.Point;
  26import android.graphics.drawable.BitmapDrawable;
  27import android.graphics.drawable.Drawable;
  28import android.net.Uri;
  29import android.nfc.NdefMessage;
  30import android.nfc.NdefRecord;
  31import android.nfc.NfcAdapter;
  32import android.nfc.NfcEvent;
  33import android.os.AsyncTask;
  34import android.os.Build;
  35import android.os.Bundle;
  36import android.os.Handler;
  37import android.os.IBinder;
  38import android.os.SystemClock;
  39import android.preference.PreferenceManager;
  40import android.text.InputType;
  41import android.util.DisplayMetrics;
  42import android.util.Log;
  43import android.view.MenuItem;
  44import android.view.View;
  45import android.view.inputmethod.InputMethodManager;
  46import android.widget.CompoundButton;
  47import android.widget.EditText;
  48import android.widget.ImageView;
  49import android.widget.LinearLayout;
  50import android.widget.TextView;
  51import android.widget.Toast;
  52
  53import com.google.zxing.BarcodeFormat;
  54import com.google.zxing.EncodeHintType;
  55import com.google.zxing.WriterException;
  56import com.google.zxing.common.BitMatrix;
  57import com.google.zxing.qrcode.QRCodeWriter;
  58import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
  59
  60import net.java.otr4j.session.SessionID;
  61
  62import java.io.FileNotFoundException;
  63import java.lang.ref.WeakReference;
  64import java.util.ArrayList;
  65import java.util.Hashtable;
  66import java.util.List;
  67import java.util.concurrent.RejectedExecutionException;
  68
  69import eu.siacs.conversations.Config;
  70import eu.siacs.conversations.R;
  71import eu.siacs.conversations.crypto.axolotl.XmppAxolotlSession;
  72import eu.siacs.conversations.entities.Account;
  73import eu.siacs.conversations.entities.Contact;
  74import eu.siacs.conversations.entities.Conversation;
  75import eu.siacs.conversations.entities.Message;
  76import eu.siacs.conversations.entities.MucOptions;
  77import eu.siacs.conversations.entities.Presences;
  78import eu.siacs.conversations.services.AvatarService;
  79import eu.siacs.conversations.services.XmppConnectionService;
  80import eu.siacs.conversations.services.XmppConnectionService.XmppConnectionBinder;
  81import eu.siacs.conversations.ui.widget.Switch;
  82import eu.siacs.conversations.utils.CryptoHelper;
  83import eu.siacs.conversations.utils.ExceptionHelper;
  84import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
  85import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
  86import eu.siacs.conversations.xmpp.jid.InvalidJidException;
  87import eu.siacs.conversations.xmpp.jid.Jid;
  88
  89public abstract class XmppActivity extends Activity {
  90
  91	protected static final int REQUEST_ANNOUNCE_PGP = 0x0101;
  92	protected static final int REQUEST_INVITE_TO_CONVERSATION = 0x0102;
  93	protected static final int REQUEST_CHOOSE_PGP_ID = 0x0103;
  94
  95	public XmppConnectionService xmppConnectionService;
  96	public boolean xmppConnectionServiceBound = false;
  97	protected boolean registeredListeners = false;
  98
  99	protected int mPrimaryTextColor;
 100	protected int mSecondaryTextColor;
 101	protected int mTertiaryTextColor;
 102	protected int mPrimaryBackgroundColor;
 103	protected int mSecondaryBackgroundColor;
 104	protected int mColorRed;
 105	protected int mColorOrange;
 106	protected int mColorGreen;
 107	protected int mPrimaryColor;
 108
 109	protected boolean mUseSubject = true;
 110
 111	private DisplayMetrics metrics;
 112	protected int mTheme;
 113	protected boolean mUsingEnterKey = false;
 114
 115	private long mLastUiRefresh = 0;
 116	private Handler mRefreshUiHandler = new Handler();
 117	private Runnable mRefreshUiRunnable = new Runnable() {
 118		@Override
 119		public void run() {
 120			mLastUiRefresh = SystemClock.elapsedRealtime();
 121			refreshUiReal();
 122		}
 123	};
 124
 125	protected ConferenceInvite mPendingConferenceInvite = null;
 126
 127
 128	protected final void refreshUi() {
 129		final long diff = SystemClock.elapsedRealtime() - mLastUiRefresh;
 130		if (diff > Config.REFRESH_UI_INTERVAL) {
 131			mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
 132			runOnUiThread(mRefreshUiRunnable);
 133		} else {
 134			final long next = Config.REFRESH_UI_INTERVAL - diff;
 135			mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
 136			mRefreshUiHandler.postDelayed(mRefreshUiRunnable,next);
 137		}
 138	}
 139
 140	abstract protected void refreshUiReal();
 141
 142	protected interface OnValueEdited {
 143		public void onValueEdited(String value);
 144	}
 145
 146	public interface OnPresenceSelected {
 147		public void onPresenceSelected();
 148	}
 149
 150	protected ServiceConnection mConnection = new ServiceConnection() {
 151
 152		@Override
 153		public void onServiceConnected(ComponentName className, IBinder service) {
 154			XmppConnectionBinder binder = (XmppConnectionBinder) service;
 155			xmppConnectionService = binder.getService();
 156			xmppConnectionServiceBound = true;
 157			if (!registeredListeners && shouldRegisterListeners()) {
 158				registerListeners();
 159				registeredListeners = true;
 160			}
 161			onBackendConnected();
 162		}
 163
 164		@Override
 165		public void onServiceDisconnected(ComponentName arg0) {
 166			xmppConnectionServiceBound = false;
 167		}
 168	};
 169
 170	@Override
 171	protected void onStart() {
 172		super.onStart();
 173		if (!xmppConnectionServiceBound) {
 174			connectToBackend();
 175		} else {
 176			if (!registeredListeners) {
 177				this.registerListeners();
 178				this.registeredListeners = true;
 179			}
 180			this.onBackendConnected();
 181		}
 182	}
 183
 184	@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
 185	protected boolean shouldRegisterListeners() {
 186		if  (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
 187			return !isDestroyed() && !isFinishing();
 188		} else {
 189			return !isFinishing();
 190		}
 191	}
 192
 193	public void connectToBackend() {
 194		Intent intent = new Intent(this, XmppConnectionService.class);
 195		intent.setAction("ui");
 196		startService(intent);
 197		bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
 198	}
 199
 200	@Override
 201	protected void onStop() {
 202		super.onStop();
 203		if (xmppConnectionServiceBound) {
 204			if (registeredListeners) {
 205				this.unregisterListeners();
 206				this.registeredListeners = false;
 207			}
 208			unbindService(mConnection);
 209			xmppConnectionServiceBound = false;
 210		}
 211	}
 212
 213	protected void hideKeyboard() {
 214		InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
 215
 216		View focus = getCurrentFocus();
 217
 218		if (focus != null) {
 219
 220			inputManager.hideSoftInputFromWindow(focus.getWindowToken(),
 221					InputMethodManager.HIDE_NOT_ALWAYS);
 222		}
 223	}
 224
 225	public boolean hasPgp() {
 226		return xmppConnectionService.getPgpEngine() != null;
 227	}
 228
 229	public void showInstallPgpDialog() {
 230		Builder builder = new AlertDialog.Builder(this);
 231		builder.setTitle(getString(R.string.openkeychain_required));
 232		builder.setIconAttribute(android.R.attr.alertDialogIcon);
 233		builder.setMessage(getText(R.string.openkeychain_required_long));
 234		builder.setNegativeButton(getString(R.string.cancel), null);
 235		builder.setNeutralButton(getString(R.string.restart),
 236				new OnClickListener() {
 237
 238					@Override
 239					public void onClick(DialogInterface dialog, int which) {
 240						if (xmppConnectionServiceBound) {
 241							unbindService(mConnection);
 242							xmppConnectionServiceBound = false;
 243						}
 244						stopService(new Intent(XmppActivity.this,
 245									XmppConnectionService.class));
 246						finish();
 247					}
 248				});
 249		builder.setPositiveButton(getString(R.string.install),
 250				new OnClickListener() {
 251
 252					@Override
 253					public void onClick(DialogInterface dialog, int which) {
 254						Uri uri = Uri
 255							.parse("market://details?id=org.sufficientlysecure.keychain");
 256						Intent marketIntent = new Intent(Intent.ACTION_VIEW,
 257								uri);
 258						PackageManager manager = getApplicationContext()
 259							.getPackageManager();
 260						List<ResolveInfo> infos = manager
 261							.queryIntentActivities(marketIntent, 0);
 262						if (infos.size() > 0) {
 263							startActivity(marketIntent);
 264						} else {
 265							uri = Uri.parse("http://www.openkeychain.org/");
 266							Intent browserIntent = new Intent(
 267									Intent.ACTION_VIEW, uri);
 268							startActivity(browserIntent);
 269						}
 270						finish();
 271					}
 272				});
 273		builder.create().show();
 274	}
 275
 276	abstract void onBackendConnected();
 277
 278	protected void registerListeners() {
 279		if (this instanceof XmppConnectionService.OnConversationUpdate) {
 280			this.xmppConnectionService.setOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this);
 281		}
 282		if (this instanceof XmppConnectionService.OnAccountUpdate) {
 283			this.xmppConnectionService.setOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this);
 284		}
 285		if (this instanceof XmppConnectionService.OnCaptchaRequested) {
 286			this.xmppConnectionService.setOnCaptchaRequestedListener((XmppConnectionService.OnCaptchaRequested) this);
 287		}
 288		if (this instanceof XmppConnectionService.OnRosterUpdate) {
 289			this.xmppConnectionService.setOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this);
 290		}
 291		if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
 292			this.xmppConnectionService.setOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this);
 293		}
 294		if (this instanceof OnUpdateBlocklist) {
 295			this.xmppConnectionService.setOnUpdateBlocklistListener((OnUpdateBlocklist) this);
 296		}
 297		if (this instanceof XmppConnectionService.OnShowErrorToast) {
 298			this.xmppConnectionService.setOnShowErrorToastListener((XmppConnectionService.OnShowErrorToast) this);
 299		}
 300		if (this instanceof OnKeyStatusUpdated) {
 301			this.xmppConnectionService.setOnKeyStatusUpdatedListener((OnKeyStatusUpdated) this);
 302		}
 303	}
 304
 305	protected void unregisterListeners() {
 306		if (this instanceof XmppConnectionService.OnConversationUpdate) {
 307			this.xmppConnectionService.removeOnConversationListChangedListener();
 308		}
 309		if (this instanceof XmppConnectionService.OnAccountUpdate) {
 310			this.xmppConnectionService.removeOnAccountListChangedListener();
 311		}
 312		if (this instanceof XmppConnectionService.OnCaptchaRequested) {
 313			this.xmppConnectionService.removeOnCaptchaRequestedListener();
 314		}
 315		if (this instanceof XmppConnectionService.OnRosterUpdate) {
 316			this.xmppConnectionService.removeOnRosterUpdateListener();
 317		}
 318		if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
 319			this.xmppConnectionService.removeOnMucRosterUpdateListener();
 320		}
 321		if (this instanceof OnUpdateBlocklist) {
 322			this.xmppConnectionService.removeOnUpdateBlocklistListener();
 323		}
 324		if (this instanceof XmppConnectionService.OnShowErrorToast) {
 325			this.xmppConnectionService.removeOnShowErrorToastListener();
 326		}
 327		if (this instanceof OnKeyStatusUpdated) {
 328			this.xmppConnectionService.removeOnNewKeysAvailableListener();
 329		}
 330	}
 331
 332	@Override
 333	public boolean onOptionsItemSelected(final MenuItem item) {
 334		switch (item.getItemId()) {
 335			case R.id.action_settings:
 336				startActivity(new Intent(this, SettingsActivity.class));
 337				break;
 338			case R.id.action_accounts:
 339				startActivity(new Intent(this, ManageAccountActivity.class));
 340				break;
 341			case android.R.id.home:
 342				finish();
 343				break;
 344			case R.id.action_show_qr_code:
 345				showQrCode();
 346				break;
 347		}
 348		return super.onOptionsItemSelected(item);
 349	}
 350
 351	@Override
 352	protected void onCreate(Bundle savedInstanceState) {
 353		super.onCreate(savedInstanceState);
 354		metrics = getResources().getDisplayMetrics();
 355		ExceptionHelper.init(getApplicationContext());
 356		mPrimaryTextColor = getResources().getColor(R.color.black87);
 357		mSecondaryTextColor = getResources().getColor(R.color.black54);
 358		mTertiaryTextColor = getResources().getColor(R.color.black12);
 359		mColorRed = getResources().getColor(R.color.red800);
 360		mColorOrange = getResources().getColor(R.color.orange500);
 361		mColorGreen = getResources().getColor(R.color.green500);
 362		mPrimaryColor = getResources().getColor(R.color.primary);
 363		mPrimaryBackgroundColor = getResources().getColor(R.color.grey50);
 364		mSecondaryBackgroundColor = getResources().getColor(R.color.grey200);
 365		this.mTheme = findTheme();
 366		setTheme(this.mTheme);
 367		this.mUsingEnterKey = usingEnterKey();
 368		mUseSubject = getPreferences().getBoolean("use_subject", true);
 369		final ActionBar ab = getActionBar();
 370		if (ab!=null) {
 371			ab.setDisplayHomeAsUpEnabled(true);
 372		}
 373	}
 374
 375	protected boolean usingEnterKey() {
 376		return getPreferences().getBoolean("display_enter_key", false);
 377	}
 378
 379	protected SharedPreferences getPreferences() {
 380		return PreferenceManager
 381			.getDefaultSharedPreferences(getApplicationContext());
 382	}
 383
 384	public boolean useSubjectToIdentifyConference() {
 385		return mUseSubject;
 386	}
 387
 388	public void switchToConversation(Conversation conversation) {
 389		switchToConversation(conversation, null, false);
 390	}
 391
 392	public void switchToConversation(Conversation conversation, String text,
 393			boolean newTask) {
 394		switchToConversation(conversation,text,null,false,newTask);
 395	}
 396
 397	public void highlightInMuc(Conversation conversation, String nick) {
 398		switchToConversation(conversation, null, nick, false, false);
 399	}
 400
 401	public void privateMsgInMuc(Conversation conversation, String nick) {
 402		switchToConversation(conversation, null, nick, true, false);
 403	}
 404
 405	private void switchToConversation(Conversation conversation, String text, String nick, boolean pm, boolean newTask) {
 406		Intent viewConversationIntent = new Intent(this,
 407				ConversationActivity.class);
 408		viewConversationIntent.setAction(Intent.ACTION_VIEW);
 409		viewConversationIntent.putExtra(ConversationActivity.CONVERSATION,
 410				conversation.getUuid());
 411		if (text != null) {
 412			viewConversationIntent.putExtra(ConversationActivity.TEXT, text);
 413		}
 414		if (nick != null) {
 415			viewConversationIntent.putExtra(ConversationActivity.NICK, nick);
 416			viewConversationIntent.putExtra(ConversationActivity.PRIVATE_MESSAGE,pm);
 417		}
 418		viewConversationIntent.setType(ConversationActivity.VIEW_CONVERSATION);
 419		if (newTask) {
 420			viewConversationIntent.setFlags(viewConversationIntent.getFlags()
 421					| Intent.FLAG_ACTIVITY_NEW_TASK
 422					| Intent.FLAG_ACTIVITY_SINGLE_TOP);
 423		} else {
 424			viewConversationIntent.setFlags(viewConversationIntent.getFlags()
 425					| Intent.FLAG_ACTIVITY_CLEAR_TOP);
 426		}
 427		startActivity(viewConversationIntent);
 428		finish();
 429	}
 430
 431	public void switchToContactDetails(Contact contact) {
 432		switchToContactDetails(contact, null);
 433	}
 434
 435	public void switchToContactDetails(Contact contact, String messageFingerprint) {
 436		Intent intent = new Intent(this, ContactDetailsActivity.class);
 437		intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
 438		intent.putExtra("account", contact.getAccount().getJid().toBareJid().toString());
 439		intent.putExtra("contact", contact.getJid().toString());
 440		intent.putExtra("fingerprint", messageFingerprint);
 441		startActivity(intent);
 442	}
 443
 444	public void switchToAccount(Account account) {
 445		switchToAccount(account, false);
 446	}
 447
 448	public void switchToAccount(Account account, boolean init) {
 449		Intent intent = new Intent(this, EditAccountActivity.class);
 450		intent.putExtra("jid", account.getJid().toBareJid().toString());
 451		intent.putExtra("init", init);
 452		startActivity(intent);
 453	}
 454
 455	protected void inviteToConversation(Conversation conversation) {
 456		Intent intent = new Intent(getApplicationContext(),
 457				ChooseContactActivity.class);
 458		List<String> contacts = new ArrayList<>();
 459		if (conversation.getMode() == Conversation.MODE_MULTI) {
 460			for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
 461				Jid jid = user.getJid();
 462				if (jid != null) {
 463					contacts.add(jid.toBareJid().toString());
 464				}
 465			}
 466		} else {
 467			contacts.add(conversation.getJid().toBareJid().toString());
 468		}
 469		intent.putExtra("filter_contacts", contacts.toArray(new String[contacts.size()]));
 470		intent.putExtra("conversation", conversation.getUuid());
 471		intent.putExtra("multiple", true);
 472		startActivityForResult(intent, REQUEST_INVITE_TO_CONVERSATION);
 473	}
 474
 475	protected void announcePgp(Account account, final Conversation conversation) {
 476		if (account.getPgpId() == -1) {
 477			choosePgpSignId(account);
 478		} else {
 479			xmppConnectionService.getPgpEngine().generateSignature(account,
 480					"online", new UiCallback<Account>() {
 481
 482				@Override
 483				public void userInputRequried(PendingIntent pi,
 484											  Account account) {
 485					try {
 486						startIntentSenderForResult(pi.getIntentSender(),
 487								REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
 488					} catch (final SendIntentException ignored) {
 489					}
 490				}
 491
 492				@Override
 493				public void success(Account account) {
 494					xmppConnectionService.databaseBackend.updateAccount(account);
 495					xmppConnectionService.sendPresence(account);
 496					if (conversation != null) {
 497						conversation.setNextEncryption(Message.ENCRYPTION_PGP);
 498						xmppConnectionService.databaseBackend.updateConversation(conversation);
 499					}
 500				}
 501
 502				@Override
 503				public void error(int error, Account account) {
 504					displayErrorDialog(error);
 505				}
 506			});
 507		}
 508	}
 509
 510	protected void choosePgpSignId(Account account) {
 511		xmppConnectionService.getPgpEngine().chooseKey(account, new UiCallback<Account>() {
 512			@Override
 513			public void success(Account account1) {
 514			}
 515
 516			@Override
 517			public void error(int errorCode, Account object) {
 518
 519			}
 520
 521			@Override
 522			public void userInputRequried(PendingIntent pi, Account object) {
 523				try {
 524					startIntentSenderForResult(pi.getIntentSender(),
 525							REQUEST_CHOOSE_PGP_ID, null, 0, 0, 0);
 526				} catch (final SendIntentException ignored) {
 527				}
 528			}
 529		});
 530	}
 531
 532	protected void displayErrorDialog(final int errorCode) {
 533		runOnUiThread(new Runnable() {
 534
 535			@Override
 536			public void run() {
 537				AlertDialog.Builder builder = new AlertDialog.Builder(
 538						XmppActivity.this);
 539				builder.setIconAttribute(android.R.attr.alertDialogIcon);
 540				builder.setTitle(getString(R.string.error));
 541				builder.setMessage(errorCode);
 542				builder.setNeutralButton(R.string.accept, null);
 543				builder.create().show();
 544			}
 545		});
 546
 547	}
 548
 549	protected void showAddToRosterDialog(final Conversation conversation) {
 550		showAddToRosterDialog(conversation.getContact());
 551	}
 552
 553	protected void showAddToRosterDialog(final Contact contact) {
 554		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 555		builder.setTitle(contact.getJid().toString());
 556		builder.setMessage(getString(R.string.not_in_roster));
 557		builder.setNegativeButton(getString(R.string.cancel), null);
 558		builder.setPositiveButton(getString(R.string.add_contact),
 559				new DialogInterface.OnClickListener() {
 560
 561					@Override
 562					public void onClick(DialogInterface dialog, int which) {
 563						final Jid jid = contact.getJid();
 564						Account account = contact.getAccount();
 565						Contact contact = account.getRoster().getContact(jid);
 566						xmppConnectionService.createContact(contact);
 567					}
 568				});
 569		builder.create().show();
 570	}
 571
 572	private void showAskForPresenceDialog(final Contact contact) {
 573		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 574		builder.setTitle(contact.getJid().toString());
 575		builder.setMessage(R.string.request_presence_updates);
 576		builder.setNegativeButton(R.string.cancel, null);
 577		builder.setPositiveButton(R.string.request_now,
 578				new DialogInterface.OnClickListener() {
 579
 580					@Override
 581					public void onClick(DialogInterface dialog, int which) {
 582						if (xmppConnectionServiceBound) {
 583							xmppConnectionService.sendPresencePacket(contact
 584									.getAccount(), xmppConnectionService
 585									.getPresenceGenerator()
 586									.requestPresenceUpdatesFrom(contact));
 587						}
 588					}
 589				});
 590		builder.create().show();
 591	}
 592
 593	private void warnMutalPresenceSubscription(final Conversation conversation,
 594			final OnPresenceSelected listener) {
 595		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 596		builder.setTitle(conversation.getContact().getJid().toString());
 597		builder.setMessage(R.string.without_mutual_presence_updates);
 598		builder.setNegativeButton(R.string.cancel, null);
 599		builder.setPositiveButton(R.string.ignore, new OnClickListener() {
 600
 601			@Override
 602			public void onClick(DialogInterface dialog, int which) {
 603				conversation.setNextCounterpart(null);
 604				if (listener != null) {
 605					listener.onPresenceSelected();
 606				}
 607			}
 608		});
 609		builder.create().show();
 610	}
 611
 612	protected void quickEdit(String previousValue, OnValueEdited callback) {
 613		quickEdit(previousValue, callback, false);
 614	}
 615
 616	protected void quickPasswordEdit(String previousValue,
 617			OnValueEdited callback) {
 618		quickEdit(previousValue, callback, true);
 619	}
 620
 621	@SuppressLint("InflateParams")
 622	private void quickEdit(final String previousValue,
 623			final OnValueEdited callback, boolean password) {
 624		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 625		View view = getLayoutInflater().inflate(R.layout.quickedit, null);
 626		final EditText editor = (EditText) view.findViewById(R.id.editor);
 627		OnClickListener mClickListener = new OnClickListener() {
 628
 629			@Override
 630			public void onClick(DialogInterface dialog, int which) {
 631				String value = editor.getText().toString();
 632				if (!previousValue.equals(value) && value.trim().length() > 0) {
 633					callback.onValueEdited(value);
 634				}
 635			}
 636		};
 637		if (password) {
 638			editor.setInputType(InputType.TYPE_CLASS_TEXT
 639					| InputType.TYPE_TEXT_VARIATION_PASSWORD);
 640			editor.setHint(R.string.password);
 641			builder.setPositiveButton(R.string.accept, mClickListener);
 642		} else {
 643			builder.setPositiveButton(R.string.edit, mClickListener);
 644		}
 645		editor.requestFocus();
 646		editor.setText(previousValue);
 647		builder.setView(view);
 648		builder.setNegativeButton(R.string.cancel, null);
 649		builder.create().show();
 650	}
 651
 652	protected boolean addFingerprintRow(LinearLayout keys, final Account account, final String fingerprint, boolean highlight) {
 653		final XmppAxolotlSession.Trust trust = account.getAxolotlService()
 654				.getFingerprintTrust(fingerprint);
 655		if (trust == null) {
 656			return false;
 657		}
 658		return addFingerprintRowWithListeners(keys, account, fingerprint, highlight, trust, true,
 659				new CompoundButton.OnCheckedChangeListener() {
 660					@Override
 661					public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
 662						account.getAxolotlService().setFingerprintTrust(fingerprint,
 663								(isChecked) ? XmppAxolotlSession.Trust.TRUSTED :
 664										XmppAxolotlSession.Trust.UNTRUSTED);
 665					}
 666				},
 667				new View.OnClickListener() {
 668					@Override
 669					public void onClick(View v) {
 670						account.getAxolotlService().setFingerprintTrust(fingerprint,
 671								XmppAxolotlSession.Trust.UNTRUSTED);
 672						v.setEnabled(true);
 673					}
 674				}
 675
 676		);
 677	}
 678
 679	protected boolean addFingerprintRowWithListeners(LinearLayout keys, final Account account,
 680	                                                 final String fingerprint,
 681	                                                 boolean highlight,
 682	                                                 XmppAxolotlSession.Trust trust,
 683	                                                 boolean showTag,
 684	                                                 CompoundButton.OnCheckedChangeListener
 685			                                                 onCheckedChangeListener,
 686	                                                 View.OnClickListener onClickListener) {
 687		if (trust == XmppAxolotlSession.Trust.COMPROMISED) {
 688			return false;
 689		}
 690		View view = getLayoutInflater().inflate(R.layout.contact_key, keys, false);
 691		TextView key = (TextView) view.findViewById(R.id.key);
 692		TextView keyType = (TextView) view.findViewById(R.id.key_type);
 693		Switch trustToggle = (Switch) view.findViewById(R.id.tgl_trust);
 694		trustToggle.setVisibility(View.VISIBLE);
 695		trustToggle.setOnCheckedChangeListener(onCheckedChangeListener);
 696		trustToggle.setOnClickListener(onClickListener);
 697		view.setOnLongClickListener(new View.OnLongClickListener() {
 698			@Override
 699			public boolean onLongClick(View v) {
 700				showPurgeKeyDialog(account, fingerprint);
 701				return true;
 702			}
 703		});
 704		boolean x509 = trust == XmppAxolotlSession.Trust.TRUSTED_X509 || trust == XmppAxolotlSession.Trust.INACTIVE_TRUSTED_X509;
 705		switch (trust) {
 706			case UNTRUSTED:
 707			case TRUSTED:
 708			case TRUSTED_X509:
 709				trustToggle.setChecked(trust.trusted(), false);
 710				trustToggle.setEnabled(trust != XmppAxolotlSession.Trust.TRUSTED_X509);
 711				if (trust == XmppAxolotlSession.Trust.TRUSTED_X509) {
 712					trustToggle.setOnClickListener(null);
 713				}
 714				key.setTextColor(getPrimaryTextColor());
 715				keyType.setTextColor(getSecondaryTextColor());
 716				break;
 717			case UNDECIDED:
 718				trustToggle.setChecked(false, false);
 719				trustToggle.setEnabled(false);
 720				key.setTextColor(getPrimaryTextColor());
 721				keyType.setTextColor(getSecondaryTextColor());
 722				break;
 723			case INACTIVE_UNTRUSTED:
 724			case INACTIVE_UNDECIDED:
 725				trustToggle.setOnClickListener(null);
 726				trustToggle.setChecked(false, false);
 727				trustToggle.setEnabled(false);
 728				key.setTextColor(getTertiaryTextColor());
 729				keyType.setTextColor(getTertiaryTextColor());
 730				break;
 731			case INACTIVE_TRUSTED:
 732			case INACTIVE_TRUSTED_X509:
 733				trustToggle.setOnClickListener(null);
 734				trustToggle.setChecked(true, false);
 735				trustToggle.setEnabled(false);
 736				key.setTextColor(getTertiaryTextColor());
 737				keyType.setTextColor(getTertiaryTextColor());
 738				break;
 739		}
 740
 741		if (showTag) {
 742			keyType.setText(getString(x509 ? R.string.omemo_fingerprint_x509 : R.string.omemo_fingerprint));
 743		} else {
 744			keyType.setVisibility(View.GONE);
 745		}
 746		if (highlight) {
 747			keyType.setTextColor(getResources().getColor(R.color.accent));
 748			keyType.setText(getString(x509 ? R.string.omemo_fingerprint_x509_selected_message : R.string.omemo_fingerprint_selected_message));
 749		} else {
 750			keyType.setText(getString(x509 ? R.string.omemo_fingerprint_x509 : R.string.omemo_fingerprint));
 751		}
 752
 753		key.setText(CryptoHelper.prettifyFingerprint(fingerprint));
 754		keys.addView(view);
 755		return true;
 756	}
 757
 758	public void showPurgeKeyDialog(final Account account, final String fingerprint) {
 759		Builder builder = new Builder(this);
 760		builder.setTitle(getString(R.string.purge_key));
 761		builder.setIconAttribute(android.R.attr.alertDialogIcon);
 762		builder.setMessage(getString(R.string.purge_key_desc_part1)
 763				+ "\n\n" + CryptoHelper.prettifyFingerprint(fingerprint)
 764				+ "\n\n" + getString(R.string.purge_key_desc_part2));
 765		builder.setNegativeButton(getString(R.string.cancel), null);
 766		builder.setPositiveButton(getString(R.string.accept),
 767				new DialogInterface.OnClickListener() {
 768					@Override
 769					public void onClick(DialogInterface dialog, int which) {
 770						account.getAxolotlService().purgeKey(fingerprint);
 771						refreshUi();
 772					}
 773				});
 774		builder.create().show();
 775	}
 776
 777	public void selectPresence(final Conversation conversation,
 778			final OnPresenceSelected listener) {
 779		final Contact contact = conversation.getContact();
 780		if (conversation.hasValidOtrSession()) {
 781			SessionID id = conversation.getOtrSession().getSessionID();
 782			Jid jid;
 783			try {
 784				jid = Jid.fromString(id.getAccountID() + "/" + id.getUserID());
 785			} catch (InvalidJidException e) {
 786				jid = null;
 787			}
 788			conversation.setNextCounterpart(jid);
 789			listener.onPresenceSelected();
 790		} else 	if (!contact.showInRoster()) {
 791			showAddToRosterDialog(conversation);
 792		} else {
 793			Presences presences = contact.getPresences();
 794			if (presences.size() == 0) {
 795				if (!contact.getOption(Contact.Options.TO)
 796						&& !contact.getOption(Contact.Options.ASKING)
 797						&& contact.getAccount().getStatus() == Account.State.ONLINE) {
 798					showAskForPresenceDialog(contact);
 799				} else if (!contact.getOption(Contact.Options.TO)
 800						|| !contact.getOption(Contact.Options.FROM)) {
 801					warnMutalPresenceSubscription(conversation, listener);
 802				} else {
 803					conversation.setNextCounterpart(null);
 804					listener.onPresenceSelected();
 805				}
 806			} else if (presences.size() == 1) {
 807				String presence = presences.asStringArray()[0];
 808				try {
 809					conversation.setNextCounterpart(Jid.fromParts(contact.getJid().getLocalpart(),contact.getJid().getDomainpart(),presence));
 810				} catch (InvalidJidException e) {
 811					conversation.setNextCounterpart(null);
 812				}
 813				listener.onPresenceSelected();
 814			} else {
 815				final StringBuilder presence = new StringBuilder();
 816				AlertDialog.Builder builder = new AlertDialog.Builder(this);
 817				builder.setTitle(getString(R.string.choose_presence));
 818				final String[] presencesArray = presences.asStringArray();
 819				int preselectedPresence = 0;
 820				for (int i = 0; i < presencesArray.length; ++i) {
 821					if (presencesArray[i].equals(contact.lastseen.presence)) {
 822						preselectedPresence = i;
 823						break;
 824					}
 825				}
 826				presence.append(presencesArray[preselectedPresence]);
 827				builder.setSingleChoiceItems(presencesArray,
 828						preselectedPresence,
 829						new DialogInterface.OnClickListener() {
 830
 831							@Override
 832							public void onClick(DialogInterface dialog,
 833									int which) {
 834								presence.delete(0, presence.length());
 835								presence.append(presencesArray[which]);
 836							}
 837						});
 838				builder.setNegativeButton(R.string.cancel, null);
 839				builder.setPositiveButton(R.string.ok, new OnClickListener() {
 840
 841					@Override
 842					public void onClick(DialogInterface dialog, int which) {
 843						try {
 844							conversation.setNextCounterpart(Jid.fromParts(contact.getJid().getLocalpart(),contact.getJid().getDomainpart(),presence.toString()));
 845						} catch (InvalidJidException e) {
 846							conversation.setNextCounterpart(null);
 847						}
 848						listener.onPresenceSelected();
 849					}
 850				});
 851				builder.create().show();
 852			}
 853		}
 854	}
 855
 856	protected void onActivityResult(int requestCode, int resultCode,
 857			final Intent data) {
 858		super.onActivityResult(requestCode, resultCode, data);
 859		if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
 860			mPendingConferenceInvite = ConferenceInvite.parse(data);
 861			if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
 862				mPendingConferenceInvite.execute(this);
 863				mPendingConferenceInvite = null;
 864			}
 865		}
 866	}
 867
 868	private UiCallback<Conversation> adhocCallback = new UiCallback<Conversation>() {
 869		@Override
 870		public void success(final Conversation conversation) {
 871			switchToConversation(conversation);
 872			runOnUiThread(new Runnable() {
 873				@Override
 874				public void run() {
 875					Toast.makeText(XmppActivity.this,R.string.conference_created,Toast.LENGTH_LONG).show();
 876				}
 877			});
 878		}
 879
 880		@Override
 881		public void error(final int errorCode, Conversation object) {
 882			runOnUiThread(new Runnable() {
 883				@Override
 884				public void run() {
 885					Toast.makeText(XmppActivity.this,errorCode,Toast.LENGTH_LONG).show();
 886				}
 887			});
 888		}
 889
 890		@Override
 891		public void userInputRequried(PendingIntent pi, Conversation object) {
 892
 893		}
 894	};
 895
 896	public int getTertiaryTextColor() {
 897		return this.mTertiaryTextColor;
 898	}
 899
 900	public int getSecondaryTextColor() {
 901		return this.mSecondaryTextColor;
 902	}
 903
 904	public int getPrimaryTextColor() {
 905		return this.mPrimaryTextColor;
 906	}
 907
 908	public int getWarningTextColor() {
 909		return this.mColorRed;
 910	}
 911
 912	public int getOnlineColor() {
 913		return this.mColorGreen;
 914	}
 915
 916	public int getPrimaryBackgroundColor() {
 917		return this.mPrimaryBackgroundColor;
 918	}
 919
 920	public int getSecondaryBackgroundColor() {
 921		return this.mSecondaryBackgroundColor;
 922	}
 923
 924	public int getPixel(int dp) {
 925		DisplayMetrics metrics = getResources().getDisplayMetrics();
 926		return ((int) (dp * metrics.density));
 927	}
 928
 929	public boolean copyTextToClipboard(String text, int labelResId) {
 930		ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
 931		String label = getResources().getString(labelResId);
 932		if (mClipBoardManager != null) {
 933			ClipData mClipData = ClipData.newPlainText(label, text);
 934			mClipBoardManager.setPrimaryClip(mClipData);
 935			return true;
 936		}
 937		return false;
 938	}
 939
 940	protected void registerNdefPushMessageCallback() {
 941		NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
 942		if (nfcAdapter != null && nfcAdapter.isEnabled()) {
 943			nfcAdapter.setNdefPushMessageCallback(new NfcAdapter.CreateNdefMessageCallback() {
 944				@Override
 945				public NdefMessage createNdefMessage(NfcEvent nfcEvent) {
 946					return new NdefMessage(new NdefRecord[]{
 947						NdefRecord.createUri(getShareableUri()),
 948							NdefRecord.createApplicationRecord("eu.siacs.conversations")
 949					});
 950				}
 951			}, this);
 952		}
 953	}
 954
 955	protected void unregisterNdefPushMessageCallback() {
 956		NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
 957		if (nfcAdapter != null && nfcAdapter.isEnabled()) {
 958			nfcAdapter.setNdefPushMessageCallback(null,this);
 959		}
 960	}
 961
 962	protected String getShareableUri() {
 963		return null;
 964	}
 965
 966	@Override
 967	public void onResume() {
 968		super.onResume();
 969		if (this.getShareableUri()!=null) {
 970			this.registerNdefPushMessageCallback();
 971		}
 972	}
 973
 974	protected int findTheme() {
 975		if (getPreferences().getBoolean("use_larger_font", false)) {
 976			return R.style.ConversationsTheme_LargerText;
 977		} else {
 978			return R.style.ConversationsTheme;
 979		}
 980	}
 981
 982	@Override
 983	public void onPause() {
 984		super.onPause();
 985		this.unregisterNdefPushMessageCallback();
 986	}
 987
 988	protected void showQrCode() {
 989		String uri = getShareableUri();
 990		if (uri!=null) {
 991			Point size = new Point();
 992			getWindowManager().getDefaultDisplay().getSize(size);
 993			final int width = (size.x < size.y ? size.x : size.y);
 994			Bitmap bitmap = createQrCodeBitmap(uri, width);
 995			ImageView view = new ImageView(this);
 996			view.setImageBitmap(bitmap);
 997			AlertDialog.Builder builder = new AlertDialog.Builder(this);
 998			builder.setView(view);
 999			builder.create().show();
1000		}
1001	}
1002
1003	protected Bitmap createQrCodeBitmap(String input, int size) {
1004		Log.d(Config.LOGTAG,"qr code requested size: "+size);
1005		try {
1006			final QRCodeWriter QR_CODE_WRITER = new QRCodeWriter();
1007			final Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
1008			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
1009			final BitMatrix result = QR_CODE_WRITER.encode(input, BarcodeFormat.QR_CODE, size, size, hints);
1010			final int width = result.getWidth();
1011			final int height = result.getHeight();
1012			final int[] pixels = new int[width * height];
1013			for (int y = 0; y < height; y++) {
1014				final int offset = y * width;
1015				for (int x = 0; x < width; x++) {
1016					pixels[offset + x] = result.get(x, y) ? Color.BLACK : Color.TRANSPARENT;
1017				}
1018			}
1019			final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
1020			Log.d(Config.LOGTAG,"output size: "+width+"x"+height);
1021			bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
1022			return bitmap;
1023		} catch (final WriterException e) {
1024			return null;
1025		}
1026	}
1027
1028	public static class ConferenceInvite {
1029		private String uuid;
1030		private List<Jid> jids = new ArrayList<>();
1031
1032		public static ConferenceInvite parse(Intent data) {
1033			ConferenceInvite invite = new ConferenceInvite();
1034			invite.uuid = data.getStringExtra("conversation");
1035			if (invite.uuid == null) {
1036				return null;
1037			}
1038			try {
1039				if (data.getBooleanExtra("multiple", false)) {
1040					String[] toAdd = data.getStringArrayExtra("contacts");
1041					for (String item : toAdd) {
1042						invite.jids.add(Jid.fromString(item));
1043					}
1044				} else {
1045					invite.jids.add(Jid.fromString(data.getStringExtra("contact")));
1046				}
1047			} catch (final InvalidJidException ignored) {
1048				return null;
1049			}
1050			return invite;
1051		}
1052
1053		public void execute(XmppActivity activity) {
1054			XmppConnectionService service = activity.xmppConnectionService;
1055			Conversation conversation = service.findConversationByUuid(this.uuid);
1056			if (conversation == null) {
1057				return;
1058			}
1059			if (conversation.getMode() == Conversation.MODE_MULTI) {
1060				for (Jid jid : jids) {
1061					service.invite(conversation, jid);
1062				}
1063			} else {
1064				jids.add(conversation.getJid().toBareJid());
1065				service.createAdhocConference(conversation.getAccount(), jids, activity.adhocCallback);
1066			}
1067		}
1068	}
1069
1070	public AvatarService avatarService() {
1071		return xmppConnectionService.getAvatarService();
1072	}
1073
1074	class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
1075		private final WeakReference<ImageView> imageViewReference;
1076		private Message message = null;
1077
1078		public BitmapWorkerTask(ImageView imageView) {
1079			imageViewReference = new WeakReference<>(imageView);
1080		}
1081
1082		@Override
1083		protected Bitmap doInBackground(Message... params) {
1084			message = params[0];
1085			try {
1086				return xmppConnectionService.getFileBackend().getThumbnail(
1087						message, (int) (metrics.density * 288), false);
1088			} catch (FileNotFoundException e) {
1089				return null;
1090			}
1091		}
1092
1093		@Override
1094		protected void onPostExecute(Bitmap bitmap) {
1095			if (bitmap != null) {
1096				final ImageView imageView = imageViewReference.get();
1097				if (imageView != null) {
1098					imageView.setImageBitmap(bitmap);
1099					imageView.setBackgroundColor(0x00000000);
1100				}
1101			}
1102		}
1103	}
1104
1105	public void loadBitmap(Message message, ImageView imageView) {
1106		Bitmap bm;
1107		try {
1108			bm = xmppConnectionService.getFileBackend().getThumbnail(message,
1109					(int) (metrics.density * 288), true);
1110		} catch (FileNotFoundException e) {
1111			bm = null;
1112		}
1113		if (bm != null) {
1114			imageView.setImageBitmap(bm);
1115			imageView.setBackgroundColor(0x00000000);
1116		} else {
1117			if (cancelPotentialWork(message, imageView)) {
1118				imageView.setBackgroundColor(0xff333333);
1119				final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
1120				final AsyncDrawable asyncDrawable = new AsyncDrawable(
1121						getResources(), null, task);
1122				imageView.setImageDrawable(asyncDrawable);
1123				try {
1124					task.execute(message);
1125				} catch (final RejectedExecutionException ignored) {
1126				}
1127			}
1128		}
1129	}
1130
1131	public static boolean cancelPotentialWork(Message message,
1132			ImageView imageView) {
1133		final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
1134
1135		if (bitmapWorkerTask != null) {
1136			final Message oldMessage = bitmapWorkerTask.message;
1137			if (oldMessage == null || message != oldMessage) {
1138				bitmapWorkerTask.cancel(true);
1139			} else {
1140				return false;
1141			}
1142		}
1143		return true;
1144	}
1145
1146	private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
1147		if (imageView != null) {
1148			final Drawable drawable = imageView.getDrawable();
1149			if (drawable instanceof AsyncDrawable) {
1150				final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
1151				return asyncDrawable.getBitmapWorkerTask();
1152			}
1153		}
1154		return null;
1155	}
1156
1157	static class AsyncDrawable extends BitmapDrawable {
1158		private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
1159
1160		public AsyncDrawable(Resources res, Bitmap bitmap,
1161				BitmapWorkerTask bitmapWorkerTask) {
1162			super(res, bitmap);
1163			bitmapWorkerTaskReference = new WeakReference<>(
1164					bitmapWorkerTask);
1165		}
1166
1167		public BitmapWorkerTask getBitmapWorkerTask() {
1168			return bitmapWorkerTaskReference.get();
1169		}
1170	}
1171}