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