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