ConversationActivity.java

  1package eu.siacs.conversations.ui;
  2
  3import java.io.FileNotFoundException;
  4import java.lang.ref.WeakReference;
  5import java.util.ArrayList;
  6import java.util.List;
  7
  8import eu.siacs.conversations.R;
  9import eu.siacs.conversations.entities.Contact;
 10import eu.siacs.conversations.entities.Conversation;
 11import eu.siacs.conversations.entities.Message;
 12import eu.siacs.conversations.services.ImageProvider;
 13import eu.siacs.conversations.services.XmppConnectionService.OnConversationUpdate;
 14import eu.siacs.conversations.utils.ExceptionHelper;
 15import eu.siacs.conversations.utils.UIHelper;
 16import android.net.Uri;
 17import android.os.AsyncTask;
 18import android.os.Bundle;
 19import android.preference.PreferenceManager;
 20import android.provider.MediaStore;
 21import android.app.AlertDialog;
 22import android.app.FragmentTransaction;
 23import android.app.PendingIntent;
 24import android.content.Context;
 25import android.content.DialogInterface;
 26import android.content.DialogInterface.OnClickListener;
 27import android.content.IntentSender.SendIntentException;
 28import android.content.Intent;
 29import android.content.SharedPreferences;
 30import android.content.res.Resources;
 31import android.graphics.Bitmap;
 32import android.graphics.Color;
 33import android.graphics.Typeface;
 34import android.graphics.drawable.BitmapDrawable;
 35import android.graphics.drawable.Drawable;
 36import android.support.v4.widget.SlidingPaneLayout;
 37import android.support.v4.widget.SlidingPaneLayout.PanelSlideListener;
 38import android.util.DisplayMetrics;
 39import android.util.Log;
 40import android.view.KeyEvent;
 41import android.view.LayoutInflater;
 42import android.view.Menu;
 43import android.view.MenuItem;
 44import android.view.View;
 45import android.view.ViewGroup;
 46import android.widget.AdapterView;
 47import android.widget.AdapterView.OnItemClickListener;
 48import android.widget.ArrayAdapter;
 49import android.widget.CheckBox;
 50import android.widget.ListView;
 51import android.widget.PopupMenu;
 52import android.widget.PopupMenu.OnMenuItemClickListener;
 53import android.widget.TextView;
 54import android.widget.ImageView;
 55import android.widget.Toast;
 56
 57public class ConversationActivity extends XmppActivity {
 58
 59	public static final String VIEW_CONVERSATION = "viewConversation";
 60	public static final String CONVERSATION = "conversationUuid";
 61	public static final String TEXT = "text";
 62	public static final String PRESENCE = "eu.siacs.conversations.presence";
 63
 64	public static final int REQUEST_SEND_MESSAGE = 0x75441;
 65	public static final int REQUEST_DECRYPT_PGP = 0x76783;
 66	private static final int REQUEST_ATTACH_FILE_DIALOG = 0x48502;
 67	private static final int REQUEST_IMAGE_CAPTURE = 0x33788;
 68	private static final int REQUEST_RECORD_AUDIO = 0x46189;
 69	private static final int REQUEST_SEND_PGP_IMAGE = 0x53883;
 70	public static final int REQUEST_ENCRYPT_MESSAGE = 0x378018;
 71
 72	private static final int ATTACHMENT_CHOICE_CHOOSE_IMAGE = 0x92734;
 73	private static final int ATTACHMENT_CHOICE_TAKE_PHOTO = 0x84123;
 74	private static final int ATTACHMENT_CHOICE_RECORD_VOICE = 0x75291;
 75
 76	protected SlidingPaneLayout spl;
 77
 78	private List<Conversation> conversationList = new ArrayList<Conversation>();
 79	private Conversation selectedConversation = null;
 80	private ListView listView;
 81
 82	private boolean paneShouldBeOpen = true;
 83	private boolean useSubject = true;
 84	private boolean showLastseen = false;
 85	private ArrayAdapter<Conversation> listAdapter;
 86
 87	private OnConversationUpdate onConvChanged = new OnConversationUpdate() {
 88		
 89		@Override
 90		public void onConversationUpdate() {
 91			runOnUiThread(new Runnable() {
 92
 93				@Override
 94				public void run() {
 95					updateConversationList();
 96					if (paneShouldBeOpen) {
 97						if (conversationList.size() >= 1) {
 98							swapConversationFragment();
 99						} else {
100							startActivity(new Intent(getApplicationContext(),
101									StartConversation.class));
102							finish();
103						}
104					}
105					ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager()
106							.findFragmentByTag("conversation");
107					if (selectedFragment != null) {
108						selectedFragment.updateMessages();
109					}
110				}
111			});
112		}
113	};
114
115	protected ConversationActivity activity = this;
116	private DisplayMetrics metrics;
117	private Toast prepareImageToast;
118
119	public List<Conversation> getConversationList() {
120		return this.conversationList;
121	}
122
123	public Conversation getSelectedConversation() {
124		return this.selectedConversation;
125	}
126
127	public void setSelectedConversation(Conversation conversation) {
128		this.selectedConversation = conversation;
129	}
130
131	public ListView getConversationListView() {
132		return this.listView;
133	}
134
135	public SlidingPaneLayout getSlidingPaneLayout() {
136		return this.spl;
137	}
138
139	public boolean shouldPaneBeOpen() {
140		return paneShouldBeOpen;
141	}
142
143	@Override
144	protected void onCreate(Bundle savedInstanceState) {
145
146		metrics = getResources().getDisplayMetrics();
147
148		super.onCreate(savedInstanceState);
149
150		setContentView(R.layout.fragment_conversations_overview);
151
152		listView = (ListView) findViewById(R.id.list);
153
154		this.listAdapter = new ArrayAdapter<Conversation>(this,
155				R.layout.conversation_list_row, conversationList) {
156			@Override
157			public View getView(int position, View view, ViewGroup parent) {
158				if (view == null) {
159					LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
160					view = (View) inflater.inflate(
161							R.layout.conversation_list_row, null);
162				}
163				Conversation conv;
164				if (conversationList.size() > position) {
165					conv = getItem(position);
166				} else {
167					return view;
168				}
169				if (!spl.isSlideable()) {
170					if (conv == getSelectedConversation()) {
171						view.setBackgroundColor(0xffdddddd);
172					} else {
173						view.setBackgroundColor(Color.TRANSPARENT);
174					}
175				} else {
176					view.setBackgroundColor(Color.TRANSPARENT);
177				}
178				TextView convName = (TextView) view
179						.findViewById(R.id.conversation_name);
180				convName.setText(conv.getName(useSubject));
181				TextView convLastMsg = (TextView) view
182						.findViewById(R.id.conversation_lastmsg);
183				ImageView imagePreview = (ImageView) view
184						.findViewById(R.id.conversation_lastimage);
185
186				Message latestMessage = conv.getLatestMessage();
187
188				if (latestMessage.getType() == Message.TYPE_TEXT) {
189					if ((latestMessage.getEncryption() != Message.ENCRYPTION_PGP)
190							&& (latestMessage.getEncryption() != Message.ENCRYPTION_DECRYPTION_FAILED)) {
191						convLastMsg.setText(conv.getLatestMessage().getBody());
192					} else {
193						convLastMsg
194								.setText(getText(R.string.encrypted_message_received));
195					}
196					convLastMsg.setVisibility(View.VISIBLE);
197					imagePreview.setVisibility(View.GONE);
198				} else if (latestMessage.getType() == Message.TYPE_IMAGE) {
199					if (latestMessage.getStatus() >= Message.STATUS_RECIEVED) {
200						convLastMsg.setVisibility(View.GONE);
201						imagePreview.setVisibility(View.VISIBLE);
202						loadBitmap(latestMessage, imagePreview);
203					} else {
204						convLastMsg.setVisibility(View.VISIBLE);
205						imagePreview.setVisibility(View.GONE);
206						if (latestMessage.getStatus() == Message.STATUS_RECEIVED_OFFER) {
207							convLastMsg
208									.setText(getText(R.string.image_offered_for_download));
209						} else if (latestMessage.getStatus() == Message.STATUS_RECIEVING) {
210							convLastMsg
211									.setText(getText(R.string.receiving_image));
212						} else {
213							convLastMsg.setText("");
214						}
215					}
216				}
217
218				if (!conv.isRead()) {
219					convName.setTypeface(null, Typeface.BOLD);
220					convLastMsg.setTypeface(null, Typeface.BOLD);
221				} else {
222					convName.setTypeface(null, Typeface.NORMAL);
223					convLastMsg.setTypeface(null, Typeface.NORMAL);
224				}
225
226				((TextView) view.findViewById(R.id.conversation_lastupdate))
227						.setText(UIHelper.readableTimeDifference(getContext(),
228								conv.getLatestMessage().getTimeSent()));
229
230				ImageView profilePicture = (ImageView) view
231						.findViewById(R.id.conversation_image);
232				profilePicture.setImageBitmap(UIHelper.getContactPicture(conv,
233						56, activity.getApplicationContext(), false));
234
235				return view;
236			}
237
238		};
239
240		listView.setAdapter(this.listAdapter);
241
242		listView.setOnItemClickListener(new OnItemClickListener() {
243
244			@Override
245			public void onItemClick(AdapterView<?> arg0, View clickedView,
246					int position, long arg3) {
247				paneShouldBeOpen = false;
248				if (getSelectedConversation() != conversationList.get(position)) {
249					setSelectedConversation(conversationList.get(position));
250					swapConversationFragment(); // .onBackendConnected(conversationList.get(position));
251				} else {
252					spl.closePane();
253				}
254			}
255		});
256		spl = (SlidingPaneLayout) findViewById(R.id.slidingpanelayout);
257		spl.setParallaxDistance(150);
258		spl.setShadowResource(R.drawable.es_slidingpane_shadow);
259		spl.setSliderFadeColor(0);
260		spl.setPanelSlideListener(new PanelSlideListener() {
261
262			@Override
263			public void onPanelOpened(View arg0) {
264				paneShouldBeOpen = true;
265				getActionBar().setDisplayHomeAsUpEnabled(false);
266				getActionBar().setHomeButtonEnabled(false);
267				getActionBar().setTitle(R.string.app_name);
268				invalidateOptionsMenu();
269				hideKeyboard();
270			}
271
272			@Override
273			public void onPanelClosed(View arg0) {
274				paneShouldBeOpen = false;
275				if ((conversationList.size() > 0)
276						&& (getSelectedConversation() != null)) {
277					getActionBar().setDisplayHomeAsUpEnabled(true);
278					getActionBar().setHomeButtonEnabled(true);
279					getActionBar().setTitle(
280							getSelectedConversation().getName(useSubject));
281					invalidateOptionsMenu();
282					if (!getSelectedConversation().isRead()) {
283						xmppConnectionService
284								.markRead(getSelectedConversation());
285						UIHelper.updateNotification(getApplicationContext(),
286								getConversationList(), null, false);
287						listView.invalidateViews();
288					}
289				}
290			}
291
292			@Override
293			public void onPanelSlide(View arg0, float arg1) {
294				// TODO Auto-generated method stub
295
296			}
297		});
298	}
299
300	@Override
301	public boolean onCreateOptionsMenu(Menu menu) {
302		getMenuInflater().inflate(R.menu.conversations, menu);
303		MenuItem menuSecure = (MenuItem) menu.findItem(R.id.action_security);
304		MenuItem menuArchive = (MenuItem) menu.findItem(R.id.action_archive);
305		MenuItem menuMucDetails = (MenuItem) menu
306				.findItem(R.id.action_muc_details);
307		MenuItem menuContactDetails = (MenuItem) menu
308				.findItem(R.id.action_contact_details);
309		MenuItem menuInviteContacts = (MenuItem) menu
310				.findItem(R.id.action_invite);
311		MenuItem menuAttach = (MenuItem) menu.findItem(R.id.action_attach_file);
312		MenuItem menuClearHistory = (MenuItem) menu
313				.findItem(R.id.action_clear_history);
314
315		if ((spl.isOpen() && (spl.isSlideable()))) {
316			menuArchive.setVisible(false);
317			menuMucDetails.setVisible(false);
318			menuContactDetails.setVisible(false);
319			menuSecure.setVisible(false);
320			menuInviteContacts.setVisible(false);
321			menuAttach.setVisible(false);
322			menuClearHistory.setVisible(false);
323		} else {
324			((MenuItem) menu.findItem(R.id.action_add)).setVisible(!spl
325					.isSlideable());
326			if (this.getSelectedConversation() != null) {
327				if (this.getSelectedConversation().getLatestMessage()
328						.getEncryption() != Message.ENCRYPTION_NONE) {
329					menuSecure.setIcon(R.drawable.ic_action_secure);
330				}
331				if (this.getSelectedConversation().getMode() == Conversation.MODE_MULTI) {
332					menuContactDetails.setVisible(false);
333					menuAttach.setVisible(false);
334				} else {
335					menuMucDetails.setVisible(false);
336					menuInviteContacts.setVisible(false);
337				}
338			}
339		}
340		return true;
341	}
342
343	private void selectPresenceToAttachFile(final int attachmentChoice) {
344		selectPresence(getSelectedConversation(), new OnPresenceSelected() {
345
346			@Override
347			public void onPresenceSelected() {
348				if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO) {
349					Intent takePictureIntent = new Intent(
350							MediaStore.ACTION_IMAGE_CAPTURE);
351					takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
352							ImageProvider.getIncomingContentUri());
353					if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
354						startActivityForResult(takePictureIntent,
355								REQUEST_IMAGE_CAPTURE);
356					}
357				} else if (attachmentChoice == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
358					Intent attachFileIntent = new Intent();
359					attachFileIntent.setType("image/*");
360					attachFileIntent.setAction(Intent.ACTION_GET_CONTENT);
361					Intent chooser = Intent.createChooser(attachFileIntent,
362							getString(R.string.attach_file));
363					startActivityForResult(chooser, REQUEST_ATTACH_FILE_DIALOG);
364				} else if (attachmentChoice == ATTACHMENT_CHOICE_RECORD_VOICE) {
365					Intent intent = new Intent(
366							MediaStore.Audio.Media.RECORD_SOUND_ACTION);
367					startActivityForResult(intent, REQUEST_RECORD_AUDIO);
368				}
369			}
370		});
371	}
372
373	private void attachFile(final int attachmentChoice) {
374		final Conversation conversation = getSelectedConversation();
375		if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
376			if (hasPgp()) {
377				if (conversation.getContact().getPgpKeyId() != 0) {
378					xmppConnectionService.getPgpEngine().hasKey(
379							conversation.getContact(),
380							new UiCallback<Contact>() {
381
382								@Override
383								public void userInputRequried(PendingIntent pi,
384										Contact contact) {
385									ConversationActivity.this.runIntent(pi,
386											attachmentChoice);
387								}
388
389								@Override
390								public void success(Contact contact) {
391									selectPresenceToAttachFile(attachmentChoice);
392								}
393
394								@Override
395								public void error(int error, Contact contact) {
396									displayErrorDialog(error);
397								}
398							});
399				} else {
400					final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
401							.findFragmentByTag("conversation");
402					if (fragment != null) {
403						fragment.showNoPGPKeyDialog(false,
404								new OnClickListener() {
405
406									@Override
407									public void onClick(DialogInterface dialog,
408											int which) {
409										conversation
410												.setNextEncryption(Message.ENCRYPTION_NONE);
411										selectPresenceToAttachFile(attachmentChoice);
412									}
413								});
414					}
415				}
416			} else {
417				showInstallPgpDialog();
418			}
419		} else if (getSelectedConversation().getNextEncryption() == Message.ENCRYPTION_NONE) {
420			selectPresenceToAttachFile(attachmentChoice);
421		} else {
422			selectPresenceToAttachFile(attachmentChoice);
423		}
424	}
425
426	@Override
427	public boolean onOptionsItemSelected(MenuItem item) {
428		switch (item.getItemId()) {
429		case android.R.id.home:
430			spl.openPane();
431			break;
432		case R.id.action_attach_file:
433			View menuAttachFile = findViewById(R.id.action_attach_file);
434			if (menuAttachFile==null) {
435				break;
436			}
437			PopupMenu attachFilePopup = new PopupMenu(this, menuAttachFile);
438			attachFilePopup.inflate(R.menu.attachment_choices);
439			attachFilePopup
440					.setOnMenuItemClickListener(new OnMenuItemClickListener() {
441
442						@Override
443						public boolean onMenuItemClick(MenuItem item) {
444							switch (item.getItemId()) {
445							case R.id.attach_choose_picture:
446								attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
447								break;
448							case R.id.attach_take_picture:
449								attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
450								break;
451							case R.id.attach_record_voice:
452								attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
453								break;
454							}
455							return false;
456						}
457					});
458			attachFilePopup.show();
459			break;
460		case R.id.action_add:
461			startActivity(new Intent(this, StartConversation.class));
462			break;
463		case R.id.action_archive:
464			this.endConversation(getSelectedConversation());
465			break;
466		case R.id.action_contact_details:
467			Contact contact = this.getSelectedConversation().getContact();
468			if (contact.showInRoster()) {
469				switchToContactDetails(contact);
470			} else {
471				showAddToRosterDialog(getSelectedConversation());
472			}
473			break;
474		case R.id.action_muc_details:
475			Intent intent = new Intent(this, MucDetailsActivity.class);
476			intent.setAction(MucDetailsActivity.ACTION_VIEW_MUC);
477			intent.putExtra("uuid", getSelectedConversation().getUuid());
478			startActivity(intent);
479			break;
480		case R.id.action_invite:
481			/*Intent inviteIntent = new Intent(getApplicationContext(),
482					ContactsActivity.class);
483			inviteIntent.setAction("invite");
484			inviteIntent.putExtra("uuid", getSelectedConversation().getUuid());
485			startActivity(inviteIntent);*/
486			break;
487		case R.id.action_security:
488			final Conversation conversation = getSelectedConversation();
489			View menuItemView = findViewById(R.id.action_security);
490			if (menuItemView==null) {
491				break;
492			}
493			PopupMenu popup = new PopupMenu(this, menuItemView);
494			final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
495					.findFragmentByTag("conversation");
496			if (fragment != null) {
497				popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
498
499					@Override
500					public boolean onMenuItemClick(MenuItem item) {
501						switch (item.getItemId()) {
502						case R.id.encryption_choice_none:
503							conversation
504									.setNextEncryption(Message.ENCRYPTION_NONE);
505							item.setChecked(true);
506							break;
507						case R.id.encryption_choice_otr:
508							conversation
509									.setNextEncryption(Message.ENCRYPTION_OTR);
510							item.setChecked(true);
511							break;
512						case R.id.encryption_choice_pgp:
513							if (hasPgp()) {
514								if (conversation.getAccount().getKeys()
515										.has("pgp_signature")) {
516									conversation
517											.setNextEncryption(Message.ENCRYPTION_PGP);
518									item.setChecked(true);
519								} else {
520									announcePgp(conversation.getAccount(),
521											conversation);
522								}
523							} else {
524								showInstallPgpDialog();
525							}
526							break;
527						default:
528							conversation
529									.setNextEncryption(Message.ENCRYPTION_NONE);
530							break;
531						}
532						fragment.updateChatMsgHint();
533						return true;
534					}
535				});
536				popup.inflate(R.menu.encryption_choices);
537				MenuItem otr = popup.getMenu().findItem(
538						R.id.encryption_choice_otr);
539				if (conversation.getMode() == Conversation.MODE_MULTI) {
540					otr.setEnabled(false);
541				}
542				switch (conversation.getNextEncryption()) {
543				case Message.ENCRYPTION_NONE:
544					popup.getMenu().findItem(R.id.encryption_choice_none)
545							.setChecked(true);
546					break;
547				case Message.ENCRYPTION_OTR:
548					otr.setChecked(true);
549					break;
550				case Message.ENCRYPTION_PGP:
551					popup.getMenu().findItem(R.id.encryption_choice_pgp)
552							.setChecked(true);
553					break;
554				default:
555					popup.getMenu().findItem(R.id.encryption_choice_none)
556							.setChecked(true);
557					break;
558				}
559				popup.show();
560			}
561
562			break;
563		case R.id.action_clear_history:
564			clearHistoryDialog(getSelectedConversation());
565			break;
566		default:
567			break;
568		}
569		return super.onOptionsItemSelected(item);
570	}
571
572	private void endConversation(Conversation conversation) {
573		conversation.setStatus(Conversation.STATUS_ARCHIVED);
574		paneShouldBeOpen = true;
575		spl.openPane();
576		xmppConnectionService.archiveConversation(conversation);
577		if (conversationList.size() > 0) {
578			setSelectedConversation(conversationList.get(0));
579		} else {
580			setSelectedConversation(null);
581		}
582	}
583
584	protected void clearHistoryDialog(final Conversation conversation) {
585		AlertDialog.Builder builder = new AlertDialog.Builder(this);
586		builder.setTitle(getString(R.string.clear_conversation_history));
587		View dialogView = getLayoutInflater().inflate(
588				R.layout.dialog_clear_history, null);
589		final CheckBox endConversationCheckBox = (CheckBox) dialogView
590				.findViewById(R.id.end_conversation_checkbox);
591		builder.setView(dialogView);
592		builder.setNegativeButton(getString(R.string.cancel), null);
593		builder.setPositiveButton(getString(R.string.delete_messages),
594				new OnClickListener() {
595
596					@Override
597					public void onClick(DialogInterface dialog, int which) {
598						activity.xmppConnectionService
599								.clearConversationHistory(conversation);
600						if (endConversationCheckBox.isChecked()) {
601							endConversation(conversation);
602						}
603					}
604				});
605		builder.create().show();
606	}
607
608	protected ConversationFragment swapConversationFragment() {
609		ConversationFragment selectedFragment = new ConversationFragment();
610
611		FragmentTransaction transaction = getFragmentManager()
612				.beginTransaction();
613		transaction.replace(R.id.selected_conversation, selectedFragment,
614				"conversation");
615		transaction.commitAllowingStateLoss();
616		return selectedFragment;
617	}
618
619	@Override
620	public boolean onKeyDown(int keyCode, KeyEvent event) {
621		if (keyCode == KeyEvent.KEYCODE_BACK) {
622			if (!spl.isOpen()) {
623				spl.openPane();
624				return false;
625			}
626		}
627		return super.onKeyDown(keyCode, event);
628	}
629
630	@Override
631	protected void onNewIntent(Intent intent) {
632		if ((Intent.ACTION_VIEW.equals(intent.getAction()) && (VIEW_CONVERSATION
633				.equals(intent.getType())))) {
634			String convToView = (String) intent.getExtras().get(CONVERSATION);
635			updateConversationList();
636			for (int i = 0; i < conversationList.size(); ++i) {
637				if (conversationList.get(i).getUuid().equals(convToView)) {
638					setSelectedConversation(conversationList.get(i));
639					break;
640				}
641			}
642			paneShouldBeOpen = false;
643			String text = intent.getExtras().getString(TEXT, null);
644			swapConversationFragment().setText(text);
645		}
646	}
647
648	@Override
649	public void onStart() {
650		super.onStart();
651		SharedPreferences preferences = PreferenceManager
652				.getDefaultSharedPreferences(this);
653		this.useSubject = preferences.getBoolean("use_subject_in_muc", true);
654		this.showLastseen = preferences.getBoolean("show_last_seen", false);
655		if (this.xmppConnectionServiceBound) {
656			this.onBackendConnected();
657		}
658		if (conversationList.size() >= 1) {
659			onConvChanged.onConversationUpdate();
660		}
661	}
662
663	@Override
664	protected void onStop() {
665		if (xmppConnectionServiceBound) {
666			xmppConnectionService.removeOnConversationListChangedListener();
667		}
668		super.onStop();
669	}
670
671	@Override
672	void onBackendConnected() {
673		this.registerListener();
674		if (conversationList.size() == 0) {
675			updateConversationList();
676		}
677
678		if ((getIntent().getAction() != null)
679				&& (getIntent().getAction().equals(Intent.ACTION_VIEW) && (!handledViewIntent))) {
680			if (getIntent().getType().equals(
681					ConversationActivity.VIEW_CONVERSATION)) {
682				handledViewIntent = true;
683
684				String convToView = (String) getIntent().getExtras().get(
685						CONVERSATION);
686
687				for (int i = 0; i < conversationList.size(); ++i) {
688					if (conversationList.get(i).getUuid().equals(convToView)) {
689						setSelectedConversation(conversationList.get(i));
690					}
691				}
692				paneShouldBeOpen = false;
693				String text = getIntent().getExtras().getString(TEXT, null);
694				swapConversationFragment().setText(text);
695			}
696		} else {
697			if (xmppConnectionService.getAccounts().size() == 0) {
698				startActivity(new Intent(this, ManageAccountActivity.class));
699				finish();
700			} else if (conversationList.size() <= 0) {
701				// add no history
702				startActivity(new Intent(this, StartConversation.class));
703				finish();
704			} else {
705				spl.openPane();
706				// find currently loaded fragment
707				ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager()
708						.findFragmentByTag("conversation");
709				if (selectedFragment != null) {
710					selectedFragment.onBackendConnected();
711				} else {
712					setSelectedConversation(conversationList.get(0));
713					swapConversationFragment();
714				}
715				ExceptionHelper.checkForCrash(this, this.xmppConnectionService);
716			}
717		}
718	}
719
720	public void registerListener() {
721		if (xmppConnectionServiceBound) {
722			xmppConnectionService
723					.setOnConversationListChangedListener(this.onConvChanged);
724		}
725	}
726
727	@Override
728	protected void onActivityResult(int requestCode, int resultCode,
729			final Intent data) {
730		super.onActivityResult(requestCode, resultCode, data);
731		if (resultCode == RESULT_OK) {
732			if (requestCode == REQUEST_DECRYPT_PGP) {
733				ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager()
734						.findFragmentByTag("conversation");
735				if (selectedFragment != null) {
736					selectedFragment.hideSnackbar();
737				}
738			} else if (requestCode == REQUEST_ATTACH_FILE_DIALOG) {
739				attachImageToConversation(getSelectedConversation(),
740						data.getData());
741			} else if (requestCode == REQUEST_SEND_PGP_IMAGE) {
742
743			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
744				attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
745			} else if (requestCode == ATTACHMENT_CHOICE_TAKE_PHOTO) {
746				attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
747			} else if (requestCode == REQUEST_ANNOUNCE_PGP) {
748				announcePgp(getSelectedConversation().getAccount(),
749						getSelectedConversation());
750			} else if (requestCode == REQUEST_ENCRYPT_MESSAGE) {
751				// encryptTextMessage();
752			} else if (requestCode == REQUEST_IMAGE_CAPTURE) {
753				attachImageToConversation(getSelectedConversation(), null);
754			} else if (requestCode == REQUEST_RECORD_AUDIO) {
755				Log.d("xmppService", data.getData().toString());
756				attachAudioToConversation(getSelectedConversation(),
757						data.getData());
758			} else {
759				Log.d(LOGTAG, "unknown result code:" + requestCode);
760			}
761		}
762	}
763
764	private void attachAudioToConversation(Conversation conversation, Uri uri) {
765
766	}
767
768	private void attachImageToConversation(Conversation conversation, Uri uri) {
769		prepareImageToast = Toast.makeText(getApplicationContext(),
770				getText(R.string.preparing_image), Toast.LENGTH_LONG);
771		prepareImageToast.show();
772		xmppConnectionService.attachImageToConversation(conversation, uri,
773				new UiCallback<Message>() {
774
775					@Override
776					public void userInputRequried(PendingIntent pi,
777							Message object) {
778						hidePrepareImageToast();
779						ConversationActivity.this.runIntent(pi,
780								ConversationActivity.REQUEST_SEND_PGP_IMAGE);
781					}
782
783					@Override
784					public void success(Message message) {
785						xmppConnectionService.sendMessage(message);
786					}
787
788					@Override
789					public void error(int error, Message message) {
790						hidePrepareImageToast();
791						displayErrorDialog(error);
792					}
793				});
794	}
795
796	private void hidePrepareImageToast() {
797		if (prepareImageToast != null) {
798			runOnUiThread(new Runnable() {
799
800				@Override
801				public void run() {
802					prepareImageToast.cancel();
803				}
804			});
805		}
806	}
807
808	public void updateConversationList() {
809		xmppConnectionService.populateWithOrderedConversations(conversationList);
810		listView.invalidateViews();
811	}
812
813	public boolean showLastseen() {
814		if (getSelectedConversation() == null) {
815			return false;
816		} else {
817			return this.showLastseen
818					&& getSelectedConversation().getMode() == Conversation.MODE_SINGLE;
819		}
820	}
821
822	public void runIntent(PendingIntent pi, int requestCode) {
823		try {
824			this.startIntentSenderForResult(pi.getIntentSender(), requestCode,
825					null, 0, 0, 0);
826		} catch (SendIntentException e1) {
827			Log.d("xmppService", "failed to start intent to send message");
828		}
829	}
830
831	class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
832		private final WeakReference<ImageView> imageViewReference;
833		private Message message = null;
834
835		public BitmapWorkerTask(ImageView imageView) {
836			imageViewReference = new WeakReference<ImageView>(imageView);
837		}
838
839		@Override
840		protected Bitmap doInBackground(Message... params) {
841			message = params[0];
842			try {
843				return xmppConnectionService.getFileBackend().getThumbnail(
844						message, (int) (metrics.density * 288), false);
845			} catch (FileNotFoundException e) {
846				Log.d("xmppService", "file not found!");
847				return null;
848			}
849		}
850
851		@Override
852		protected void onPostExecute(Bitmap bitmap) {
853			if (imageViewReference != null && bitmap != null) {
854				final ImageView imageView = imageViewReference.get();
855				if (imageView != null) {
856					imageView.setImageBitmap(bitmap);
857					imageView.setBackgroundColor(0x00000000);
858				}
859			}
860		}
861	}
862
863	public void loadBitmap(Message message, ImageView imageView) {
864		Bitmap bm;
865		try {
866			bm = xmppConnectionService.getFileBackend().getThumbnail(message,
867					(int) (metrics.density * 288), true);
868		} catch (FileNotFoundException e) {
869			bm = null;
870		}
871		if (bm != null) {
872			imageView.setImageBitmap(bm);
873			imageView.setBackgroundColor(0x00000000);
874		} else {
875			if (cancelPotentialWork(message, imageView)) {
876				imageView.setBackgroundColor(0xff333333);
877				final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
878				final AsyncDrawable asyncDrawable = new AsyncDrawable(
879						getResources(), null, task);
880				imageView.setImageDrawable(asyncDrawable);
881				task.execute(message);
882			}
883		}
884	}
885
886	public static boolean cancelPotentialWork(Message message,
887			ImageView imageView) {
888		final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
889
890		if (bitmapWorkerTask != null) {
891			final Message oldMessage = bitmapWorkerTask.message;
892			if (oldMessage == null || message != oldMessage) {
893				bitmapWorkerTask.cancel(true);
894			} else {
895				return false;
896			}
897		}
898		return true;
899	}
900
901	private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
902		if (imageView != null) {
903			final Drawable drawable = imageView.getDrawable();
904			if (drawable instanceof AsyncDrawable) {
905				final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
906				return asyncDrawable.getBitmapWorkerTask();
907			}
908		}
909		return null;
910	}
911
912	static class AsyncDrawable extends BitmapDrawable {
913		private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
914
915		public AsyncDrawable(Resources res, Bitmap bitmap,
916				BitmapWorkerTask bitmapWorkerTask) {
917			super(res, bitmap);
918			bitmapWorkerTaskReference = new WeakReference<BitmapWorkerTask>(
919					bitmapWorkerTask);
920		}
921
922		public BitmapWorkerTask getBitmapWorkerTask() {
923			return bitmapWorkerTaskReference.get();
924		}
925	}
926
927	public void encryptTextMessage(Message message) {
928		xmppConnectionService.getPgpEngine().encrypt(message,
929				new UiCallback<Message>() {
930
931					@Override
932					public void userInputRequried(PendingIntent pi,
933							Message message) {
934						activity.runIntent(pi,
935								ConversationActivity.REQUEST_SEND_MESSAGE);
936					}
937
938					@Override
939					public void success(Message message) {
940						message.setEncryption(Message.ENCRYPTION_DECRYPTED);
941						xmppConnectionService.sendMessage(message);
942					}
943
944					@Override
945					public void error(int error, Message message) {
946
947					}
948				});
949	}
950}