ConversationActivity.java

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