1package eu.siacs.conversations.ui;
2
3import android.app.Activity;
4import android.app.AlertDialog;
5import android.app.Fragment;
6import android.app.PendingIntent;
7import android.content.ActivityNotFoundException;
8import android.content.Context;
9import android.content.DialogInterface;
10import android.content.Intent;
11import android.content.IntentSender.SendIntentException;
12import android.os.Bundle;
13import android.os.Handler;
14import android.support.v13.view.inputmethod.InputConnectionCompat;
15import android.support.v13.view.inputmethod.InputContentInfoCompat;
16import android.text.Editable;
17import android.text.InputType;
18import android.util.Log;
19import android.util.Pair;
20import android.view.ContextMenu;
21import android.view.ContextMenu.ContextMenuInfo;
22import android.view.Gravity;
23import android.view.KeyEvent;
24import android.view.LayoutInflater;
25import android.view.MenuItem;
26import android.view.View;
27import android.view.View.OnClickListener;
28import android.view.ViewGroup;
29import android.view.inputmethod.EditorInfo;
30import android.view.inputmethod.InputMethodManager;
31import android.widget.AbsListView;
32import android.widget.AbsListView.OnScrollListener;
33import android.widget.AdapterView;
34import android.widget.AdapterView.AdapterContextMenuInfo;
35import android.widget.ImageButton;
36import android.widget.ListView;
37import android.widget.PopupMenu;
38import android.widget.RelativeLayout;
39import android.widget.TextView;
40import android.widget.TextView.OnEditorActionListener;
41import android.widget.Toast;
42
43import net.java.otr4j.session.SessionStatus;
44
45import java.util.ArrayList;
46import java.util.Arrays;
47import java.util.Collections;
48import java.util.List;
49import java.util.ListIterator;
50import java.util.UUID;
51import java.util.concurrent.atomic.AtomicBoolean;
52
53import eu.siacs.conversations.Config;
54import eu.siacs.conversations.R;
55import eu.siacs.conversations.entities.Account;
56import eu.siacs.conversations.entities.Blockable;
57import eu.siacs.conversations.entities.Contact;
58import eu.siacs.conversations.entities.Conversation;
59import eu.siacs.conversations.entities.DownloadableFile;
60import eu.siacs.conversations.entities.Message;
61import eu.siacs.conversations.entities.MucOptions;
62import eu.siacs.conversations.entities.Presence;
63import eu.siacs.conversations.entities.Transferable;
64import eu.siacs.conversations.entities.TransferablePlaceholder;
65import eu.siacs.conversations.http.HttpDownloadConnection;
66import eu.siacs.conversations.persistance.FileBackend;
67import eu.siacs.conversations.services.MessageArchiveService;
68import eu.siacs.conversations.services.XmppConnectionService;
69import eu.siacs.conversations.ui.XmppActivity.OnPresenceSelected;
70import eu.siacs.conversations.ui.XmppActivity.OnValueEdited;
71import eu.siacs.conversations.ui.adapter.MessageAdapter;
72import eu.siacs.conversations.ui.adapter.MessageAdapter.OnContactPictureClicked;
73import eu.siacs.conversations.ui.adapter.MessageAdapter.OnContactPictureLongClicked;
74import eu.siacs.conversations.ui.widget.ListSelectionManager;
75import eu.siacs.conversations.utils.GeoHelper;
76import eu.siacs.conversations.utils.NickValidityChecker;
77import eu.siacs.conversations.utils.UIHelper;
78import eu.siacs.conversations.xmpp.XmppConnection;
79import eu.siacs.conversations.xmpp.chatstate.ChatState;
80import eu.siacs.conversations.xmpp.jid.Jid;
81
82public class ConversationFragment extends Fragment implements EditMessage.KeyboardListener {
83
84 protected Conversation conversation;
85 private OnClickListener leaveMuc = new OnClickListener() {
86
87 @Override
88 public void onClick(View v) {
89 activity.endConversation(conversation);
90 }
91 };
92 private OnClickListener joinMuc = new OnClickListener() {
93
94 @Override
95 public void onClick(View v) {
96 activity.xmppConnectionService.joinMuc(conversation);
97 }
98 };
99 private OnClickListener enterPassword = new OnClickListener() {
100
101 @Override
102 public void onClick(View v) {
103 MucOptions muc = conversation.getMucOptions();
104 String password = muc.getPassword();
105 if (password == null) {
106 password = "";
107 }
108 activity.quickPasswordEdit(password, new OnValueEdited() {
109
110 @Override
111 public void onValueEdited(String value) {
112 activity.xmppConnectionService.providePasswordForMuc(
113 conversation, value);
114 }
115 });
116 }
117 };
118 protected ListView messagesView;
119 final protected List<Message> messageList = new ArrayList<>();
120 protected MessageAdapter messageListAdapter;
121 private EditMessage mEditMessage;
122 private ImageButton mSendButton;
123 private RelativeLayout snackbar;
124 private TextView snackbarMessage;
125 private TextView snackbarAction;
126 private Toast messageLoaderToast;
127
128 private OnScrollListener mOnScrollListener = new OnScrollListener() {
129
130 @Override
131 public void onScrollStateChanged(AbsListView view, int scrollState) {
132 // TODO Auto-generated method stub
133
134 }
135
136 @Override
137 public void onScroll(AbsListView view, int firstVisibleItem,
138 int visibleItemCount, int totalItemCount) {
139 synchronized (ConversationFragment.this.messageList) {
140 if (firstVisibleItem < 5 && conversation != null && conversation.messagesLoaded.compareAndSet(true,false) && messageList.size() > 0) {
141 long timestamp;
142 if (messageList.get(0).getType() == Message.TYPE_STATUS && messageList.size() >= 2) {
143 timestamp = messageList.get(1).getTimeSent();
144 } else {
145 timestamp = messageList.get(0).getTimeSent();
146 }
147 activity.xmppConnectionService.loadMoreMessages(conversation, timestamp, new XmppConnectionService.OnMoreMessagesLoaded() {
148 @Override
149 public void onMoreMessagesLoaded(final int c, final Conversation conversation) {
150 if (ConversationFragment.this.conversation != conversation) {
151 conversation.messagesLoaded.set(true);
152 return;
153 }
154 activity.runOnUiThread(new Runnable() {
155 @Override
156 public void run() {
157 final int oldPosition = messagesView.getFirstVisiblePosition();
158 Message message = null;
159 int childPos;
160 for(childPos = 0; childPos + oldPosition < messageList.size(); ++childPos) {
161 message = messageList.get(oldPosition + childPos);
162 if (message.getType() != Message.TYPE_STATUS) {
163 break;
164 }
165 }
166 final String uuid = message != null ? message.getUuid() : null;
167 View v = messagesView.getChildAt(childPos);
168 final int pxOffset = (v == null) ? 0 : v.getTop();
169 ConversationFragment.this.conversation.populateWithMessages(ConversationFragment.this.messageList);
170 try {
171 updateStatusMessages();
172 } catch (IllegalStateException e) {
173 Log.d(Config.LOGTAG,"caught illegal state exception while updating status messages");
174 }
175 messageListAdapter.notifyDataSetChanged();
176 int pos = Math.max(getIndexOf(uuid,messageList),0);
177 messagesView.setSelectionFromTop(pos, pxOffset);
178 if (messageLoaderToast != null) {
179 messageLoaderToast.cancel();
180 }
181 conversation.messagesLoaded.set(true);
182 }
183 });
184 }
185
186 @Override
187 public void informUser(final int resId) {
188
189 activity.runOnUiThread(new Runnable() {
190 @Override
191 public void run() {
192 if (messageLoaderToast != null) {
193 messageLoaderToast.cancel();
194 }
195 if (ConversationFragment.this.conversation != conversation) {
196 return;
197 }
198 messageLoaderToast = Toast.makeText(activity, resId, Toast.LENGTH_LONG);
199 messageLoaderToast.show();
200 }
201 });
202
203 }
204 });
205
206 }
207 }
208 }
209 };
210
211 private int getIndexOf(String uuid, List<Message> messages) {
212 if (uuid == null) {
213 return messages.size() - 1;
214 }
215 for(int i = 0; i < messages.size(); ++i) {
216 if (uuid.equals(messages.get(i).getUuid())) {
217 return i;
218 } else {
219 Message next = messages.get(i);
220 while(next != null && next.wasMergedIntoPrevious()) {
221 if (uuid.equals(next.getUuid())) {
222 return i;
223 }
224 next = next.next();
225 }
226
227 }
228 }
229 return -1;
230 }
231
232 public Pair<Integer,Integer> getScrollPosition() {
233 if (this.messagesView.getCount() == 0 ||
234 this.messagesView.getLastVisiblePosition() == this.messagesView.getCount() - 1) {
235 return null;
236 } else {
237 final int pos = messagesView.getFirstVisiblePosition();
238 final View view = messagesView.getChildAt(0);
239 if (view == null) {
240 return null;
241 } else {
242 return new Pair<>(pos, view.getTop());
243 }
244 }
245 }
246
247 public void setScrollPosition(Pair<Integer,Integer> scrollPosition) {
248 if (scrollPosition != null) {
249 this.messagesView.setSelectionFromTop(scrollPosition.first, scrollPosition.second);
250 }
251 }
252
253 protected OnClickListener clickToDecryptListener = new OnClickListener() {
254
255 @Override
256 public void onClick(View v) {
257 PendingIntent pendingIntent = conversation.getAccount().getPgpDecryptionService().getPendingIntent();
258 if (pendingIntent != null) {
259 try {
260 activity.startIntentSenderForResult(pendingIntent.getIntentSender(),
261 ConversationActivity.REQUEST_DECRYPT_PGP,
262 null,
263 0,
264 0,
265 0);
266 } catch (SendIntentException e) {
267 Toast.makeText(activity,R.string.unable_to_connect_to_keychain, Toast.LENGTH_SHORT).show();
268 conversation.getAccount().getPgpDecryptionService().continueDecryption(true);
269 }
270 }
271 updateSnackBar(conversation);
272 }
273 };
274 protected OnClickListener clickToVerify = new OnClickListener() {
275
276 @Override
277 public void onClick(View v) {
278 activity.verifyOtrSessionDialog(conversation, v);
279 }
280 };
281 private OnEditorActionListener mEditorActionListener = new OnEditorActionListener() {
282
283 @Override
284 public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
285 if (actionId == EditorInfo.IME_ACTION_SEND) {
286 InputMethodManager imm = (InputMethodManager) v.getContext()
287 .getSystemService(Context.INPUT_METHOD_SERVICE);
288 if (imm.isFullscreenMode()) {
289 imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
290 }
291 sendMessage();
292 return true;
293 } else {
294 return false;
295 }
296 }
297 };
298 private EditMessage.OnCommitContentListener mEditorContentListener = new EditMessage.OnCommitContentListener() {
299 @Override
300 public boolean onCommitContent(InputContentInfoCompat inputContentInfo, int flags, Bundle opts, String[] contentMimeTypes) {
301 // try to get permission to read the image, if applicable
302 if ((flags & InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION) != 0) {
303 try {
304 inputContentInfo.requestPermission();
305 } catch (Exception e) {
306 Log.e(Config.LOGTAG, "InputContentInfoCompat#requestPermission() failed.", e);
307 Toast.makeText(
308 activity,
309 activity.getString(R.string.no_permission_to_access_x, inputContentInfo.getDescription()),
310 Toast.LENGTH_LONG
311 ).show();
312 return false;
313 }
314 }
315
316 // send the image
317 activity.attachImageToConversation(inputContentInfo.getContentUri());
318
319 // TODO: revoke permissions?
320 // since uploading an image is async its tough to wire a callback to when
321 // the image has finished uploading.
322 // According to the docs: "calling IC#releasePermission() is just to be a
323 // good citizen. Even if we failed to call that method, the system would eventually revoke
324 // the permission sometime after inputContentInfo object gets garbage-collected."
325 // See: https://developer.android.com/samples/CommitContentSampleApp/src/com.example.android.commitcontent.app/MainActivity.html#l164
326 return true;
327 }
328 };
329 private OnClickListener mSendButtonListener = new OnClickListener() {
330
331 @Override
332 public void onClick(View v) {
333 Object tag = v.getTag();
334 if (tag instanceof SendButtonAction) {
335 SendButtonAction action = (SendButtonAction) tag;
336 switch (action) {
337 case TAKE_PHOTO:
338 activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_TAKE_PHOTO);
339 break;
340 case SEND_LOCATION:
341 activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_LOCATION);
342 break;
343 case RECORD_VOICE:
344 activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_RECORD_VOICE);
345 break;
346 case CHOOSE_PICTURE:
347 activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_CHOOSE_IMAGE);
348 break;
349 case CANCEL:
350 if (conversation != null) {
351 if(conversation.setCorrectingMessage(null)) {
352 mEditMessage.setText("");
353 mEditMessage.append(conversation.getDraftMessage());
354 conversation.setDraftMessage(null);
355 } else if (conversation.getMode() == Conversation.MODE_MULTI) {
356 conversation.setNextCounterpart(null);
357 }
358 updateChatMsgHint();
359 updateSendButton();
360 updateEditablity();
361 }
362 break;
363 default:
364 sendMessage();
365 }
366 } else {
367 sendMessage();
368 }
369 }
370 };
371 private OnClickListener clickToMuc = new OnClickListener() {
372
373 @Override
374 public void onClick(View v) {
375 Intent intent = new Intent(getActivity(), ConferenceDetailsActivity.class);
376 intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
377 intent.putExtra("uuid", conversation.getUuid());
378 startActivity(intent);
379 }
380 };
381 private ConversationActivity activity;
382 private Message selectedMessage;
383
384 private void sendMessage() {
385 final String body = mEditMessage.getText().toString();
386 final Conversation conversation = this.conversation;
387 if (body.length() == 0 || conversation == null) {
388 return;
389 }
390 final Message message;
391 if (conversation.getCorrectingMessage() == null) {
392 message = new Message(conversation, body, conversation.getNextEncryption());
393 if (conversation.getMode() == Conversation.MODE_MULTI) {
394 if (conversation.getNextCounterpart() != null) {
395 message.setCounterpart(conversation.getNextCounterpart());
396 message.setType(Message.TYPE_PRIVATE);
397 }
398 }
399 } else {
400 message = conversation.getCorrectingMessage();
401 message.setBody(body);
402 message.setEdited(message.getUuid());
403 message.setUuid(UUID.randomUUID().toString());
404 }
405 switch (message.getConversation().getNextEncryption()) {
406 case Message.ENCRYPTION_OTR:
407 sendOtrMessage(message);
408 break;
409 case Message.ENCRYPTION_PGP:
410 sendPgpMessage(message);
411 break;
412 case Message.ENCRYPTION_AXOLOTL:
413 if(!activity.trustKeysIfNeeded(ConversationActivity.REQUEST_TRUST_KEYS_TEXT)) {
414 sendAxolotlMessage(message);
415 }
416 break;
417 default:
418 sendPlainTextMessage(message);
419 }
420 }
421
422 public void updateChatMsgHint() {
423 final boolean multi = conversation.getMode() == Conversation.MODE_MULTI;
424 if (conversation.getCorrectingMessage() != null) {
425 this.mEditMessage.setHint(R.string.send_corrected_message);
426 } else if (multi && conversation.getNextCounterpart() != null) {
427 this.mEditMessage.setHint(getString(
428 R.string.send_private_message_to,
429 conversation.getNextCounterpart().getResourcepart()));
430 } else if (multi && !conversation.getMucOptions().participating()) {
431 this.mEditMessage.setHint(R.string.you_are_not_participating);
432 } else {
433 this.mEditMessage.setHint(UIHelper.getMessageHint(activity,conversation));
434 getActivity().invalidateOptionsMenu();
435 }
436 }
437
438 public void setupIme() {
439 if (activity != null) {
440 if (activity.usingEnterKey() && activity.enterIsSend()) {
441 mEditMessage.setInputType(mEditMessage.getInputType() & (~InputType.TYPE_TEXT_FLAG_MULTI_LINE));
442 mEditMessage.setInputType(mEditMessage.getInputType() & (~InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE));
443 } else if (activity.usingEnterKey()) {
444 mEditMessage.setInputType(mEditMessage.getInputType() | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
445 mEditMessage.setInputType(mEditMessage.getInputType() & (~InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE));
446 } else {
447 mEditMessage.setInputType(mEditMessage.getInputType() | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
448 mEditMessage.setInputType(mEditMessage.getInputType() | InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE);
449 }
450 }
451 }
452
453 @Override
454 public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
455 final View view = inflater.inflate(R.layout.fragment_conversation, container, false);
456 view.setOnClickListener(null);
457
458 String[] allImagesMimeType = {"image/*"};
459 mEditMessage = (EditMessage) view.findViewById(R.id.textinput);
460 mEditMessage.setOnClickListener(new OnClickListener() {
461
462 @Override
463 public void onClick(View v) {
464 if (activity != null) {
465 activity.hideConversationsOverview();
466 }
467 }
468 });
469 mEditMessage.setOnEditorActionListener(mEditorActionListener);
470 mEditMessage.setRichContentListener(allImagesMimeType, mEditorContentListener);
471
472 mSendButton = (ImageButton) view.findViewById(R.id.textSendButton);
473 mSendButton.setOnClickListener(this.mSendButtonListener);
474
475 snackbar = (RelativeLayout) view.findViewById(R.id.snackbar);
476 snackbarMessage = (TextView) view.findViewById(R.id.snackbar_message);
477 snackbarAction = (TextView) view.findViewById(R.id.snackbar_action);
478
479 messagesView = (ListView) view.findViewById(R.id.messages_view);
480 messagesView.setOnScrollListener(mOnScrollListener);
481 messagesView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
482 messageListAdapter = new MessageAdapter((ConversationActivity) getActivity(), this.messageList);
483 messageListAdapter.setOnContactPictureClicked(new OnContactPictureClicked() {
484
485 @Override
486 public void onContactPictureClicked(Message message) {
487 if (message.getStatus() <= Message.STATUS_RECEIVED) {
488 if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
489 Jid user = message.getCounterpart();
490 if (user != null && !user.isBareJid()) {
491 if (!message.getConversation().getMucOptions().isUserInRoom(user)) {
492 Toast.makeText(activity,activity.getString(R.string.user_has_left_conference,user.getResourcepart()),Toast.LENGTH_SHORT).show();
493 }
494 highlightInConference(user.getResourcepart());
495 }
496 } else {
497 if (!message.getContact().isSelf()) {
498 String fingerprint;
499 if (message.getEncryption() == Message.ENCRYPTION_PGP
500 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
501 fingerprint = "pgp";
502 } else {
503 fingerprint = message.getFingerprint();
504 }
505 activity.switchToContactDetails(message.getContact(), fingerprint);
506 }
507 }
508 } else {
509 Account account = message.getConversation().getAccount();
510 Intent intent;
511 if (activity.manuallyChangePresence()) {
512 intent = new Intent(activity, SetPresenceActivity.class);
513 intent.putExtra(SetPresenceActivity.EXTRA_ACCOUNT, account.getJid().toBareJid().toString());
514 } else {
515 intent = new Intent(activity, EditAccountActivity.class);
516 intent.putExtra("jid", account.getJid().toBareJid().toString());
517 String fingerprint;
518 if (message.getEncryption() == Message.ENCRYPTION_PGP
519 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
520 fingerprint = "pgp";
521 } else if (message.getEncryption() == Message.ENCRYPTION_OTR) {
522 fingerprint = "otr";
523 } else {
524 fingerprint = message.getFingerprint();
525 }
526 intent.putExtra("fingerprint", fingerprint);
527 }
528 startActivity(intent);
529 }
530 }
531 });
532 messageListAdapter
533 .setOnContactPictureLongClicked(new OnContactPictureLongClicked() {
534
535 @Override
536 public void onContactPictureLongClicked(Message message) {
537 if (message.getStatus() <= Message.STATUS_RECEIVED) {
538 if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
539 Jid user = message.getCounterpart();
540 if (user != null && !user.isBareJid()) {
541 if (message.getConversation().getMucOptions().isUserInRoom(user)) {
542 privateMessageWith(user);
543 } else {
544 Toast.makeText(activity, activity.getString(R.string.user_has_left_conference, user.getResourcepart()), Toast.LENGTH_SHORT).show();
545 }
546 }
547 }
548 } else {
549 activity.showQrCode();
550 }
551 }
552 });
553 messageListAdapter.setOnQuoteListener(new MessageAdapter.OnQuoteListener() {
554
555 @Override
556 public void onQuote(String text) {
557 if (mEditMessage.isEnabled()) {
558 text = text.replaceAll("(\n *){2,}", "\n").replaceAll("(^|\n)", "$1> ").replaceAll("\n$", "");
559 Editable editable = mEditMessage.getEditableText();
560 int position = mEditMessage.getSelectionEnd();
561 if (position == -1) position = editable.length();
562 if (position > 0 && editable.charAt(position - 1) != '\n') {
563 editable.insert(position++, "\n");
564 }
565 editable.insert(position, text);
566 position += text.length();
567 editable.insert(position++, "\n");
568 if (position < editable.length() && editable.charAt(position) != '\n') {
569 editable.insert(position, "\n");
570 }
571 mEditMessage.setSelection(position);
572 mEditMessage.requestFocus();
573 InputMethodManager inputMethodManager = (InputMethodManager) getActivity()
574 .getSystemService(Context.INPUT_METHOD_SERVICE);
575 if (inputMethodManager != null) {
576 inputMethodManager.showSoftInput(mEditMessage, InputMethodManager.SHOW_IMPLICIT);
577 }
578 }
579 }
580 });
581 messagesView.setAdapter(messageListAdapter);
582
583 registerForContextMenu(messagesView);
584
585 return view;
586 }
587
588 @Override
589 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
590 synchronized (this.messageList) {
591 super.onCreateContextMenu(menu, v, menuInfo);
592 AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
593 this.selectedMessage = this.messageList.get(acmi.position);
594 populateContextMenu(menu);
595 }
596 }
597
598 private void populateContextMenu(ContextMenu menu) {
599 final Message m = this.selectedMessage;
600 final Transferable t = m.getTransferable();
601 Message relevantForCorrection = m;
602 while(relevantForCorrection.mergeable(relevantForCorrection.next())) {
603 relevantForCorrection = relevantForCorrection.next();
604 }
605 if (m.getType() != Message.TYPE_STATUS) {
606 final boolean treatAsFile = m.getType() != Message.TYPE_TEXT
607 && m.getType() != Message.TYPE_PRIVATE
608 && t == null;
609 activity.getMenuInflater().inflate(R.menu.message_context, menu);
610 menu.setHeaderTitle(R.string.message_options);
611 MenuItem selectText = menu.findItem(R.id.select_text);
612 MenuItem retryDecryption = menu.findItem(R.id.retry_decryption);
613 MenuItem correctMessage = menu.findItem(R.id.correct_message);
614 MenuItem shareWith = menu.findItem(R.id.share_with);
615 MenuItem sendAgain = menu.findItem(R.id.send_again);
616 MenuItem copyUrl = menu.findItem(R.id.copy_url);
617 MenuItem downloadFile = menu.findItem(R.id.download_file);
618 MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
619 MenuItem deleteFile = menu.findItem(R.id.delete_file);
620 MenuItem showErrorMessage = menu.findItem(R.id.show_error_message);
621 if (!treatAsFile && !GeoHelper.isGeoUri(m.getBody()) && !m.treatAsDownloadable()) {
622 selectText.setVisible(ListSelectionManager.isSupported());
623 }
624 if (m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED) {
625 retryDecryption.setVisible(true);
626 }
627 if (relevantForCorrection.getType() == Message.TYPE_TEXT
628 && relevantForCorrection.isLastCorrectableMessage()
629 && (m.getConversation().getMucOptions().nonanonymous() || m.getConversation().getMode() == Conversation.MODE_SINGLE)) {
630 correctMessage.setVisible(true);
631 }
632 if (treatAsFile || (m.getType() == Message.TYPE_TEXT && !m.treatAsDownloadable())) {
633 shareWith.setVisible(true);
634 }
635 if (m.getStatus() == Message.STATUS_SEND_FAILED) {
636 sendAgain.setVisible(true);
637 }
638 if (m.hasFileOnRemoteHost()
639 || GeoHelper.isGeoUri(m.getBody())
640 || m.treatAsDownloadable()
641 || (t != null && t instanceof HttpDownloadConnection)) {
642 copyUrl.setVisible(true);
643 }
644 if ((m.isFileOrImage() && t instanceof TransferablePlaceholder && m.hasFileOnRemoteHost())) {
645 downloadFile.setVisible(true);
646 downloadFile.setTitle(activity.getString(R.string.download_x_file,UIHelper.getFileDescriptionString(activity, m)));
647 }
648 boolean waitingOfferedSending = m.getStatus() == Message.STATUS_WAITING
649 || m.getStatus() == Message.STATUS_UNSEND
650 || m.getStatus() == Message.STATUS_OFFERED;
651 if ((t != null && !(t instanceof TransferablePlaceholder)) || waitingOfferedSending && m.needsUploading()) {
652 cancelTransmission.setVisible(true);
653 }
654 if (treatAsFile) {
655 String path = m.getRelativeFilePath();
656 if (path == null || !path.startsWith("/")) {
657 deleteFile.setVisible(true);
658 deleteFile.setTitle(activity.getString(R.string.delete_x_file, UIHelper.getFileDescriptionString(activity, m)));
659 }
660 }
661 if (m.getStatus() == Message.STATUS_SEND_FAILED && m.getErrorMessage() != null) {
662 showErrorMessage.setVisible(true);
663 }
664 }
665 }
666
667 @Override
668 public boolean onContextItemSelected(MenuItem item) {
669 switch (item.getItemId()) {
670 case R.id.share_with:
671 shareWith(selectedMessage);
672 return true;
673 case R.id.select_text:
674 selectText(selectedMessage);
675 return true;
676 case R.id.correct_message:
677 correctMessage(selectedMessage);
678 return true;
679 case R.id.send_again:
680 resendMessage(selectedMessage);
681 return true;
682 case R.id.copy_url:
683 copyUrl(selectedMessage);
684 return true;
685 case R.id.download_file:
686 downloadFile(selectedMessage);
687 return true;
688 case R.id.cancel_transmission:
689 cancelTransmission(selectedMessage);
690 return true;
691 case R.id.retry_decryption:
692 retryDecryption(selectedMessage);
693 return true;
694 case R.id.delete_file:
695 deleteFile(selectedMessage);
696 return true;
697 case R.id.show_error_message:
698 showErrorMessage(selectedMessage);
699 return true;
700 default:
701 return super.onContextItemSelected(item);
702 }
703 }
704
705 private void showErrorMessage(final Message message) {
706 AlertDialog.Builder builder = new AlertDialog.Builder(activity);
707 builder.setTitle(R.string.error_message);
708 builder.setMessage(message.getErrorMessage());
709 builder.setPositiveButton(R.string.confirm,null);
710 builder.create().show();
711 }
712
713 private void shareWith(Message message) {
714 Intent shareIntent = new Intent();
715 shareIntent.setAction(Intent.ACTION_SEND);
716 if (GeoHelper.isGeoUri(message.getBody())) {
717 shareIntent.putExtra(Intent.EXTRA_TEXT, message.getBody());
718 shareIntent.setType("text/plain");
719 } else if (!message.isFileOrImage()) {
720 shareIntent.putExtra(Intent.EXTRA_TEXT, message.getMergedBody().toString());
721 shareIntent.setType("text/plain");
722 } else {
723 final DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
724 try {
725 shareIntent.putExtra(Intent.EXTRA_STREAM, FileBackend.getUriForFile(activity, file));
726 } catch (SecurityException e) {
727 Toast.makeText(activity, activity.getString(R.string.no_permission_to_access_x, file.getAbsolutePath()), Toast.LENGTH_SHORT).show();
728 return;
729 }
730 shareIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
731 String mime = message.getMimeType();
732 if (mime == null) {
733 mime = "*/*";
734 }
735 shareIntent.setType(mime);
736 }
737 try {
738 activity.startActivity(Intent.createChooser(shareIntent, getText(R.string.share_with)));
739 } catch (ActivityNotFoundException e) {
740 //This should happen only on faulty androids because normally chooser is always available
741 Toast.makeText(activity,R.string.no_application_found_to_open_file,Toast.LENGTH_SHORT).show();
742 }
743 }
744
745 private void selectText(Message message) {
746 final int index;
747 synchronized (this.messageList) {
748 index = this.messageList.indexOf(message);
749 }
750 if (index >= 0) {
751 final int first = this.messagesView.getFirstVisiblePosition();
752 final int last = first + this.messagesView.getChildCount();
753 if (index >= first && index < last) {
754 final View view = this.messagesView.getChildAt(index - first);
755 final TextView messageBody = this.messageListAdapter.getMessageBody(view);
756 if (messageBody != null) {
757 ListSelectionManager.startSelection(messageBody);
758 }
759 }
760 }
761 }
762
763 private void deleteFile(Message message) {
764 if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
765 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
766 activity.updateConversationList();
767 updateMessages();
768 }
769 }
770
771 private void resendMessage(Message message) {
772 if (message.getType() == Message.TYPE_FILE || message.getType() == Message.TYPE_IMAGE) {
773 DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
774 if (!file.exists()) {
775 Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
776 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
777 activity.updateConversationList();
778 updateMessages();
779 return;
780 }
781 }
782 activity.xmppConnectionService.resendFailedMessages(message);
783 }
784
785 private void copyUrl(Message message) {
786 final String url;
787 final int resId;
788 if (GeoHelper.isGeoUri(message.getBody())) {
789 resId = R.string.location;
790 url = message.getBody();
791 } else if (message.hasFileOnRemoteHost()) {
792 resId = R.string.file_url;
793 url = message.getFileParams().url.toString();
794 } else {
795 url = message.getBody().trim();
796 resId = R.string.file_url;
797 }
798 if (activity.copyTextToClipboard(url, resId)) {
799 Toast.makeText(activity, R.string.url_copied_to_clipboard,
800 Toast.LENGTH_SHORT).show();
801 }
802 }
803
804 private void downloadFile(Message message) {
805 activity.xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message,true);
806 }
807
808 private void cancelTransmission(Message message) {
809 Transferable transferable = message.getTransferable();
810 if (transferable != null) {
811 transferable.cancel();
812 } else if (message.getStatus() != Message.STATUS_RECEIVED) {
813 activity.xmppConnectionService.markMessage(message,Message.STATUS_SEND_FAILED);
814 }
815 }
816
817 private void retryDecryption(Message message) {
818 message.setEncryption(Message.ENCRYPTION_PGP);
819 activity.updateConversationList();
820 updateMessages();
821 conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
822 }
823
824 protected void privateMessageWith(final Jid counterpart) {
825 if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
826 activity.xmppConnectionService.sendChatState(conversation);
827 }
828 this.mEditMessage.setText("");
829 this.conversation.setNextCounterpart(counterpart);
830 updateChatMsgHint();
831 updateSendButton();
832 updateEditablity();
833 }
834
835 private void correctMessage(Message message) {
836 while(message.mergeable(message.next())) {
837 message = message.next();
838 }
839 this.conversation.setCorrectingMessage(message);
840 final Editable editable = mEditMessage.getText();
841 this.conversation.setDraftMessage(editable.toString());
842 this.mEditMessage.setText("");
843 this.mEditMessage.append(message.getBody());
844
845 }
846
847 protected void highlightInConference(String nick) {
848 final Editable editable = mEditMessage.getText();
849 String oldString = editable.toString().trim();
850 final int pos = mEditMessage.getSelectionStart();
851 if (oldString.isEmpty() || pos == 0) {
852 editable.insert(0, nick + ": ");
853 } else {
854 final char before = editable.charAt(pos - 1);
855 final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
856 if (before == '\n') {
857 editable.insert(pos, nick + ": ");
858 } else {
859 if (pos > 2 && editable.subSequence(pos-2,pos).toString().equals(": ")) {
860 if (NickValidityChecker.check(conversation,Arrays.asList(editable.subSequence(0,pos-2).toString().split(", ")))) {
861 editable.insert(pos - 2, ", " + nick);
862 return;
863 }
864 }
865 editable.insert(pos, (Character.isWhitespace(before) ? "" : " ") + nick + (Character.isWhitespace(after) ? "" : " "));
866 if (Character.isWhitespace(after)) {
867 mEditMessage.setSelection(mEditMessage.getSelectionStart() + 1);
868 }
869 }
870 }
871 }
872
873 @Override
874 public void onStop() {
875 super.onStop();
876 if (this.conversation != null) {
877 final String msg = mEditMessage.getText().toString();
878 this.conversation.setNextMessage(msg);
879 updateChatState(this.conversation, msg);
880 }
881 }
882
883 private void updateChatState(final Conversation conversation, final String msg) {
884 ChatState state = msg.length() == 0 ? Config.DEFAULT_CHATSTATE : ChatState.PAUSED;
885 Account.State status = conversation.getAccount().getStatus();
886 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
887 activity.xmppConnectionService.sendChatState(conversation);
888 }
889 }
890
891 public boolean reInit(Conversation conversation) {
892 if (conversation == null) {
893 return false;
894 }
895 this.activity = (ConversationActivity) getActivity();
896 setupIme();
897 if (this.conversation != null) {
898 final String msg = mEditMessage.getText().toString();
899 this.conversation.setNextMessage(msg);
900 if (this.conversation != conversation) {
901 updateChatState(this.conversation, msg);
902 }
903 this.conversation.trim();
904
905 }
906
907 if (activity != null) {
908 this.mSendButton.setContentDescription(activity.getString(R.string.send_message_to_x,conversation.getName()));
909 }
910
911 this.conversation = conversation;
912 this.mEditMessage.setKeyboardListener(null);
913 this.mEditMessage.setText("");
914 this.mEditMessage.append(this.conversation.getNextMessage());
915 this.mEditMessage.setKeyboardListener(this);
916 messageListAdapter.updatePreferences();
917 this.messagesView.setAdapter(messageListAdapter);
918 updateMessages();
919 this.conversation.messagesLoaded.set(true);
920 synchronized (this.messageList) {
921 final Message first = conversation.getFirstUnreadMessage();
922 final int bottom = Math.max(0, this.messageList.size() - 1);
923 final int pos;
924 if (first == null) {
925 pos = bottom;
926 } else {
927 int i = getIndexOf(first.getUuid(), this.messageList);
928 pos = i < 0 ? bottom : i;
929 }
930 messagesView.setSelection(pos);
931 return pos == bottom;
932 }
933 }
934
935 private OnClickListener mEnableAccountListener = new OnClickListener() {
936 @Override
937 public void onClick(View v) {
938 final Account account = conversation == null ? null : conversation.getAccount();
939 if (account != null) {
940 account.setOption(Account.OPTION_DISABLED, false);
941 activity.xmppConnectionService.updateAccount(account);
942 }
943 }
944 };
945
946 private OnClickListener mUnblockClickListener = new OnClickListener() {
947 @Override
948 public void onClick(final View v) {
949 v.post(new Runnable() {
950 @Override
951 public void run() {
952 v.setVisibility(View.INVISIBLE);
953 }
954 });
955 if (conversation.isDomainBlocked()) {
956 BlockContactDialog.show(activity, conversation);
957 } else {
958 activity.unblockConversation(conversation);
959 }
960 }
961 };
962
963 private OnClickListener mBlockClickListener = new OnClickListener() {
964 @Override
965 public void onClick(final View view) {
966 final Jid jid = conversation.getJid();
967 if (jid.isDomainJid()) {
968 BlockContactDialog.show(activity, conversation);
969 } else {
970 PopupMenu popupMenu = new PopupMenu(activity, view);
971 popupMenu.inflate(R.menu.block);
972 popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
973 @Override
974 public boolean onMenuItemClick(MenuItem menuItem) {
975 Blockable blockable;
976 switch (menuItem.getItemId()) {
977 case R.id.block_domain:
978 blockable = conversation.getAccount().getRoster().getContact(jid.toDomainJid());
979 break;
980 default:
981 blockable = conversation;
982 }
983 BlockContactDialog.show(activity, blockable);
984 return true;
985 }
986 });
987 popupMenu.show();
988 }
989 }
990 };
991
992 private OnClickListener mAddBackClickListener = new OnClickListener() {
993
994 @Override
995 public void onClick(View v) {
996 final Contact contact = conversation == null ? null : conversation.getContact();
997 if (contact != null) {
998 activity.xmppConnectionService.createContact(contact);
999 activity.switchToContactDetails(contact);
1000 }
1001 }
1002 };
1003
1004 private OnClickListener mAllowPresenceSubscription = new OnClickListener() {
1005 @Override
1006 public void onClick(View v) {
1007 final Contact contact = conversation == null ? null : conversation.getContact();
1008 if (contact != null) {
1009 activity.xmppConnectionService.sendPresencePacket(contact.getAccount(),
1010 activity.xmppConnectionService.getPresenceGenerator()
1011 .sendPresenceUpdatesTo(contact));
1012 hideSnackbar();
1013 }
1014 }
1015 };
1016
1017 private OnClickListener mAnswerSmpClickListener = new OnClickListener() {
1018 @Override
1019 public void onClick(View view) {
1020 Intent intent = new Intent(activity, VerifyOTRActivity.class);
1021 intent.setAction(VerifyOTRActivity.ACTION_VERIFY_CONTACT);
1022 intent.putExtra("contact", conversation.getContact().getJid().toBareJid().toString());
1023 intent.putExtra(VerifyOTRActivity.EXTRA_ACCOUNT, conversation.getAccount().getJid().toBareJid().toString());
1024 intent.putExtra("mode", VerifyOTRActivity.MODE_ANSWER_QUESTION);
1025 startActivity(intent);
1026 }
1027 };
1028
1029 private void updateSnackBar(final Conversation conversation) {
1030 final Account account = conversation.getAccount();
1031 final XmppConnection connection = account.getXmppConnection();
1032 final int mode = conversation.getMode();
1033 final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
1034 if (account.getStatus() == Account.State.DISABLED) {
1035 showSnackbar(R.string.this_account_is_disabled, R.string.enable, this.mEnableAccountListener);
1036 } else if (conversation.isBlocked()) {
1037 showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
1038 } else if (contact != null && !contact.showInRoster() && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1039 showSnackbar(R.string.contact_added_you, R.string.add_back, this.mAddBackClickListener);
1040 } else if (contact != null && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1041 showSnackbar(R.string.contact_asks_for_presence_subscription, R.string.allow, this.mAllowPresenceSubscription);
1042 } else if (mode == Conversation.MODE_MULTI
1043 && !conversation.getMucOptions().online()
1044 && account.getStatus() == Account.State.ONLINE) {
1045 switch (conversation.getMucOptions().getError()) {
1046 case NICK_IN_USE:
1047 showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
1048 break;
1049 case NO_RESPONSE:
1050 showSnackbar(R.string.joining_conference, 0, null);
1051 break;
1052 case SERVER_NOT_FOUND:
1053 if (conversation.receivedMessagesCount() > 0) {
1054 showSnackbar(R.string.remote_server_not_found,R.string.try_again, joinMuc);
1055 } else {
1056 showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
1057 }
1058 break;
1059 case PASSWORD_REQUIRED:
1060 showSnackbar(R.string.conference_requires_password, R.string.enter_password, enterPassword);
1061 break;
1062 case BANNED:
1063 showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
1064 break;
1065 case MEMBERS_ONLY:
1066 showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
1067 break;
1068 case KICKED:
1069 showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
1070 break;
1071 case UNKNOWN:
1072 showSnackbar(R.string.conference_unknown_error, R.string.join, joinMuc);
1073 break;
1074 case SHUTDOWN:
1075 showSnackbar(R.string.conference_shutdown, R.string.join, joinMuc);
1076 break;
1077 default:
1078 hideSnackbar();
1079 break;
1080 }
1081 } else if (account.hasPendingPgpIntent(conversation)) {
1082 showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
1083 } else if (mode == Conversation.MODE_SINGLE
1084 && conversation.smpRequested()) {
1085 showSnackbar(R.string.smp_requested, R.string.verify, this.mAnswerSmpClickListener);
1086 } else if (mode == Conversation.MODE_SINGLE
1087 && conversation.hasValidOtrSession()
1088 && (conversation.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED)
1089 && (!conversation.isOtrFingerprintVerified())) {
1090 showSnackbar(R.string.unknown_otr_fingerprint, R.string.verify, clickToVerify);
1091 } else if (connection != null
1092 && connection.getFeatures().blocking()
1093 && conversation.countMessages() != 0
1094 && !conversation.isBlocked()
1095 && conversation.isWithStranger()) {
1096 showSnackbar(R.string.received_message_from_stranger,R.string.block, mBlockClickListener);
1097 } else {
1098 hideSnackbar();
1099 }
1100 }
1101
1102 public void updateMessages() {
1103 synchronized (this.messageList) {
1104 if (getView() == null) {
1105 return;
1106 }
1107 final ConversationActivity activity = (ConversationActivity) getActivity();
1108 if (this.conversation != null) {
1109 conversation.populateWithMessages(ConversationFragment.this.messageList);
1110 updateSnackBar(conversation);
1111 updateStatusMessages();
1112 this.messageListAdapter.notifyDataSetChanged();
1113 updateChatMsgHint();
1114 if (!activity.isConversationsOverviewVisable() || !activity.isConversationsOverviewHideable()) {
1115 activity.sendReadMarkerIfNecessary(conversation);
1116 }
1117 updateSendButton();
1118 updateEditablity();
1119 }
1120 }
1121 }
1122
1123 protected void messageSent() {
1124 mSendingPgpMessage.set(false);
1125 mEditMessage.setText("");
1126 if (conversation.setCorrectingMessage(null)) {
1127 mEditMessage.append(conversation.getDraftMessage());
1128 conversation.setDraftMessage(null);
1129 }
1130 conversation.setNextMessage(mEditMessage.getText().toString());
1131 updateChatMsgHint();
1132 new Handler().post(new Runnable() {
1133 @Override
1134 public void run() {
1135 int size = messageList.size();
1136 messagesView.setSelection(size - 1);
1137 }
1138 });
1139 }
1140
1141 public void setFocusOnInputField() {
1142 mEditMessage.requestFocus();
1143 }
1144
1145 public void doneSendingPgpMessage() {
1146 mSendingPgpMessage.set(false);
1147 }
1148
1149 enum SendButtonAction {TEXT, TAKE_PHOTO, SEND_LOCATION, RECORD_VOICE, CANCEL, CHOOSE_PICTURE}
1150
1151 private int getSendButtonImageResource(SendButtonAction action, Presence.Status status) {
1152 switch (action) {
1153 case TEXT:
1154 switch (status) {
1155 case CHAT:
1156 case ONLINE:
1157 return R.drawable.ic_send_text_online;
1158 case AWAY:
1159 return R.drawable.ic_send_text_away;
1160 case XA:
1161 case DND:
1162 return R.drawable.ic_send_text_dnd;
1163 default:
1164 return activity.getThemeResource(R.attr.ic_send_text_offline, R.drawable.ic_send_text_offline);
1165 }
1166 case TAKE_PHOTO:
1167 switch (status) {
1168 case CHAT:
1169 case ONLINE:
1170 return R.drawable.ic_send_photo_online;
1171 case AWAY:
1172 return R.drawable.ic_send_photo_away;
1173 case XA:
1174 case DND:
1175 return R.drawable.ic_send_photo_dnd;
1176 default:
1177 return activity.getThemeResource(R.attr.ic_send_photo_offline, R.drawable.ic_send_photo_offline);
1178 }
1179 case RECORD_VOICE:
1180 switch (status) {
1181 case CHAT:
1182 case ONLINE:
1183 return R.drawable.ic_send_voice_online;
1184 case AWAY:
1185 return R.drawable.ic_send_voice_away;
1186 case XA:
1187 case DND:
1188 return R.drawable.ic_send_voice_dnd;
1189 default:
1190 return activity.getThemeResource(R.attr.ic_send_voice_offline, R.drawable.ic_send_voice_offline);
1191 }
1192 case SEND_LOCATION:
1193 switch (status) {
1194 case CHAT:
1195 case ONLINE:
1196 return R.drawable.ic_send_location_online;
1197 case AWAY:
1198 return R.drawable.ic_send_location_away;
1199 case XA:
1200 case DND:
1201 return R.drawable.ic_send_location_dnd;
1202 default:
1203 return activity.getThemeResource(R.attr.ic_send_location_offline, R.drawable.ic_send_location_offline);
1204 }
1205 case CANCEL:
1206 switch (status) {
1207 case CHAT:
1208 case ONLINE:
1209 return R.drawable.ic_send_cancel_online;
1210 case AWAY:
1211 return R.drawable.ic_send_cancel_away;
1212 case XA:
1213 case DND:
1214 return R.drawable.ic_send_cancel_dnd;
1215 default:
1216 return activity.getThemeResource(R.attr.ic_send_cancel_offline, R.drawable.ic_send_cancel_offline);
1217 }
1218 case CHOOSE_PICTURE:
1219 switch (status) {
1220 case CHAT:
1221 case ONLINE:
1222 return R.drawable.ic_send_picture_online;
1223 case AWAY:
1224 return R.drawable.ic_send_picture_away;
1225 case XA:
1226 case DND:
1227 return R.drawable.ic_send_picture_dnd;
1228 default:
1229 return activity.getThemeResource(R.attr.ic_send_picture_offline, R.drawable.ic_send_picture_offline);
1230 }
1231 }
1232 return activity.getThemeResource(R.attr.ic_send_text_offline, R.drawable.ic_send_text_offline);
1233 }
1234
1235 private void updateEditablity() {
1236 boolean canWrite = this.conversation.getMode() == Conversation.MODE_SINGLE || this.conversation.getMucOptions().participating() || this.conversation.getNextCounterpart() != null;
1237 this.mEditMessage.setFocusable(canWrite);
1238 this.mEditMessage.setFocusableInTouchMode(canWrite);
1239 this.mSendButton.setEnabled(canWrite);
1240 this.mEditMessage.setCursorVisible(canWrite);
1241 }
1242
1243 public void updateSendButton() {
1244 final Conversation c = this.conversation;
1245 final SendButtonAction action;
1246 final Presence.Status status;
1247 final String text = this.mEditMessage == null ? "" : this.mEditMessage.getText().toString();
1248 final boolean empty = text.length() == 0;
1249 final boolean conference = c.getMode() == Conversation.MODE_MULTI;
1250 if (c.getCorrectingMessage() != null && (empty || text.equals(c.getCorrectingMessage().getBody()))) {
1251 action = SendButtonAction.CANCEL;
1252 } else if (conference && !c.getAccount().httpUploadAvailable()) {
1253 if (empty && c.getNextCounterpart() != null) {
1254 action = SendButtonAction.CANCEL;
1255 } else {
1256 action = SendButtonAction.TEXT;
1257 }
1258 } else {
1259 if (empty) {
1260 if (conference && c.getNextCounterpart() != null) {
1261 action = SendButtonAction.CANCEL;
1262 } else {
1263 String setting = activity.getPreferences().getString("quick_action", activity.getResources().getString(R.string.quick_action));
1264 if (!setting.equals("none") && UIHelper.receivedLocationQuestion(conversation.getLatestMessage())) {
1265 setting = "location";
1266 } else if (setting.equals("recent")) {
1267 setting = activity.getPreferences().getString("recently_used_quick_action", "text");
1268 }
1269 switch (setting) {
1270 case "photo":
1271 action = SendButtonAction.TAKE_PHOTO;
1272 break;
1273 case "location":
1274 action = SendButtonAction.SEND_LOCATION;
1275 break;
1276 case "voice":
1277 action = SendButtonAction.RECORD_VOICE;
1278 break;
1279 case "picture":
1280 action = SendButtonAction.CHOOSE_PICTURE;
1281 break;
1282 default:
1283 action = SendButtonAction.TEXT;
1284 break;
1285 }
1286 }
1287 } else {
1288 action = SendButtonAction.TEXT;
1289 }
1290 }
1291 if (activity.useSendButtonToIndicateStatus() && c.getAccount().getStatus() == Account.State.ONLINE) {
1292 if (activity.xmppConnectionService != null && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
1293 status = Presence.Status.OFFLINE;
1294 } else if (c.getMode() == Conversation.MODE_SINGLE) {
1295 status = c.getContact().getShownStatus();
1296 } else {
1297 status = c.getMucOptions().online() ? Presence.Status.ONLINE : Presence.Status.OFFLINE;
1298 }
1299 } else {
1300 status = Presence.Status.OFFLINE;
1301 }
1302 this.mSendButton.setTag(action);
1303 this.mSendButton.setImageResource(getSendButtonImageResource(action, status));
1304 }
1305
1306 protected void updateDateSeparators() {
1307 synchronized (this.messageList) {
1308 for(int i = 0; i < this.messageList.size(); ++i) {
1309 final Message current = this.messageList.get(i);
1310 if (i == 0 || !UIHelper.sameDay(this.messageList.get(i-1).getTimeSent(),current.getTimeSent())) {
1311 this.messageList.add(i,Message.createDateSeparator(current));
1312 i++;
1313 }
1314 }
1315 }
1316 }
1317
1318 protected void updateStatusMessages() {
1319 updateDateSeparators();
1320 synchronized (this.messageList) {
1321 if (showLoadMoreMessages(conversation)) {
1322 this.messageList.add(0, Message.createLoadMoreMessage(conversation));
1323 }
1324 if (conversation.getMode() == Conversation.MODE_SINGLE) {
1325 ChatState state = conversation.getIncomingChatState();
1326 if (state == ChatState.COMPOSING) {
1327 this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_is_typing, conversation.getName())));
1328 } else if (state == ChatState.PAUSED) {
1329 this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_has_stopped_typing, conversation.getName())));
1330 } else {
1331 for (int i = this.messageList.size() - 1; i >= 0; --i) {
1332 if (this.messageList.get(i).getStatus() == Message.STATUS_RECEIVED) {
1333 return;
1334 } else {
1335 if (this.messageList.get(i).getStatus() == Message.STATUS_SEND_DISPLAYED) {
1336 this.messageList.add(i + 1,
1337 Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, conversation.getName())));
1338 return;
1339 }
1340 }
1341 }
1342 }
1343 } else {
1344 ChatState state = ChatState.COMPOSING;
1345 List<MucOptions.User> users = conversation.getMucOptions().getUsersWithChatState(state,5);
1346 if (users.size() == 0) {
1347 state = ChatState.PAUSED;
1348 users = conversation.getMucOptions().getUsersWithChatState(state, 5);
1349
1350 }
1351 if (users.size() > 0) {
1352 Message statusMessage;
1353 if (users.size() == 1) {
1354 MucOptions.User user = users.get(0);
1355 int id = state == ChatState.COMPOSING ? R.string.contact_is_typing : R.string.contact_has_stopped_typing;
1356 statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.getDisplayName(user)));
1357 statusMessage.setTrueCounterpart(user.getRealJid());
1358 statusMessage.setCounterpart(user.getFullJid());
1359 } else {
1360 StringBuilder builder = new StringBuilder();
1361 for(MucOptions.User user : users) {
1362 if (builder.length() != 0) {
1363 builder.append(", ");
1364 }
1365 builder.append(UIHelper.getDisplayName(user));
1366 }
1367 int id = state == ChatState.COMPOSING ? R.string.contacts_are_typing : R.string.contacts_have_stopped_typing;
1368 statusMessage = Message.createStatusMessage(conversation, getString(id, builder.toString()));
1369 }
1370 this.messageList.add(statusMessage);
1371 }
1372
1373 }
1374 }
1375 }
1376
1377 private boolean showLoadMoreMessages(final Conversation c) {
1378 final boolean mam = hasMamSupport(c);
1379 final MessageArchiveService service = activity.xmppConnectionService.getMessageArchiveService();
1380 return mam && (c.getLastClearHistory().getTimestamp() != 0 || (c.countMessages() == 0 && c.messagesLoaded.get() && c.hasMessagesLeftOnServer() && !service.queryInProgress(c)));
1381 }
1382
1383 private boolean hasMamSupport(final Conversation c) {
1384 if (c.getMode() == Conversation.MODE_SINGLE) {
1385 final XmppConnection connection = c.getAccount().getXmppConnection();
1386 return connection != null && connection.getFeatures().mam();
1387 } else {
1388 return c.getMucOptions().mamSupport();
1389 }
1390 }
1391
1392 protected void showSnackbar(final int message, final int action, final OnClickListener clickListener) {
1393 snackbar.setVisibility(View.VISIBLE);
1394 snackbar.setOnClickListener(null);
1395 snackbarMessage.setText(message);
1396 snackbarMessage.setOnClickListener(null);
1397 snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
1398 if (action != 0) {
1399 snackbarAction.setText(action);
1400 }
1401 snackbarAction.setOnClickListener(clickListener);
1402 }
1403
1404 protected void hideSnackbar() {
1405 snackbar.setVisibility(View.GONE);
1406 }
1407
1408 protected void sendPlainTextMessage(Message message) {
1409 ConversationActivity activity = (ConversationActivity) getActivity();
1410 activity.xmppConnectionService.sendMessage(message);
1411 messageSent();
1412 }
1413
1414 private AtomicBoolean mSendingPgpMessage = new AtomicBoolean(false);
1415
1416 protected void sendPgpMessage(final Message message) {
1417 final ConversationActivity activity = (ConversationActivity) getActivity();
1418 final XmppConnectionService xmppService = activity.xmppConnectionService;
1419 final Contact contact = message.getConversation().getContact();
1420 if (!activity.hasPgp()) {
1421 activity.showInstallPgpDialog();
1422 return;
1423 }
1424 if (conversation.getAccount().getPgpSignature() == null) {
1425 activity.announcePgp(conversation.getAccount(), conversation, activity.onOpenPGPKeyPublished);
1426 return;
1427 }
1428 if (!mSendingPgpMessage.compareAndSet(false,true)) {
1429 Log.d(Config.LOGTAG,"sending pgp message already in progress");
1430 }
1431 if (conversation.getMode() == Conversation.MODE_SINGLE) {
1432 if (contact.getPgpKeyId() != 0) {
1433 xmppService.getPgpEngine().hasKey(contact,
1434 new UiCallback<Contact>() {
1435
1436 @Override
1437 public void userInputRequried(PendingIntent pi,
1438 Contact contact) {
1439 activity.runIntent(
1440 pi,
1441 ConversationActivity.REQUEST_ENCRYPT_MESSAGE);
1442 }
1443
1444 @Override
1445 public void success(Contact contact) {
1446 activity.encryptTextMessage(message);
1447 }
1448
1449 @Override
1450 public void error(int error, Contact contact) {
1451 activity.runOnUiThread(new Runnable() {
1452 @Override
1453 public void run() {
1454 Toast.makeText(activity,
1455 R.string.unable_to_connect_to_keychain,
1456 Toast.LENGTH_SHORT
1457 ).show();
1458 }
1459 });
1460 mSendingPgpMessage.set(false);
1461 }
1462 });
1463
1464 } else {
1465 showNoPGPKeyDialog(false,
1466 new DialogInterface.OnClickListener() {
1467
1468 @Override
1469 public void onClick(DialogInterface dialog,
1470 int which) {
1471 conversation
1472 .setNextEncryption(Message.ENCRYPTION_NONE);
1473 xmppService.updateConversation(conversation);
1474 message.setEncryption(Message.ENCRYPTION_NONE);
1475 xmppService.sendMessage(message);
1476 messageSent();
1477 }
1478 });
1479 }
1480 } else {
1481 if (conversation.getMucOptions().pgpKeysInUse()) {
1482 if (!conversation.getMucOptions().everybodyHasKeys()) {
1483 Toast warning = Toast
1484 .makeText(getActivity(),
1485 R.string.missing_public_keys,
1486 Toast.LENGTH_LONG);
1487 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
1488 warning.show();
1489 }
1490 activity.encryptTextMessage(message);
1491 } else {
1492 showNoPGPKeyDialog(true,
1493 new DialogInterface.OnClickListener() {
1494
1495 @Override
1496 public void onClick(DialogInterface dialog,
1497 int which) {
1498 conversation
1499 .setNextEncryption(Message.ENCRYPTION_NONE);
1500 message.setEncryption(Message.ENCRYPTION_NONE);
1501 xmppService.updateConversation(conversation);
1502 xmppService.sendMessage(message);
1503 messageSent();
1504 }
1505 });
1506 }
1507 }
1508 }
1509
1510 public void showNoPGPKeyDialog(boolean plural,
1511 DialogInterface.OnClickListener listener) {
1512 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1513 builder.setIconAttribute(android.R.attr.alertDialogIcon);
1514 if (plural) {
1515 builder.setTitle(getString(R.string.no_pgp_keys));
1516 builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
1517 } else {
1518 builder.setTitle(getString(R.string.no_pgp_key));
1519 builder.setMessage(getText(R.string.contact_has_no_pgp_key));
1520 }
1521 builder.setNegativeButton(getString(R.string.cancel), null);
1522 builder.setPositiveButton(getString(R.string.send_unencrypted),
1523 listener);
1524 builder.create().show();
1525 }
1526
1527 protected void sendAxolotlMessage(final Message message) {
1528 final ConversationActivity activity = (ConversationActivity) getActivity();
1529 final XmppConnectionService xmppService = activity.xmppConnectionService;
1530 xmppService.sendMessage(message);
1531 messageSent();
1532 }
1533
1534 protected void sendOtrMessage(final Message message) {
1535 final ConversationActivity activity = (ConversationActivity) getActivity();
1536 final XmppConnectionService xmppService = activity.xmppConnectionService;
1537 activity.selectPresence(message.getConversation(),
1538 new OnPresenceSelected() {
1539
1540 @Override
1541 public void onPresenceSelected() {
1542 message.setCounterpart(conversation.getNextCounterpart());
1543 xmppService.sendMessage(message);
1544 messageSent();
1545 }
1546 });
1547 }
1548
1549 public void appendText(String text) {
1550 if (text == null) {
1551 return;
1552 }
1553 String previous = this.mEditMessage.getText().toString();
1554 if (previous.length() != 0 && !previous.endsWith(" ")) {
1555 text = " " + text;
1556 }
1557 this.mEditMessage.append(text);
1558 }
1559
1560 @Override
1561 public boolean onEnterPressed() {
1562 if (activity.enterIsSend()) {
1563 sendMessage();
1564 return true;
1565 } else {
1566 return false;
1567 }
1568 }
1569
1570 @Override
1571 public void onTypingStarted() {
1572 Account.State status = conversation.getAccount().getStatus();
1573 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
1574 activity.xmppConnectionService.sendChatState(conversation);
1575 }
1576 activity.hideConversationsOverview();
1577 updateSendButton();
1578 }
1579
1580 @Override
1581 public void onTypingStopped() {
1582 Account.State status = conversation.getAccount().getStatus();
1583 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
1584 activity.xmppConnectionService.sendChatState(conversation);
1585 }
1586 }
1587
1588 @Override
1589 public void onTextDeleted() {
1590 Account.State status = conversation.getAccount().getStatus();
1591 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1592 activity.xmppConnectionService.sendChatState(conversation);
1593 }
1594 updateSendButton();
1595 }
1596
1597 @Override
1598 public void onTextChanged() {
1599 if (conversation != null && conversation.getCorrectingMessage() != null) {
1600 updateSendButton();
1601 }
1602 }
1603
1604 private int completionIndex = 0;
1605 private int lastCompletionLength = 0;
1606 private String incomplete;
1607 private int lastCompletionCursor;
1608 private boolean firstWord = false;
1609
1610 @Override
1611 public boolean onTabPressed(boolean repeated) {
1612 if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
1613 return false;
1614 }
1615 if (repeated) {
1616 completionIndex++;
1617 } else {
1618 lastCompletionLength = 0;
1619 completionIndex = 0;
1620 final String content = mEditMessage.getText().toString();
1621 lastCompletionCursor = mEditMessage.getSelectionEnd();
1622 int start = lastCompletionCursor > 0 ? content.lastIndexOf(" ",lastCompletionCursor-1) + 1 : 0;
1623 firstWord = start == 0;
1624 incomplete = content.substring(start,lastCompletionCursor);
1625 }
1626 List<String> completions = new ArrayList<>();
1627 for(MucOptions.User user : conversation.getMucOptions().getUsers()) {
1628 String name = user.getName();
1629 if (name != null && name.startsWith(incomplete)) {
1630 completions.add(name+(firstWord ? ": " : " "));
1631 }
1632 }
1633 Collections.sort(completions);
1634 if (completions.size() > completionIndex) {
1635 String completion = completions.get(completionIndex).substring(incomplete.length());
1636 mEditMessage.getEditableText().delete(lastCompletionCursor,lastCompletionCursor + lastCompletionLength);
1637 mEditMessage.getEditableText().insert(lastCompletionCursor, completion);
1638 lastCompletionLength = completion.length();
1639 } else {
1640 completionIndex = -1;
1641 mEditMessage.getEditableText().delete(lastCompletionCursor,lastCompletionCursor + lastCompletionLength);
1642 lastCompletionLength = 0;
1643 }
1644 return true;
1645 }
1646
1647 @Override
1648 public void onActivityResult(int requestCode, int resultCode,
1649 final Intent data) {
1650 if (resultCode == Activity.RESULT_OK) {
1651 if (requestCode == ConversationActivity.REQUEST_DECRYPT_PGP) {
1652 activity.getSelectedConversation().getAccount().getPgpDecryptionService().continueDecryption(true);
1653 } else if (requestCode == ConversationActivity.REQUEST_TRUST_KEYS_TEXT) {
1654 final String body = mEditMessage.getText().toString();
1655 Message message = new Message(conversation, body, conversation.getNextEncryption());
1656 sendAxolotlMessage(message);
1657 } else if (requestCode == ConversationActivity.REQUEST_TRUST_KEYS_MENU) {
1658 int choice = data.getIntExtra("choice", ConversationActivity.ATTACHMENT_CHOICE_INVALID);
1659 activity.selectPresenceToAttachFile(choice, conversation.getNextEncryption());
1660 }
1661 }
1662 }
1663
1664}