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 boolean onKeyDown(final int keyCode, final KeyEvent event) {
643		if (keyCode == KeyEvent.KEYCODE_BACK) {
644			if (!isConversationsOverviewVisable()) {
645				showConversationsOverview();
646				return false;
647			}
648		}
649		return super.onKeyDown(keyCode, event);
650	}
651
652	@Override
653	protected void onNewIntent(final Intent intent) {
654		if (xmppConnectionServiceBound) {
655			if (intent != null && VIEW_CONVERSATION.equals(intent.getType())) {
656				handleViewConversationIntent(intent);
657			}
658		} else {
659			setIntent(intent);
660		}
661	}
662
663	@Override
664	public void onStart() {
665		super.onStart();
666		if (this.xmppConnectionServiceBound) {
667			this.onBackendConnected();
668		}
669		if (conversationList.size() >= 1) {
670			this.onConversationUpdate();
671		}
672	}
673
674	@Override
675	public void onSaveInstanceState(final Bundle savedInstanceState) {
676		Conversation conversation = getSelectedConversation();
677		if (conversation != null) {
678			savedInstanceState.putString(STATE_OPEN_CONVERSATION,
679					conversation.getUuid());
680		}
681		savedInstanceState.putBoolean(STATE_PANEL_OPEN,
682				isConversationsOverviewVisable());
683		if (this.mPendingImageUri != null) {
684			savedInstanceState.putString(STATE_PENDING_URI, this.mPendingImageUri.toString());
685		}
686		super.onSaveInstanceState(savedInstanceState);
687	}
688
689	@Override
690	void onBackendConnected() {
691		updateConversationList();
692		if (xmppConnectionService.getAccounts().size() == 0) {
693			startActivity(new Intent(this, EditAccountActivity.class));
694		} else if (conversationList.size() <= 0) {
695			startActivity(new Intent(this, StartConversationActivity.class));
696			finish();
697		} else if (getIntent() != null
698				&& VIEW_CONVERSATION.equals(getIntent().getType())) {
699			handleViewConversationIntent(getIntent());
700		} else if (mOpenConverstaion != null) {
701			selectConversationByUuid(mOpenConverstaion);
702			if (mPanelOpen) {
703				showConversationsOverview();
704			} else {
705				if (isConversationsOverviewHideable()) {
706					openConversation();
707				}
708			}
709			this.mConversationFragment.reInit(getSelectedConversation());
710			mOpenConverstaion = null;
711		} else if (getSelectedConversation() != null) {
712			this.mConversationFragment.updateMessages();
713		} else {
714			showConversationsOverview();
715			mPendingImageUri = null;
716			mPendingFileUri = null;
717			setSelectedConversation(conversationList.get(0));
718			this.mConversationFragment.reInit(getSelectedConversation());
719		}
720
721		if (mPendingImageUri != null) {
722			attachImageToConversation(getSelectedConversation(),mPendingImageUri);
723			mPendingImageUri = null;
724		} else if (mPendingFileUri != null) {
725			attachFileToConversation(getSelectedConversation(),mPendingFileUri);
726			mPendingFileUri = null;
727		}
728		ExceptionHelper.checkForCrash(this, this.xmppConnectionService);
729		setIntent(new Intent());
730	}
731
732	private void handleViewConversationIntent(Intent intent) {
733		String uuid = (String) intent.getExtras().get(CONVERSATION);
734		String text = intent.getExtras().getString(TEXT, "");
735		String nick = intent.getExtras().getString(NICK,null);
736		selectConversationByUuid(uuid);
737		this.mConversationFragment.reInit(getSelectedConversation());
738		if (nick!=null) {
739			this.mConversationFragment.highlightInConference(nick);
740		} else {
741			this.mConversationFragment.appendText(text);
742		}
743		hideConversationsOverview();
744		if (mContentView instanceof SlidingPaneLayout) {
745			openConversation();
746		}
747	}
748
749	private void selectConversationByUuid(String uuid) {
750        for (Conversation aConversationList : conversationList) {
751            if (aConversationList.getUuid().equals(uuid)) {
752                setSelectedConversation(aConversationList);
753            }
754        }
755	}
756
757	@Override
758	protected void unregisterListeners() {
759		super.unregisterListeners();
760		xmppConnectionService.getNotificationService().setOpenConversation(null);
761	}
762
763	@Override
764	protected void onActivityResult(int requestCode, int resultCode,
765									final Intent data) {
766		super.onActivityResult(requestCode, resultCode, data);
767		if (resultCode == RESULT_OK) {
768			if (requestCode == REQUEST_DECRYPT_PGP) {
769				ConversationFragment selectedFragment = (ConversationFragment) getFragmentManager()
770						.findFragmentByTag("conversation");
771				if (selectedFragment != null) {
772					selectedFragment.hideSnackbar();
773					selectedFragment.updateMessages();
774				}
775			} else if (requestCode == REQUEST_ATTACH_IMAGE_DIALOG) {
776				mPendingImageUri = data.getData();
777				if (xmppConnectionServiceBound) {
778					attachImageToConversation(getSelectedConversation(),
779							mPendingImageUri);
780					mPendingImageUri = null;
781				}
782			} else if (requestCode == REQUEST_ATTACH_FILE_DIALOG) {
783				mPendingFileUri = data.getData();
784				if (xmppConnectionServiceBound) {
785					attachFileToConversation(getSelectedConversation(),
786							mPendingFileUri);
787					mPendingFileUri = null;
788				}
789			} else if (requestCode == REQUEST_SEND_PGP_IMAGE) {
790
791			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
792				attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
793			} else if (requestCode == ATTACHMENT_CHOICE_TAKE_PHOTO) {
794				attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
795			} else if (requestCode == REQUEST_ANNOUNCE_PGP) {
796				announcePgp(getSelectedConversation().getAccount(),
797						getSelectedConversation());
798			} else if (requestCode == REQUEST_ENCRYPT_MESSAGE) {
799				// encryptTextMessage();
800			} else if (requestCode == REQUEST_IMAGE_CAPTURE && mPendingImageUri != null) {
801				if (xmppConnectionServiceBound) {
802					attachImageToConversation(getSelectedConversation(),
803							mPendingImageUri);
804					mPendingImageUri = null;
805				}
806				Intent intent = new Intent(
807						Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
808				intent.setData(mPendingImageUri);
809				sendBroadcast(intent);
810			}
811		} else {
812			if (requestCode == REQUEST_IMAGE_CAPTURE) {
813				mPendingImageUri = null;
814			}
815		}
816	}
817
818	private void attachFileToConversation(Conversation conversation, Uri uri) {
819		prepareFileToast = Toast.makeText(getApplicationContext(),
820				getText(R.string.preparing_file), Toast.LENGTH_LONG);
821		prepareFileToast.show();
822		xmppConnectionService.attachFileToConversation(conversation,uri, new UiCallback<Message>() {
823			@Override
824			public void success(Message message) {
825				hidePrepareFileToast();
826				xmppConnectionService.sendMessage(message);
827			}
828
829			@Override
830			public void error(int errorCode, Message message) {
831				displayErrorDialog(errorCode);
832			}
833
834			@Override
835			public void userInputRequried(PendingIntent pi, Message message) {
836
837			}
838		});
839	}
840
841	private void attachImageToConversation(Conversation conversation, Uri uri) {
842		prepareFileToast = Toast.makeText(getApplicationContext(),
843				getText(R.string.preparing_image), Toast.LENGTH_LONG);
844		prepareFileToast.show();
845		xmppConnectionService.attachImageToConversation(conversation, uri,
846				new UiCallback<Message>() {
847
848					@Override
849					public void userInputRequried(PendingIntent pi,
850												  Message object) {
851						hidePrepareFileToast();
852						ConversationActivity.this.runIntent(pi,
853								ConversationActivity.REQUEST_SEND_PGP_IMAGE);
854					}
855
856					@Override
857					public void success(Message message) {
858						xmppConnectionService.sendMessage(message);
859					}
860
861					@Override
862					public void error(int error, Message message) {
863						hidePrepareFileToast();
864						displayErrorDialog(error);
865					}
866				});
867	}
868
869	private void hidePrepareFileToast() {
870		if (prepareFileToast != null) {
871			runOnUiThread(new Runnable() {
872
873				@Override
874				public void run() {
875					prepareFileToast.cancel();
876				}
877			});
878		}
879	}
880
881	public void updateConversationList() {
882		xmppConnectionService
883				.populateWithOrderedConversations(conversationList);
884		listAdapter.notifyDataSetChanged();
885	}
886
887	public void runIntent(PendingIntent pi, int requestCode) {
888		try {
889			this.startIntentSenderForResult(pi.getIntentSender(), requestCode,
890					null, 0, 0, 0);
891		} catch (final SendIntentException ignored) {
892		}
893	}
894
895	public void encryptTextMessage(Message message) {
896		xmppConnectionService.getPgpEngine().encrypt(message,
897				new UiCallback<Message>() {
898
899					@Override
900					public void userInputRequried(PendingIntent pi,
901												  Message message) {
902						ConversationActivity.this.runIntent(pi,
903								ConversationActivity.REQUEST_SEND_MESSAGE);
904					}
905
906					@Override
907					public void success(Message message) {
908						message.setEncryption(Message.ENCRYPTION_DECRYPTED);
909						xmppConnectionService.sendMessage(message);
910					}
911
912					@Override
913					public void error(int error, Message message) {
914
915					}
916				});
917	}
918
919	public boolean forceEncryption() {
920		return getPreferences().getBoolean("force_encryption", false);
921	}
922
923	public boolean useSendButtonToIndicateStatus() {
924		return getPreferences().getBoolean("send_button_status", false);
925	}
926
927	public boolean indicateReceived() {
928		return getPreferences().getBoolean("indicate_received", false);
929	}
930
931	@Override
932	public void onAccountUpdate() {
933		final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
934				.findFragmentByTag("conversation");
935		if (fragment != null) {
936			runOnUiThread(new Runnable() {
937
938				@Override
939				public void run() {
940					fragment.updateMessages();
941				}
942			});
943		}
944	}
945
946	@Override
947	public void onConversationUpdate() {
948		runOnUiThread(new Runnable() {
949
950			@Override
951			public void run() {
952				updateConversationList();
953				if (conversationList.size() == 0) {
954					startActivity(new Intent(getApplicationContext(),
955							StartConversationActivity.class));
956					finish();
957				}
958				ConversationActivity.this.mConversationFragment.updateMessages();
959			}
960		});
961	}
962
963	@Override
964	public void onRosterUpdate() {
965		runOnUiThread(new Runnable() {
966
967				@Override
968				public void run() {
969					ConversationActivity.this.mConversationFragment.updateMessages();
970				}
971			});
972	}
973}