XmppActivity.java

  1package eu.siacs.conversations.ui;
  2
  3import android.Manifest;
  4import android.annotation.SuppressLint;
  5import android.annotation.TargetApi;
  6import android.app.PendingIntent;
  7import android.content.ActivityNotFoundException;
  8import android.content.ClipData;
  9import android.content.ClipboardManager;
 10import android.content.ComponentName;
 11import android.content.Context;
 12import android.content.DialogInterface;
 13import android.content.Intent;
 14import android.content.IntentSender.SendIntentException;
 15import android.content.ServiceConnection;
 16import android.content.SharedPreferences;
 17import android.content.pm.PackageManager;
 18import android.content.pm.ResolveInfo;
 19import android.content.res.Resources;
 20import android.content.res.TypedArray;
 21import android.databinding.DataBindingUtil;
 22import android.graphics.Bitmap;
 23import android.graphics.Color;
 24import android.graphics.Point;
 25import android.graphics.drawable.BitmapDrawable;
 26import android.graphics.drawable.Drawable;
 27import android.net.ConnectivityManager;
 28import android.net.Uri;
 29import android.os.AsyncTask;
 30import android.os.Build;
 31import android.os.Bundle;
 32import android.os.Handler;
 33import android.os.IBinder;
 34import android.os.PowerManager;
 35import android.os.SystemClock;
 36import android.preference.PreferenceManager;
 37import android.support.annotation.BoolRes;
 38import android.support.annotation.StringRes;
 39import android.support.v4.content.ContextCompat;
 40import android.support.v7.app.AlertDialog;
 41import android.support.v7.app.AlertDialog.Builder;
 42import android.support.v7.app.AppCompatDelegate;
 43import android.text.InputType;
 44import android.util.DisplayMetrics;
 45import android.util.Log;
 46import android.view.Menu;
 47import android.view.MenuItem;
 48import android.view.View;
 49import android.widget.EditText;
 50import android.widget.ImageView;
 51import android.widget.Toast;
 52
 53import java.io.IOException;
 54import java.lang.ref.WeakReference;
 55import java.util.ArrayList;
 56import java.util.List;
 57import java.util.concurrent.RejectedExecutionException;
 58import java.util.concurrent.atomic.AtomicBoolean;
 59
 60import eu.siacs.conversations.Config;
 61import eu.siacs.conversations.R;
 62import eu.siacs.conversations.crypto.PgpEngine;
 63import eu.siacs.conversations.databinding.DialogQuickeditBinding;
 64import eu.siacs.conversations.entities.Account;
 65import eu.siacs.conversations.entities.Contact;
 66import eu.siacs.conversations.entities.Conversation;
 67import eu.siacs.conversations.entities.Message;
 68import eu.siacs.conversations.entities.Presences;
 69import eu.siacs.conversations.services.AvatarService;
 70import eu.siacs.conversations.services.BarcodeProvider;
 71import eu.siacs.conversations.services.XmppConnectionService;
 72import eu.siacs.conversations.services.XmppConnectionService.XmppConnectionBinder;
 73import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
 74import eu.siacs.conversations.ui.util.PresenceSelector;
 75import eu.siacs.conversations.ui.util.SoftKeyboardUtils;
 76import eu.siacs.conversations.utils.ExceptionHelper;
 77import eu.siacs.conversations.utils.ThemeHelper;
 78import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
 79import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
 80import rocks.xmpp.addr.Jid;
 81
 82public abstract class XmppActivity extends ActionBarActivity {
 83
 84	public static final String EXTRA_ACCOUNT = "account";
 85	protected static final int REQUEST_ANNOUNCE_PGP = 0x0101;
 86	protected static final int REQUEST_INVITE_TO_CONVERSATION = 0x0102;
 87	protected static final int REQUEST_CHOOSE_PGP_ID = 0x0103;
 88	protected static final int REQUEST_BATTERY_OP = 0x49ff;
 89	public XmppConnectionService xmppConnectionService;
 90	public boolean xmppConnectionServiceBound = false;
 91
 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				startActivity(new Intent(this, ManageAccountActivity.class));
342				break;
343			case android.R.id.home:
344				finish();
345				break;
346			case R.id.action_show_qr_code:
347				showQrCode();
348				break;
349		}
350		return super.onOptionsItemSelected(item);
351	}
352
353	public void selectPresence(final Conversation conversation, final PresenceSelector.OnPresenceSelected listener) {
354		final Contact contact = conversation.getContact();
355		if (!contact.showInRoster()) {
356			showAddToRosterDialog(conversation.getContact());
357		} else {
358			final Presences presences = contact.getPresences();
359			if (presences.size() == 0) {
360				if (!contact.getOption(Contact.Options.TO)
361						&& !contact.getOption(Contact.Options.ASKING)
362						&& contact.getAccount().getStatus() == Account.State.ONLINE) {
363					showAskForPresenceDialog(contact);
364				} else if (!contact.getOption(Contact.Options.TO)
365						|| !contact.getOption(Contact.Options.FROM)) {
366					PresenceSelector.warnMutualPresenceSubscription(this, conversation, listener);
367				} else {
368					conversation.setNextCounterpart(null);
369					listener.onPresenceSelected();
370				}
371			} else if (presences.size() == 1) {
372				String presence = presences.toResourceArray()[0];
373				try {
374					conversation.setNextCounterpart(Jid.of(contact.getJid().getLocal(), contact.getJid().getDomain(), presence));
375				} catch (IllegalArgumentException e) {
376					conversation.setNextCounterpart(null);
377				}
378				listener.onPresenceSelected();
379			} else {
380				PresenceSelector.showPresenceSelectionDialog(this, conversation, listener);
381			}
382		}
383	}
384
385	@Override
386	protected void onCreate(Bundle savedInstanceState) {
387		super.onCreate(savedInstanceState);
388		metrics = getResources().getDisplayMetrics();
389		ExceptionHelper.init(getApplicationContext());
390		this.isCameraFeatureAvailable = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
391
392		mColorRed = ContextCompat.getColor(this, R.color.red800);
393
394		this.mTheme = findTheme();
395		setTheme(this.mTheme);
396
397		this.mUsingEnterKey = usingEnterKey();
398	}
399
400	protected boolean isCameraFeatureAvailable() {
401		return this.isCameraFeatureAvailable;
402	}
403
404	public boolean isDarkTheme() {
405		return ThemeHelper.isDark(mTheme);
406	}
407
408	public int getThemeResource(int r_attr_name, int r_drawable_def) {
409		int[] attrs = {r_attr_name};
410		TypedArray ta = this.getTheme().obtainStyledAttributes(attrs);
411
412		int res = ta.getResourceId(0, r_drawable_def);
413		ta.recycle();
414
415		return res;
416	}
417
418	protected boolean isOptimizingBattery() {
419		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
420			final PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
421			return pm != null
422					&& !pm.isIgnoringBatteryOptimizations(getPackageName());
423		} else {
424			return false;
425		}
426	}
427
428	protected boolean isAffectedByDataSaver() {
429		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
430			final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
431			return cm != null
432					&& cm.isActiveNetworkMetered()
433					&& cm.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
434		} else {
435			return false;
436		}
437	}
438
439	protected boolean usingEnterKey() {
440		return getBooleanPreference("display_enter_key", R.bool.display_enter_key);
441	}
442
443	protected SharedPreferences getPreferences() {
444		return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
445	}
446
447	protected boolean getBooleanPreference(String name, @BoolRes int res) {
448		return getPreferences().getBoolean(name, getResources().getBoolean(res));
449	}
450
451	public void switchToConversation(Conversation conversation) {
452		switchToConversation(conversation, null, false);
453	}
454
455	public void switchToConversationAndQuote(Conversation conversation, String text) {
456		switchToConversation(conversation, text, true, null, false, false);
457	}
458
459	public void switchToConversation(Conversation conversation, String text, boolean newTask) {
460		switchToConversation(conversation, text, false, null, false, newTask);
461	}
462
463	public void highlightInMuc(Conversation conversation, String nick) {
464		switchToConversation(conversation, null, false, nick, false, false);
465	}
466
467	public void privateMsgInMuc(Conversation conversation, String nick) {
468		switchToConversation(conversation, null, false, nick, true, false);
469	}
470
471	private void switchToConversation(Conversation conversation, String text, boolean asQuote, String nick, boolean pm, boolean newTask) {
472		Intent intent = new Intent(this, ConversationsActivity.class);
473		intent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
474		intent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid());
475		if (text != null) {
476			intent.putExtra(ConversationsActivity.EXTRA_TEXT, text);
477			if (asQuote) {
478				intent.putExtra(ConversationsActivity.EXTRA_AS_QUOTE, asQuote);
479			}
480		}
481		if (nick != null) {
482			intent.putExtra(ConversationsActivity.EXTRA_NICK, nick);
483			intent.putExtra(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, pm);
484		}
485		if (newTask) {
486			intent.setFlags(intent.getFlags()
487					| Intent.FLAG_ACTIVITY_NEW_TASK
488					| Intent.FLAG_ACTIVITY_SINGLE_TOP);
489		} else {
490			intent.setFlags(intent.getFlags()
491					| Intent.FLAG_ACTIVITY_CLEAR_TOP);
492		}
493		startActivity(intent);
494		finish();
495	}
496
497	public void switchToContactDetails(Contact contact) {
498		switchToContactDetails(contact, null);
499	}
500
501	public void switchToContactDetails(Contact contact, String messageFingerprint) {
502		Intent intent = new Intent(this, ContactDetailsActivity.class);
503		intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
504		intent.putExtra(EXTRA_ACCOUNT, contact.getAccount().getJid().asBareJid().toString());
505		intent.putExtra("contact", contact.getJid().toString());
506		intent.putExtra("fingerprint", messageFingerprint);
507		startActivity(intent);
508	}
509
510	public void switchToAccount(Account account, String fingerprint) {
511		switchToAccount(account, false, fingerprint);
512	}
513
514	public void switchToAccount(Account account) {
515		switchToAccount(account, false, null);
516	}
517
518	public void switchToAccount(Account account, boolean init, String fingerprint) {
519		Intent intent = new Intent(this, EditAccountActivity.class);
520		intent.putExtra("jid", account.getJid().asBareJid().toString());
521		intent.putExtra("init", init);
522		if (init) {
523			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
524		}
525		if (fingerprint != null) {
526			intent.putExtra("fingerprint", fingerprint);
527		}
528		startActivity(intent);
529		if (init) {
530			overridePendingTransition(0, 0);
531		}
532	}
533
534	protected void delegateUriPermissionsToService(Uri uri) {
535		Intent intent = new Intent(this,XmppConnectionService.class);
536		intent.setAction(Intent.ACTION_SEND);
537		intent.setData(uri);
538		intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
539		startService(intent);
540	}
541
542	protected void inviteToConversation(Conversation conversation) {
543		startActivityForResult(ChooseContactActivity.create(this,conversation), REQUEST_INVITE_TO_CONVERSATION);
544	}
545
546	protected void announcePgp(final Account account, final Conversation conversation, Intent intent, final Runnable onSuccess) {
547		if (account.getPgpId() == 0) {
548			choosePgpSignId(account);
549		} else {
550			String status = null;
551			if (manuallyChangePresence()) {
552				status = account.getPresenceStatusMessage();
553			}
554			if (status == null) {
555				status = "";
556			}
557			xmppConnectionService.getPgpEngine().generateSignature(intent, account, status, new UiCallback<String>() {
558
559				@Override
560				public void userInputRequried(PendingIntent pi, String signature) {
561					try {
562						startIntentSenderForResult(pi.getIntentSender(), REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
563					} catch (final SendIntentException ignored) {
564					}
565				}
566
567				@Override
568				public void success(String signature) {
569					account.setPgpSignature(signature);
570					xmppConnectionService.databaseBackend.updateAccount(account);
571					xmppConnectionService.sendPresence(account);
572					if (conversation != null) {
573						conversation.setNextEncryption(Message.ENCRYPTION_PGP);
574						xmppConnectionService.updateConversation(conversation);
575						refreshUi();
576					}
577					if (onSuccess != null) {
578						runOnUiThread(onSuccess);
579					}
580				}
581
582				@Override
583				public void error(int error, String signature) {
584					if (error == 0) {
585						account.setPgpSignId(0);
586						account.unsetPgpSignature();
587						xmppConnectionService.databaseBackend.updateAccount(account);
588						choosePgpSignId(account);
589					} else {
590						displayErrorDialog(error);
591					}
592				}
593			});
594		}
595	}
596
597	protected boolean noAccountUsesPgp() {
598		if (!hasPgp()) {
599			return true;
600		}
601		for (Account account : xmppConnectionService.getAccounts()) {
602			if (account.getPgpId() != 0) {
603				return false;
604			}
605		}
606		return true;
607	}
608
609	@SuppressWarnings("deprecation")
610	@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
611	protected void setListItemBackgroundOnView(View view) {
612		int sdk = android.os.Build.VERSION.SDK_INT;
613		if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
614			view.setBackgroundDrawable(getResources().getDrawable(R.drawable.greybackground));
615		} else {
616			view.setBackground(getResources().getDrawable(R.drawable.greybackground));
617		}
618	}
619
620	protected void choosePgpSignId(Account account) {
621		xmppConnectionService.getPgpEngine().chooseKey(account, new UiCallback<Account>() {
622			@Override
623			public void success(Account account1) {
624			}
625
626			@Override
627			public void error(int errorCode, Account object) {
628
629			}
630
631			@Override
632			public void userInputRequried(PendingIntent pi, Account object) {
633				try {
634					startIntentSenderForResult(pi.getIntentSender(),
635							REQUEST_CHOOSE_PGP_ID, null, 0, 0, 0);
636				} catch (final SendIntentException ignored) {
637				}
638			}
639		});
640	}
641
642	protected void displayErrorDialog(final int errorCode) {
643		runOnUiThread(() -> {
644			Builder builder = new Builder(XmppActivity.this);
645			builder.setIconAttribute(android.R.attr.alertDialogIcon);
646			builder.setTitle(getString(R.string.error));
647			builder.setMessage(errorCode);
648			builder.setNeutralButton(R.string.accept, null);
649			builder.create().show();
650		});
651
652	}
653
654	protected void showAddToRosterDialog(final Contact contact) {
655		AlertDialog.Builder builder = new AlertDialog.Builder(this);
656		builder.setTitle(contact.getJid().toString());
657		builder.setMessage(getString(R.string.not_in_roster));
658		builder.setNegativeButton(getString(R.string.cancel), null);
659		builder.setPositiveButton(getString(R.string.add_contact), (dialog, which) -> xmppConnectionService.createContact(contact,true));
660		builder.create().show();
661	}
662
663	private void showAskForPresenceDialog(final Contact contact) {
664		AlertDialog.Builder builder = new AlertDialog.Builder(this);
665		builder.setTitle(contact.getJid().toString());
666		builder.setMessage(R.string.request_presence_updates);
667		builder.setNegativeButton(R.string.cancel, null);
668		builder.setPositiveButton(R.string.request_now,
669				(dialog, which) -> {
670					if (xmppConnectionServiceBound) {
671						xmppConnectionService.sendPresencePacket(contact
672								.getAccount(), xmppConnectionService
673								.getPresenceGenerator()
674								.requestPresenceUpdatesFrom(contact));
675					}
676				});
677		builder.create().show();
678	}
679
680	protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback) {
681		quickEdit(previousValue, callback, hint, false, false);
682	}
683
684	protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback, boolean permitEmpty) {
685		quickEdit(previousValue, callback, hint, false, permitEmpty);
686	}
687
688	protected void quickPasswordEdit(String previousValue, OnValueEdited callback) {
689		quickEdit(previousValue, callback, R.string.password, true, false);
690	}
691
692	@SuppressLint("InflateParams")
693	private void quickEdit(final String previousValue,
694	                       final OnValueEdited callback,
695	                       final @StringRes int hint,
696	                       boolean password,
697	                       boolean permitEmpty) {
698		AlertDialog.Builder builder = new AlertDialog.Builder(this);
699		DialogQuickeditBinding binding = DataBindingUtil.inflate(getLayoutInflater(),R.layout.dialog_quickedit, null, false);
700		if (password) {
701			binding.inputEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
702		}
703		builder.setPositiveButton(R.string.accept, null);
704		if (hint != 0) {
705			binding.inputLayout.setHint(getString(hint));
706		}
707		binding.inputEditText.requestFocus();
708		if (previousValue != null) {
709			binding.inputEditText.getText().append(previousValue);
710		}
711		builder.setView(binding.getRoot());
712		builder.setNegativeButton(R.string.cancel, null);
713		final AlertDialog dialog = builder.create();
714		dialog.setOnShowListener(d -> SoftKeyboardUtils.showKeyboard(binding.inputEditText));
715		dialog.show();
716		View.OnClickListener clickListener = v -> {
717			String value = binding.inputEditText.getText().toString();
718			if (!value.equals(previousValue) && (!value.trim().isEmpty() || permitEmpty)) {
719				String error = callback.onValueEdited(value);
720				if (error != null) {
721					binding.inputLayout.setError(error);
722					return;
723				}
724			}
725			SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
726			dialog.dismiss();
727		};
728		dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(clickListener);
729		dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setOnClickListener((v -> {
730			SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
731			dialog.dismiss();
732		}));
733		dialog.setOnDismissListener(dialog1 -> {
734			SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
735        });
736	}
737
738	protected boolean hasStoragePermission(int requestCode) {
739		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
740			if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
741				requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
742				return false;
743			} else {
744				return true;
745			}
746		} else {
747			return true;
748		}
749	}
750
751	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
752		super.onActivityResult(requestCode, resultCode, data);
753		if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
754			mPendingConferenceInvite = ConferenceInvite.parse(data);
755			if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
756				if (mPendingConferenceInvite.execute(this)) {
757					mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
758					mToast.show();
759				}
760				mPendingConferenceInvite = null;
761			}
762		}
763	}
764
765	public int getWarningTextColor() {
766		return this.mColorRed;
767	}
768
769	public int getPixel(int dp) {
770		DisplayMetrics metrics = getResources().getDisplayMetrics();
771		return ((int) (dp * metrics.density));
772	}
773
774	public boolean copyTextToClipboard(String text, int labelResId) {
775		ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
776		String label = getResources().getString(labelResId);
777		if (mClipBoardManager != null) {
778			ClipData mClipData = ClipData.newPlainText(label, text);
779			mClipBoardManager.setPrimaryClip(mClipData);
780			return true;
781		}
782		return false;
783	}
784
785	protected boolean neverCompressPictures() {
786		return getPreferences().getString("picture_compression", getResources().getString(R.string.picture_compression)).equals("never");
787	}
788
789	protected boolean manuallyChangePresence() {
790		return getBooleanPreference(SettingsActivity.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
791	}
792
793	protected String getShareableUri() {
794		return getShareableUri(false);
795	}
796
797	protected String getShareableUri(boolean http) {
798		return null;
799	}
800
801	protected void shareLink(boolean http) {
802		String uri = getShareableUri(http);
803		if (uri == null || uri.isEmpty()) {
804			return;
805		}
806		Intent intent = new Intent(Intent.ACTION_SEND);
807		intent.setType("text/plain");
808		intent.putExtra(Intent.EXTRA_TEXT, getShareableUri(http));
809		try {
810			startActivity(Intent.createChooser(intent, getText(R.string.share_uri_with)));
811		} catch (ActivityNotFoundException e) {
812			Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
813		}
814	}
815
816	protected void launchOpenKeyChain(long keyId) {
817		PgpEngine pgp = XmppActivity.this.xmppConnectionService.getPgpEngine();
818		try {
819			startIntentSenderForResult(
820					pgp.getIntentForKey(keyId).getIntentSender(), 0, null, 0,
821					0, 0);
822		} catch (Throwable e) {
823			Toast.makeText(XmppActivity.this, R.string.openpgp_error, Toast.LENGTH_SHORT).show();
824		}
825	}
826
827	@Override
828	public void onResume() {
829		super.onResume();
830	}
831
832	protected int findTheme() {
833		return ThemeHelper.find(this);
834	}
835
836	@Override
837	public void onPause() {
838		super.onPause();
839	}
840
841	@Override
842	public boolean onMenuOpened(int id, Menu menu) {
843		if(id == AppCompatDelegate.FEATURE_SUPPORT_ACTION_BAR && menu != null) {
844			MenuDoubleTabUtil.recordMenuOpen();
845		}
846		return super.onMenuOpened(id, menu);
847	}
848
849	protected void showQrCode() {
850		showQrCode(getShareableUri());
851	}
852
853	protected void showQrCode(final String uri) {
854		if (uri == null || uri.isEmpty()) {
855			return;
856		}
857		Point size = new Point();
858		getWindowManager().getDefaultDisplay().getSize(size);
859		final int width = (size.x < size.y ? size.x : size.y);
860		Bitmap bitmap = BarcodeProvider.create2dBarcodeBitmap(uri, width);
861		ImageView view = new ImageView(this);
862		view.setBackgroundColor(Color.WHITE);
863		view.setImageBitmap(bitmap);
864		AlertDialog.Builder builder = new AlertDialog.Builder(this);
865		builder.setView(view);
866		builder.create().show();
867	}
868
869	protected Account extractAccount(Intent intent) {
870		String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null;
871		try {
872			return jid != null ? xmppConnectionService.findAccountByJid(Jid.of(jid)) : null;
873		} catch (IllegalArgumentException e) {
874			return null;
875		}
876	}
877
878	public AvatarService avatarService() {
879		return xmppConnectionService.getAvatarService();
880	}
881
882	public void loadBitmap(Message message, ImageView imageView) {
883		Bitmap bm;
884		try {
885			bm = xmppConnectionService.getFileBackend().getThumbnail(message, (int) (metrics.density * 288), true);
886		} catch (IOException e) {
887			bm = null;
888		}
889		if (bm != null) {
890			cancelPotentialWork(message, imageView);
891			imageView.setImageBitmap(bm);
892			imageView.setBackgroundColor(0x00000000);
893		} else {
894			if (cancelPotentialWork(message, imageView)) {
895				imageView.setBackgroundColor(0xff333333);
896				imageView.setImageDrawable(null);
897				final BitmapWorkerTask task = new BitmapWorkerTask(this, imageView);
898				final AsyncDrawable asyncDrawable = new AsyncDrawable(
899						getResources(), null, task);
900				imageView.setImageDrawable(asyncDrawable);
901				try {
902					task.execute(message);
903				} catch (final RejectedExecutionException ignored) {
904					ignored.printStackTrace();
905				}
906			}
907		}
908	}
909
910	protected interface OnValueEdited {
911		String onValueEdited(String value);
912	}
913
914	public static class ConferenceInvite {
915		private String uuid;
916		private List<Jid> jids = new ArrayList<>();
917
918		public static ConferenceInvite parse(Intent data) {
919			ConferenceInvite invite = new ConferenceInvite();
920			invite.uuid = data.getStringExtra(ChooseContactActivity.EXTRA_CONVERSATION);
921			if (invite.uuid == null) {
922				return null;
923			}
924			invite.jids.addAll(ChooseContactActivity.extractJabberIds(data));
925			return invite;
926		}
927
928		public boolean execute(XmppActivity activity) {
929			XmppConnectionService service = activity.xmppConnectionService;
930			Conversation conversation = service.findConversationByUuid(this.uuid);
931			if (conversation == null) {
932				return false;
933			}
934			if (conversation.getMode() == Conversation.MODE_MULTI) {
935				for (Jid jid : jids) {
936					service.invite(conversation, jid);
937				}
938				return false;
939			} else {
940				jids.add(conversation.getJid().asBareJid());
941				return service.createAdhocConference(conversation.getAccount(), null, jids, activity.adhocCallback);
942			}
943		}
944	}
945
946	static class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
947		private final WeakReference<ImageView> imageViewReference;
948		private final WeakReference<XmppActivity> activity;
949		private Message message = null;
950
951		private BitmapWorkerTask(XmppActivity activity, ImageView imageView) {
952			this.activity = new WeakReference<>(activity);
953			this.imageViewReference = new WeakReference<>(imageView);
954		}
955
956		@Override
957		protected Bitmap doInBackground(Message... params) {
958			if (isCancelled()) {
959				return null;
960			}
961			message = params[0];
962			try {
963				XmppActivity activity = this.activity.get();
964				if (activity != null && activity.xmppConnectionService != null) {
965					return activity.xmppConnectionService.getFileBackend().getThumbnail(message, (int) (activity.metrics.density * 288), false);
966				} else {
967					return null;
968				}
969			} catch (IOException e) {
970				return null;
971			}
972		}
973
974		@Override
975		protected void onPostExecute(Bitmap bitmap) {
976			if (bitmap != null && !isCancelled()) {
977				final ImageView imageView = imageViewReference.get();
978				if (imageView != null) {
979					imageView.setImageBitmap(bitmap);
980					imageView.setBackgroundColor(0x00000000);
981				}
982			}
983		}
984	}
985
986	private static class AsyncDrawable extends BitmapDrawable {
987		private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
988
989		private AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
990			super(res, bitmap);
991			bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
992		}
993
994		private BitmapWorkerTask getBitmapWorkerTask() {
995			return bitmapWorkerTaskReference.get();
996		}
997	}
998}