ConversationActivity.java

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