XmppActivity.java

  1package eu.siacs.conversations.ui;
  2
  3import java.io.FileNotFoundException;
  4import java.lang.ref.WeakReference;
  5import java.util.concurrent.RejectedExecutionException;
  6
  7import eu.siacs.conversations.Config;
  8import eu.siacs.conversations.R;
  9import eu.siacs.conversations.entities.Account;
 10import eu.siacs.conversations.entities.Contact;
 11import eu.siacs.conversations.entities.Conversation;
 12import eu.siacs.conversations.entities.Message;
 13import eu.siacs.conversations.entities.Presences;
 14import eu.siacs.conversations.services.XmppConnectionService;
 15import eu.siacs.conversations.services.XmppConnectionService.XmppConnectionBinder;
 16import eu.siacs.conversations.utils.ExceptionHelper;
 17import android.app.Activity;
 18import android.app.AlertDialog;
 19import android.app.PendingIntent;
 20import android.app.AlertDialog.Builder;
 21import android.content.ComponentName;
 22import android.content.Context;
 23import android.content.DialogInterface;
 24import android.content.DialogInterface.OnClickListener;
 25import android.content.IntentSender.SendIntentException;
 26import android.content.res.Resources;
 27import android.content.Intent;
 28import android.content.ServiceConnection;
 29import android.graphics.Bitmap;
 30import android.graphics.drawable.BitmapDrawable;
 31import android.graphics.drawable.Drawable;
 32import android.net.Uri;
 33import android.os.AsyncTask;
 34import android.os.Bundle;
 35import android.os.IBinder;
 36import android.text.InputType;
 37import android.util.DisplayMetrics;
 38import android.util.Log;
 39import android.view.MenuItem;
 40import android.view.View;
 41import android.view.inputmethod.InputMethodManager;
 42import android.widget.EditText;
 43import android.widget.ImageView;
 44
 45public abstract class XmppActivity extends Activity {
 46
 47	protected static final int REQUEST_ANNOUNCE_PGP = 0x0101;
 48	protected static final int REQUEST_INVITE_TO_CONVERSATION = 0x0102;
 49
 50	public XmppConnectionService xmppConnectionService;
 51	public boolean xmppConnectionServiceBound = false;
 52	protected boolean handledViewIntent = false;
 53
 54	protected int mPrimaryTextColor;
 55	protected int mSecondaryTextColor;
 56	protected int mWarningTextColor;
 57	protected int mPrimaryColor;
 58
 59	private DisplayMetrics metrics;
 60
 61	protected interface OnValueEdited {
 62		public void onValueEdited(String value);
 63	}
 64
 65	public interface OnPresenceSelected {
 66		public void onPresenceSelected();
 67	}
 68
 69	protected ServiceConnection mConnection = new ServiceConnection() {
 70
 71		@Override
 72		public void onServiceConnected(ComponentName className, IBinder service) {
 73			XmppConnectionBinder binder = (XmppConnectionBinder) service;
 74			xmppConnectionService = binder.getService();
 75			xmppConnectionServiceBound = true;
 76			onBackendConnected();
 77		}
 78
 79		@Override
 80		public void onServiceDisconnected(ComponentName arg0) {
 81			xmppConnectionServiceBound = false;
 82		}
 83	};
 84
 85	@Override
 86	protected void onStart() {
 87		super.onStart();
 88		if (!xmppConnectionServiceBound) {
 89			connectToBackend();
 90		}
 91	}
 92
 93	public void connectToBackend() {
 94		Intent intent = new Intent(this, XmppConnectionService.class);
 95		intent.setAction("ui");
 96		startService(intent);
 97		bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
 98	}
 99
100	@Override
101	protected void onStop() {
102		super.onStop();
103		if (xmppConnectionServiceBound) {
104			unbindService(mConnection);
105			xmppConnectionServiceBound = false;
106		}
107	}
108
109	protected void hideKeyboard() {
110		InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
111
112		View focus = getCurrentFocus();
113
114		if (focus != null) {
115
116			inputManager.hideSoftInputFromWindow(focus.getWindowToken(),
117					InputMethodManager.HIDE_NOT_ALWAYS);
118		}
119	}
120
121	public boolean hasPgp() {
122		return xmppConnectionService.getPgpEngine() != null;
123	}
124
125	public void showInstallPgpDialog() {
126		Builder builder = new AlertDialog.Builder(this);
127		builder.setTitle(getString(R.string.openkeychain_required));
128		builder.setIconAttribute(android.R.attr.alertDialogIcon);
129		builder.setMessage(getText(R.string.openkeychain_required_long));
130		builder.setNegativeButton(getString(R.string.cancel), null);
131		builder.setNeutralButton(getString(R.string.restart),
132				new OnClickListener() {
133
134					@Override
135					public void onClick(DialogInterface dialog, int which) {
136						if (xmppConnectionServiceBound) {
137							unbindService(mConnection);
138							xmppConnectionServiceBound = false;
139						}
140						stopService(new Intent(XmppActivity.this,
141								XmppConnectionService.class));
142						finish();
143					}
144				});
145		builder.setPositiveButton(getString(R.string.install),
146				new OnClickListener() {
147
148					@Override
149					public void onClick(DialogInterface dialog, int which) {
150						Uri uri = Uri
151								.parse("market://details?id=org.sufficientlysecure.keychain");
152						Intent intent = new Intent(Intent.ACTION_VIEW, uri);
153						startActivity(intent);
154						finish();
155					}
156				});
157		builder.create().show();
158	}
159
160	abstract void onBackendConnected();
161
162	public boolean onOptionsItemSelected(MenuItem item) {
163		switch (item.getItemId()) {
164		case R.id.action_settings:
165			startActivity(new Intent(this, SettingsActivity.class));
166			break;
167		case R.id.action_accounts:
168			startActivity(new Intent(this, ManageAccountActivity.class));
169			break;
170		case android.R.id.home:
171			finish();
172			break;
173		}
174		return super.onOptionsItemSelected(item);
175	}
176
177	@Override
178	protected void onCreate(Bundle savedInstanceState) {
179		super.onCreate(savedInstanceState);
180		metrics = getResources().getDisplayMetrics();
181		ExceptionHelper.init(getApplicationContext());
182		mPrimaryTextColor = getResources().getColor(R.color.primarytext);
183		mSecondaryTextColor = getResources().getColor(R.color.secondarytext);
184		mWarningTextColor = getResources().getColor(R.color.warningtext);
185		mPrimaryColor = getResources().getColor(R.color.primary);
186	}
187
188	public void switchToConversation(Conversation conversation) {
189		switchToConversation(conversation, null, false);
190	}
191
192	public void switchToConversation(Conversation conversation, String text,
193			boolean newTask) {
194		Intent viewConversationIntent = new Intent(this,
195				ConversationActivity.class);
196		viewConversationIntent.setAction(Intent.ACTION_VIEW);
197		viewConversationIntent.putExtra(ConversationActivity.CONVERSATION,
198				conversation.getUuid());
199		if (text != null) {
200			viewConversationIntent.putExtra(ConversationActivity.TEXT, text);
201		}
202		viewConversationIntent.setType(ConversationActivity.VIEW_CONVERSATION);
203		if (newTask) {
204			viewConversationIntent.setFlags(viewConversationIntent.getFlags()
205					| Intent.FLAG_ACTIVITY_NEW_TASK
206					| Intent.FLAG_ACTIVITY_SINGLE_TOP);
207		} else {
208			viewConversationIntent.setFlags(viewConversationIntent.getFlags()
209					| Intent.FLAG_ACTIVITY_CLEAR_TOP);
210		}
211		startActivity(viewConversationIntent);
212	}
213
214	public void switchToContactDetails(Contact contact) {
215		Intent intent = new Intent(this, ContactDetailsActivity.class);
216		intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
217		intent.putExtra("account", contact.getAccount().getJid());
218		intent.putExtra("contact", contact.getJid());
219		startActivity(intent);
220	}
221
222	protected void inviteToConversation(Conversation conversation) {
223		Intent intent = new Intent(getApplicationContext(),
224				ChooseContactActivity.class);
225		intent.putExtra("conversation", conversation.getUuid());
226		startActivityForResult(intent, REQUEST_INVITE_TO_CONVERSATION);
227	}
228
229	protected void announcePgp(Account account, final Conversation conversation) {
230		xmppConnectionService.getPgpEngine().generateSignature(account,
231				"online", new UiCallback<Account>() {
232
233					@Override
234					public void userInputRequried(PendingIntent pi,
235							Account account) {
236						try {
237							startIntentSenderForResult(pi.getIntentSender(),
238									REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
239						} catch (SendIntentException e) {
240						}
241					}
242
243					@Override
244					public void success(Account account) {
245						xmppConnectionService.databaseBackend
246								.updateAccount(account);
247						xmppConnectionService.sendPresencePacket(account,
248								xmppConnectionService.getPresenceGenerator()
249										.sendPresence(account));
250						if (conversation != null) {
251							conversation
252									.setNextEncryption(Message.ENCRYPTION_PGP);
253						}
254					}
255
256					@Override
257					public void error(int error, Account account) {
258						displayErrorDialog(error);
259					}
260				});
261	}
262
263	protected void displayErrorDialog(final int errorCode) {
264		runOnUiThread(new Runnable() {
265
266			@Override
267			public void run() {
268				AlertDialog.Builder builder = new AlertDialog.Builder(
269						XmppActivity.this);
270				builder.setIconAttribute(android.R.attr.alertDialogIcon);
271				builder.setTitle(getString(R.string.error));
272				builder.setMessage(errorCode);
273				builder.setNeutralButton(R.string.accept, null);
274				builder.create().show();
275			}
276		});
277
278	}
279
280	protected void showAddToRosterDialog(final Conversation conversation) {
281		String jid = conversation.getContactJid();
282		AlertDialog.Builder builder = new AlertDialog.Builder(this);
283		builder.setTitle(jid);
284		builder.setMessage(getString(R.string.not_in_roster));
285		builder.setNegativeButton(getString(R.string.cancel), null);
286		builder.setPositiveButton(getString(R.string.add_contact),
287				new DialogInterface.OnClickListener() {
288
289					@Override
290					public void onClick(DialogInterface dialog, int which) {
291						String jid = conversation.getContactJid();
292						Account account = conversation.getAccount();
293						Contact contact = account.getRoster().getContact(jid);
294						xmppConnectionService.createContact(contact);
295						switchToContactDetails(contact);
296					}
297				});
298		builder.create().show();
299	}
300
301	protected void quickEdit(String previousValue, OnValueEdited callback) {
302		quickEdit(previousValue, callback, false);
303	}
304
305	protected void quickPasswordEdit(String previousValue,
306			OnValueEdited callback) {
307		quickEdit(previousValue, callback, true);
308	}
309
310	private void quickEdit(final String previousValue,
311			final OnValueEdited callback, boolean password) {
312		AlertDialog.Builder builder = new AlertDialog.Builder(this);
313		View view = (View) getLayoutInflater()
314				.inflate(R.layout.quickedit, null);
315		final EditText editor = (EditText) view.findViewById(R.id.editor);
316		OnClickListener mClickListener = new OnClickListener() {
317
318			@Override
319			public void onClick(DialogInterface dialog, int which) {
320				String value = editor.getText().toString();
321				if (!previousValue.equals(value) && value.trim().length() > 0) {
322					callback.onValueEdited(value);
323				}
324			}
325		};
326		if (password) {
327			editor.setInputType(InputType.TYPE_CLASS_TEXT
328					| InputType.TYPE_TEXT_VARIATION_PASSWORD);
329			editor.setHint(R.string.password);
330			builder.setPositiveButton(R.string.accept, mClickListener);
331		} else {
332			builder.setPositiveButton(R.string.edit, mClickListener);
333		}
334		editor.requestFocus();
335		editor.setText(previousValue);
336		builder.setView(view);
337		builder.setNegativeButton(R.string.cancel, null);
338		builder.create().show();
339	}
340
341	public void selectPresence(final Conversation conversation,
342			final OnPresenceSelected listener) {
343		Contact contact = conversation.getContact();
344		if (!contact.showInRoster()) {
345			showAddToRosterDialog(conversation);
346		} else {
347			Presences presences = contact.getPresences();
348			if (presences.size() == 0) {
349				conversation.setNextPresence(null);
350				listener.onPresenceSelected();
351			} else if (presences.size() == 1) {
352				String presence = (String) presences.asStringArray()[0];
353				conversation.setNextPresence(presence);
354				listener.onPresenceSelected();
355			} else {
356				final StringBuilder presence = new StringBuilder();
357				AlertDialog.Builder builder = new AlertDialog.Builder(this);
358				builder.setTitle(getString(R.string.choose_presence));
359				final String[] presencesArray = presences.asStringArray();
360				int preselectedPresence = 0;
361				for (int i = 0; i < presencesArray.length; ++i) {
362					if (presencesArray[i].equals(contact.lastseen.presence)) {
363						preselectedPresence = i;
364						break;
365					}
366				}
367				presence.append(presencesArray[preselectedPresence]);
368				builder.setSingleChoiceItems(presencesArray,
369						preselectedPresence,
370						new DialogInterface.OnClickListener() {
371
372							@Override
373							public void onClick(DialogInterface dialog,
374									int which) {
375								presence.delete(0, presence.length());
376								presence.append(presencesArray[which]);
377							}
378						});
379				builder.setNegativeButton(R.string.cancel, null);
380				builder.setPositiveButton(R.string.ok, new OnClickListener() {
381
382					@Override
383					public void onClick(DialogInterface dialog, int which) {
384						conversation.setNextPresence(presence.toString());
385						listener.onPresenceSelected();
386					}
387				});
388				builder.create().show();
389			}
390		}
391	}
392
393	protected void onActivityResult(int requestCode, int resultCode,
394			final Intent data) {
395		super.onActivityResult(requestCode, resultCode, data);
396		if (requestCode == REQUEST_INVITE_TO_CONVERSATION
397				&& resultCode == RESULT_OK) {
398			String contactJid = data.getStringExtra("contact");
399			String conversationUuid = data.getStringExtra("conversation");
400			Conversation conversation = xmppConnectionService
401					.findConversationByUuid(conversationUuid);
402			if (conversation.getMode() == Conversation.MODE_MULTI) {
403				xmppConnectionService.invite(conversation, contactJid);
404			}
405			Log.d(Config.LOGTAG, "inviting " + contactJid + " to "
406					+ conversation.getName());
407		}
408	}
409
410	public int getSecondaryTextColor() {
411		return this.mSecondaryTextColor;
412	}
413
414	public int getPrimaryTextColor() {
415		return this.mPrimaryTextColor;
416	}
417
418	public int getWarningTextColor() {
419		return this.mWarningTextColor;
420	}
421
422	public int getPrimaryColor() {
423		return this.mPrimaryColor;
424	}
425
426	class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
427		private final WeakReference<ImageView> imageViewReference;
428		private Message message = null;
429
430		public BitmapWorkerTask(ImageView imageView) {
431			imageViewReference = new WeakReference<ImageView>(imageView);
432		}
433
434		@Override
435		protected Bitmap doInBackground(Message... params) {
436			message = params[0];
437			try {
438				return xmppConnectionService.getFileBackend().getThumbnail(
439						message, (int) (metrics.density * 288), false);
440			} catch (FileNotFoundException e) {
441				return null;
442			}
443		}
444
445		@Override
446		protected void onPostExecute(Bitmap bitmap) {
447			if (imageViewReference != null && bitmap != null) {
448				final ImageView imageView = imageViewReference.get();
449				if (imageView != null) {
450					imageView.setImageBitmap(bitmap);
451					imageView.setBackgroundColor(0x00000000);
452				}
453			}
454		}
455	}
456
457	public void loadBitmap(Message message, ImageView imageView) {
458		Bitmap bm;
459		try {
460			bm = xmppConnectionService.getFileBackend().getThumbnail(message,
461					(int) (metrics.density * 288), true);
462		} catch (FileNotFoundException e) {
463			bm = null;
464		}
465		if (bm != null) {
466			imageView.setImageBitmap(bm);
467			imageView.setBackgroundColor(0x00000000);
468		} else {
469			if (cancelPotentialWork(message, imageView)) {
470				imageView.setBackgroundColor(0xff333333);
471				final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
472				final AsyncDrawable asyncDrawable = new AsyncDrawable(
473						getResources(), null, task);
474				imageView.setImageDrawable(asyncDrawable);
475				try {
476					task.execute(message);
477				} catch (RejectedExecutionException e) {
478					return;
479				}
480			}
481		}
482	}
483
484	public static boolean cancelPotentialWork(Message message,
485			ImageView imageView) {
486		final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
487
488		if (bitmapWorkerTask != null) {
489			final Message oldMessage = bitmapWorkerTask.message;
490			if (oldMessage == null || message != oldMessage) {
491				bitmapWorkerTask.cancel(true);
492			} else {
493				return false;
494			}
495		}
496		return true;
497	}
498
499	private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
500		if (imageView != null) {
501			final Drawable drawable = imageView.getDrawable();
502			if (drawable instanceof AsyncDrawable) {
503				final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
504				return asyncDrawable.getBitmapWorkerTask();
505			}
506		}
507		return null;
508	}
509
510	static class AsyncDrawable extends BitmapDrawable {
511		private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
512
513		public AsyncDrawable(Resources res, Bitmap bitmap,
514				BitmapWorkerTask bitmapWorkerTask) {
515			super(res, bitmap);
516			bitmapWorkerTaskReference = new WeakReference<BitmapWorkerTask>(
517					bitmapWorkerTask);
518		}
519
520		public BitmapWorkerTask getBitmapWorkerTask() {
521			return bitmapWorkerTaskReference.get();
522		}
523	}
524}