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