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