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