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