ConversationActivity.java

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