1package eu.siacs.conversations.ui;
2
3import android.Manifest;
4import android.annotation.SuppressLint;
5import android.app.Activity;
6import android.content.SharedPreferences;
7import android.content.pm.PackageManager;
8import android.databinding.DataBindingUtil;
9import android.net.Uri;
10import android.os.Build;
11import android.preference.PreferenceManager;
12import android.provider.MediaStore;
13import android.support.annotation.IdRes;
14import android.support.v7.app.AlertDialog;
15import android.app.Fragment;
16import android.app.PendingIntent;
17import android.content.ActivityNotFoundException;
18import android.content.Context;
19import android.content.DialogInterface;
20import android.content.Intent;
21import android.content.IntentSender.SendIntentException;
22import android.os.Bundle;
23import android.os.Handler;
24import android.os.SystemClock;
25import android.support.v13.view.inputmethod.InputConnectionCompat;
26import android.support.v13.view.inputmethod.InputContentInfoCompat;
27import android.text.Editable;
28import android.util.Log;
29import android.util.Pair;
30import android.view.ContextMenu;
31import android.view.ContextMenu.ContextMenuInfo;
32import android.view.Gravity;
33import android.view.LayoutInflater;
34import android.view.Menu;
35import android.view.MenuInflater;
36import android.view.MenuItem;
37import android.view.MotionEvent;
38import android.view.View;
39import android.view.View.OnClickListener;
40import android.view.ViewGroup;
41import android.view.inputmethod.EditorInfo;
42import android.view.inputmethod.InputMethodManager;
43import android.widget.AbsListView;
44import android.widget.AbsListView.OnScrollListener;
45import android.widget.AdapterView;
46import android.widget.AdapterView.AdapterContextMenuInfo;
47import android.widget.CheckBox;
48import android.widget.ListView;
49import android.widget.PopupMenu;
50import android.widget.TextView.OnEditorActionListener;
51import android.widget.Toast;
52
53import org.openintents.openpgp.util.OpenPgpApi;
54
55import java.util.ArrayList;
56import java.util.Arrays;
57import java.util.Collections;
58import java.util.HashSet;
59import java.util.Iterator;
60import java.util.List;
61import java.util.Set;
62import java.util.UUID;
63import java.util.concurrent.atomic.AtomicBoolean;
64
65import eu.siacs.conversations.Config;
66import eu.siacs.conversations.R;
67import eu.siacs.conversations.crypto.axolotl.AxolotlService;
68import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
69import eu.siacs.conversations.databinding.FragmentConversationBinding;
70import eu.siacs.conversations.entities.Account;
71import eu.siacs.conversations.entities.Blockable;
72import eu.siacs.conversations.entities.Contact;
73import eu.siacs.conversations.entities.Conversation;
74import eu.siacs.conversations.entities.DownloadableFile;
75import eu.siacs.conversations.entities.Message;
76import eu.siacs.conversations.entities.MucOptions;
77import eu.siacs.conversations.entities.Presence;
78import eu.siacs.conversations.entities.ReadByMarker;
79import eu.siacs.conversations.entities.Transferable;
80import eu.siacs.conversations.entities.TransferablePlaceholder;
81import eu.siacs.conversations.http.HttpDownloadConnection;
82import eu.siacs.conversations.persistance.FileBackend;
83import eu.siacs.conversations.services.MessageArchiveService;
84import eu.siacs.conversations.services.XmppConnectionService;
85import eu.siacs.conversations.ui.adapter.MessageAdapter;
86import eu.siacs.conversations.ui.util.ActivityResult;
87import eu.siacs.conversations.ui.util.AttachmentTool;
88import eu.siacs.conversations.ui.util.ConversationMenuConfigurator;
89import eu.siacs.conversations.ui.util.PendingItem;
90import eu.siacs.conversations.ui.util.PresenceSelector;
91import eu.siacs.conversations.ui.util.ScrollState;
92import eu.siacs.conversations.ui.util.SendButtonAction;
93import eu.siacs.conversations.ui.util.SendButtonTool;
94import eu.siacs.conversations.ui.widget.EditMessage;
95import eu.siacs.conversations.utils.MessageUtils;
96import eu.siacs.conversations.utils.NickValidityChecker;
97import eu.siacs.conversations.utils.StylingHelper;
98import eu.siacs.conversations.utils.UIHelper;
99import eu.siacs.conversations.xmpp.XmppConnection;
100import eu.siacs.conversations.xmpp.chatstate.ChatState;
101import eu.siacs.conversations.xmpp.jid.InvalidJidException;
102import eu.siacs.conversations.xmpp.jid.Jid;
103
104import static eu.siacs.conversations.ui.XmppActivity.EXTRA_ACCOUNT;
105import static eu.siacs.conversations.ui.XmppActivity.REQUEST_ANNOUNCE_PGP;
106import static eu.siacs.conversations.ui.XmppActivity.REQUEST_CHOOSE_PGP_ID;
107
108
109public class ConversationFragment extends XmppFragment implements EditMessage.KeyboardListener {
110
111
112 public static final int REQUEST_SEND_MESSAGE = 0x0201;
113 public static final int REQUEST_DECRYPT_PGP = 0x0202;
114 public static final int REQUEST_ENCRYPT_MESSAGE = 0x0207;
115 public static final int REQUEST_TRUST_KEYS_TEXT = 0x0208;
116 public static final int REQUEST_TRUST_KEYS_MENU = 0x0209;
117 public static final int REQUEST_START_DOWNLOAD = 0x0210;
118 public static final int REQUEST_ADD_EDITOR_CONTENT = 0x0211;
119 public static final int ATTACHMENT_CHOICE_CHOOSE_IMAGE = 0x0301;
120 public static final int ATTACHMENT_CHOICE_TAKE_PHOTO = 0x0302;
121 public static final int ATTACHMENT_CHOICE_CHOOSE_FILE = 0x0303;
122 public static final int ATTACHMENT_CHOICE_RECORD_VOICE = 0x0304;
123 public static final int ATTACHMENT_CHOICE_LOCATION = 0x0305;
124 public static final int ATTACHMENT_CHOICE_INVALID = 0x0306;
125 public static final int ATTACHMENT_CHOICE_RECORD_VIDEO = 0x0307;
126
127 public static final String RECENTLY_USED_QUICK_ACTION = "recently_used_quick_action";
128 public static final String STATE_CONVERSATION_UUID = ConversationFragment.class.getName() + ".uuid";
129 public static final String STATE_SCROLL_POSITION = ConversationFragment.class.getName() + ".scroll_position";
130 public static final String STATE_PHOTO_URI = ConversationFragment.class.getName() + ".take_photo_uri";
131
132
133 final protected List<Message> messageList = new ArrayList<>();
134 private final PendingItem<ActivityResult> postponedActivityResult = new PendingItem<>();
135 private final PendingItem<String> pendingConversationsUuid = new PendingItem<>();
136 private final PendingItem<Bundle> pendingExtras = new PendingItem<>();
137 private final PendingItem<Uri> pendingTakePhotoUri = new PendingItem<>();
138 private final PendingItem<ScrollState> pendingScrollState = new PendingItem<>();
139 public Uri mPendingEditorContent = null;
140 protected MessageAdapter messageListAdapter;
141 private Conversation conversation;
142 private FragmentConversationBinding binding;
143 private Toast messageLoaderToast;
144 private ConversationActivity activity;
145
146 private boolean reInitRequiredOnStart = true;
147
148 private OnClickListener clickToMuc = new OnClickListener() {
149
150 @Override
151 public void onClick(View v) {
152 Intent intent = new Intent(getActivity(), ConferenceDetailsActivity.class);
153 intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
154 intent.putExtra("uuid", conversation.getUuid());
155 startActivity(intent);
156 }
157 };
158 private OnClickListener leaveMuc = new OnClickListener() {
159
160 @Override
161 public void onClick(View v) {
162 activity.xmppConnectionService.archiveConversation(conversation);
163 activity.onConversationArchived(conversation);
164 }
165 };
166 private OnClickListener joinMuc = new OnClickListener() {
167
168 @Override
169 public void onClick(View v) {
170 activity.xmppConnectionService.joinMuc(conversation);
171 }
172 };
173 private OnClickListener enterPassword = new OnClickListener() {
174
175 @Override
176 public void onClick(View v) {
177 MucOptions muc = conversation.getMucOptions();
178 String password = muc.getPassword();
179 if (password == null) {
180 password = "";
181 }
182 activity.quickPasswordEdit(password, value -> {
183 activity.xmppConnectionService.providePasswordForMuc(conversation, value);
184 return null;
185 });
186 }
187 };
188 private OnScrollListener mOnScrollListener = new OnScrollListener() {
189
190 @Override
191 public void onScrollStateChanged(AbsListView view, int scrollState) {
192 // TODO Auto-generated method stub
193
194 }
195
196 @Override
197 public void onScroll(final AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
198 synchronized (ConversationFragment.this.messageList) {
199 if (firstVisibleItem < 5 && conversation != null && conversation.messagesLoaded.compareAndSet(true, false) && messageList.size() > 0) {
200 long timestamp;
201 if (messageList.get(0).getType() == Message.TYPE_STATUS && messageList.size() >= 2) {
202 timestamp = messageList.get(1).getTimeSent();
203 } else {
204 timestamp = messageList.get(0).getTimeSent();
205 }
206 activity.xmppConnectionService.loadMoreMessages(conversation, timestamp, new XmppConnectionService.OnMoreMessagesLoaded() {
207 @Override
208 public void onMoreMessagesLoaded(final int c, final Conversation conversation) {
209 if (ConversationFragment.this.conversation != conversation) {
210 conversation.messagesLoaded.set(true);
211 return;
212 }
213 runOnUiThread(() -> {
214 final int oldPosition = binding.messagesView.getFirstVisiblePosition();
215 Message message = null;
216 int childPos;
217 for (childPos = 0; childPos + oldPosition < messageList.size(); ++childPos) {
218 message = messageList.get(oldPosition + childPos);
219 if (message.getType() != Message.TYPE_STATUS) {
220 break;
221 }
222 }
223 final String uuid = message != null ? message.getUuid() : null;
224 View v = binding.messagesView.getChildAt(childPos);
225 final int pxOffset = (v == null) ? 0 : v.getTop();
226 ConversationFragment.this.conversation.populateWithMessages(ConversationFragment.this.messageList);
227 try {
228 updateStatusMessages();
229 } catch (IllegalStateException e) {
230 Log.d(Config.LOGTAG, "caught illegal state exception while updating status messages");
231 }
232 messageListAdapter.notifyDataSetChanged();
233 int pos = Math.max(getIndexOf(uuid, messageList), 0);
234 binding.messagesView.setSelectionFromTop(pos, pxOffset);
235 if (messageLoaderToast != null) {
236 messageLoaderToast.cancel();
237 }
238 conversation.messagesLoaded.set(true);
239 });
240 }
241
242 @Override
243 public void informUser(final int resId) {
244
245 runOnUiThread(() -> {
246 if (messageLoaderToast != null) {
247 messageLoaderToast.cancel();
248 }
249 if (ConversationFragment.this.conversation != conversation) {
250 return;
251 }
252 messageLoaderToast = Toast.makeText(view.getContext(), resId, Toast.LENGTH_LONG);
253 messageLoaderToast.show();
254 });
255
256 }
257 });
258
259 }
260 }
261 }
262 };
263
264 private EditMessage.OnCommitContentListener mEditorContentListener = new EditMessage.OnCommitContentListener() {
265 @Override
266 public boolean onCommitContent(InputContentInfoCompat inputContentInfo, int flags, Bundle opts, String[] contentMimeTypes) {
267 // try to get permission to read the image, if applicable
268 if ((flags & InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION) != 0) {
269 try {
270 inputContentInfo.requestPermission();
271 } catch (Exception e) {
272 Log.e(Config.LOGTAG, "InputContentInfoCompat#requestPermission() failed.", e);
273 Toast.makeText(getActivity(), activity.getString(R.string.no_permission_to_access_x, inputContentInfo.getDescription()), Toast.LENGTH_LONG
274 ).show();
275 return false;
276 }
277 }
278 if (hasStoragePermission(REQUEST_ADD_EDITOR_CONTENT)) {
279 attachImageToConversation(inputContentInfo.getContentUri());
280 } else {
281 mPendingEditorContent = inputContentInfo.getContentUri();
282 }
283 return true;
284 }
285 };
286 private Message selectedMessage;
287 private OnClickListener mEnableAccountListener = new OnClickListener() {
288 @Override
289 public void onClick(View v) {
290 final Account account = conversation == null ? null : conversation.getAccount();
291 if (account != null) {
292 account.setOption(Account.OPTION_DISABLED, false);
293 activity.xmppConnectionService.updateAccount(account);
294 }
295 }
296 };
297 private OnClickListener mUnblockClickListener = new OnClickListener() {
298 @Override
299 public void onClick(final View v) {
300 v.post(() -> v.setVisibility(View.INVISIBLE));
301 if (conversation.isDomainBlocked()) {
302 BlockContactDialog.show(activity, conversation);
303 } else {
304 unblockConversation(conversation);
305 }
306 }
307 };
308 private OnClickListener mBlockClickListener = this::showBlockSubmenu;
309 private OnClickListener mAddBackClickListener = new OnClickListener() {
310
311 @Override
312 public void onClick(View v) {
313 final Contact contact = conversation == null ? null : conversation.getContact();
314 if (contact != null) {
315 activity.xmppConnectionService.createContact(contact);
316 activity.switchToContactDetails(contact);
317 }
318 }
319 };
320 private View.OnLongClickListener mLongPressBlockListener = this::showBlockSubmenu;
321 private OnClickListener mAllowPresenceSubscription = new OnClickListener() {
322 @Override
323 public void onClick(View v) {
324 final Contact contact = conversation == null ? null : conversation.getContact();
325 if (contact != null) {
326 activity.xmppConnectionService.sendPresencePacket(contact.getAccount(),
327 activity.xmppConnectionService.getPresenceGenerator()
328 .sendPresenceUpdatesTo(contact));
329 hideSnackbar();
330 }
331 }
332 };
333
334 protected OnClickListener clickToDecryptListener = new OnClickListener() {
335
336 @Override
337 public void onClick(View v) {
338 PendingIntent pendingIntent = conversation.getAccount().getPgpDecryptionService().getPendingIntent();
339 if (pendingIntent != null) {
340 try {
341 getActivity().startIntentSenderForResult(pendingIntent.getIntentSender(),
342 REQUEST_DECRYPT_PGP,
343 null,
344 0,
345 0,
346 0);
347 } catch (SendIntentException e) {
348 Toast.makeText(getActivity(), R.string.unable_to_connect_to_keychain, Toast.LENGTH_SHORT).show();
349 conversation.getAccount().getPgpDecryptionService().continueDecryption(true);
350 }
351 }
352 updateSnackBar(conversation);
353 }
354 };
355 private AtomicBoolean mSendingPgpMessage = new AtomicBoolean(false);
356 private OnEditorActionListener mEditorActionListener = (v, actionId, event) -> {
357 if (actionId == EditorInfo.IME_ACTION_SEND) {
358 InputMethodManager imm = (InputMethodManager) v.getContext()
359 .getSystemService(Context.INPUT_METHOD_SERVICE);
360 if (imm.isFullscreenMode()) {
361 imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
362 }
363 sendMessage();
364 return true;
365 } else {
366 return false;
367 }
368 };
369 private OnClickListener mSendButtonListener = new OnClickListener() {
370
371 @Override
372 public void onClick(View v) {
373 Object tag = v.getTag();
374 if (tag instanceof SendButtonAction) {
375 SendButtonAction action = (SendButtonAction) tag;
376 switch (action) {
377 case TAKE_PHOTO:
378 case RECORD_VIDEO:
379 case SEND_LOCATION:
380 case RECORD_VOICE:
381 case CHOOSE_PICTURE:
382 attachFile(action.toChoice());
383 break;
384 case CANCEL:
385 if (conversation != null) {
386 if (conversation.setCorrectingMessage(null)) {
387 binding.textinput.setText("");
388 binding.textinput.append(conversation.getDraftMessage());
389 conversation.setDraftMessage(null);
390 } else if (conversation.getMode() == Conversation.MODE_MULTI) {
391 conversation.setNextCounterpart(null);
392 }
393 updateChatMsgHint();
394 updateSendButton();
395 updateEditablity();
396 }
397 break;
398 default:
399 sendMessage();
400 }
401 } else {
402 sendMessage();
403 }
404 }
405 };
406 private int completionIndex = 0;
407 private int lastCompletionLength = 0;
408 private String incomplete;
409 private int lastCompletionCursor;
410 private boolean firstWord = false;
411 private Message mPendingDownloadableMessage;
412
413 public static void downloadFile(Activity activity, Message message) {
414 Fragment fragment = activity.getFragmentManager().findFragmentById(R.id.main_fragment);
415 if (fragment != null && fragment instanceof ConversationFragment) {
416 ((ConversationFragment) fragment).startDownloadable(message);
417 return;
418 }
419 fragment = activity.getFragmentManager().findFragmentById(R.id.secondary_fragment);
420 if (fragment != null && fragment instanceof ConversationFragment) {
421 ((ConversationFragment) fragment).startDownloadable(message);
422 }
423 }
424
425 public static Conversation getConversation(Activity activity) {
426 return getConversation(activity, R.id.secondary_fragment);
427 }
428
429 private static Conversation getConversation(Activity activity, @IdRes int res) {
430 final Fragment fragment = activity.getFragmentManager().findFragmentById(res);
431 if (fragment != null && fragment instanceof ConversationFragment) {
432 return ((ConversationFragment) fragment).getConversation();
433 } else {
434 return null;
435 }
436 }
437
438 public static Conversation getConversationReliable(Activity activity) {
439 final Conversation conversation = getConversation(activity, R.id.secondary_fragment);
440 if (conversation != null) {
441 return conversation;
442 }
443 return getConversation(activity, R.id.main_fragment);
444 }
445
446 private int getIndexOf(String uuid, List<Message> messages) {
447 if (uuid == null) {
448 return messages.size() - 1;
449 }
450 for (int i = 0; i < messages.size(); ++i) {
451 if (uuid.equals(messages.get(i).getUuid())) {
452 return i;
453 } else {
454 Message next = messages.get(i);
455 while (next != null && next.wasMergedIntoPrevious()) {
456 if (uuid.equals(next.getUuid())) {
457 return i;
458 }
459 next = next.next();
460 }
461
462 }
463 }
464 return -1;
465 }
466
467 private ScrollState getScrollPosition() {
468 final ListView listView = this.binding.messagesView;
469 if (listView.getCount() == 0 || listView.getLastVisiblePosition() == listView.getCount() - 1) {
470 return null;
471 } else {
472 final int pos = listView.getFirstVisiblePosition();
473 final View view = listView.getChildAt(0);
474 if (view == null) {
475 return null;
476 } else {
477 return new ScrollState(pos, view.getTop());
478 }
479 }
480 }
481
482 private void setScrollPosition(ScrollState scrollPosition) {
483 if (scrollPosition != null) {
484 this.binding.messagesView.setSelectionFromTop(scrollPosition.position, scrollPosition.offset);
485 }
486 }
487
488 private void attachLocationToConversation(Conversation conversation, Uri uri) {
489 if (conversation == null) {
490 return;
491 }
492 activity.xmppConnectionService.attachLocationToConversation(conversation, uri, new UiCallback<Message>() {
493
494 @Override
495 public void success(Message message) {
496 activity.xmppConnectionService.sendMessage(message);
497 }
498
499 @Override
500 public void error(int errorCode, Message object) {
501
502 }
503
504 @Override
505 public void userInputRequried(PendingIntent pi, Message object) {
506
507 }
508 });
509 }
510
511 private void attachFileToConversation(Conversation conversation, Uri uri) {
512 if (conversation == null) {
513 return;
514 }
515 final Toast prepareFileToast = Toast.makeText(getActivity(), getText(R.string.preparing_file), Toast.LENGTH_LONG);
516 prepareFileToast.show();
517 activity.delegateUriPermissionsToService(uri);
518 activity.xmppConnectionService.attachFileToConversation(conversation, uri, new UiInformableCallback<Message>() {
519 @Override
520 public void inform(final String text) {
521 hidePrepareFileToast(prepareFileToast);
522 runOnUiThread(() -> activity.replaceToast(text));
523 }
524
525 @Override
526 public void success(Message message) {
527 runOnUiThread(() -> activity.hideToast());
528 hidePrepareFileToast(prepareFileToast);
529 activity.xmppConnectionService.sendMessage(message);
530 }
531
532 @Override
533 public void error(final int errorCode, Message message) {
534 hidePrepareFileToast(prepareFileToast);
535 runOnUiThread(() -> activity.replaceToast(getString(errorCode)));
536
537 }
538
539 @Override
540 public void userInputRequried(PendingIntent pi, Message message) {
541 hidePrepareFileToast(prepareFileToast);
542 }
543 });
544 }
545
546 public void attachImageToConversation(Uri uri) {
547 this.attachImageToConversation(conversation, uri);
548 }
549
550 private void attachImageToConversation(Conversation conversation, Uri uri) {
551 if (conversation == null) {
552 return;
553 }
554 final Toast prepareFileToast = Toast.makeText(getActivity(), getText(R.string.preparing_image), Toast.LENGTH_LONG);
555 prepareFileToast.show();
556 activity.delegateUriPermissionsToService(uri);
557 activity.xmppConnectionService.attachImageToConversation(conversation, uri,
558 new UiCallback<Message>() {
559
560 @Override
561 public void userInputRequried(PendingIntent pi, Message object) {
562 hidePrepareFileToast(prepareFileToast);
563 }
564
565 @Override
566 public void success(Message message) {
567 hidePrepareFileToast(prepareFileToast);
568 activity.xmppConnectionService.sendMessage(message);
569 }
570
571 @Override
572 public void error(final int error, Message message) {
573 hidePrepareFileToast(prepareFileToast);
574 activity.runOnUiThread(() -> activity.replaceToast(getString(error)));
575 }
576 });
577 }
578
579 private void hidePrepareFileToast(final Toast prepareFileToast) {
580 if (prepareFileToast != null) {
581 activity.runOnUiThread(prepareFileToast::cancel);
582 }
583 }
584
585 private void sendMessage() {
586 final String body = this.binding.textinput.getText().toString();
587 final Conversation conversation = this.conversation;
588 if (body.length() == 0 || conversation == null) {
589 return;
590 }
591 final Message message;
592 if (conversation.getCorrectingMessage() == null) {
593 message = new Message(conversation, body, conversation.getNextEncryption());
594 if (conversation.getMode() == Conversation.MODE_MULTI) {
595 final Jid nextCounterpart = conversation.getNextCounterpart();
596 if (nextCounterpart != null) {
597 message.setCounterpart(nextCounterpart);
598 message.setTrueCounterpart(conversation.getMucOptions().getTrueCounterpart(nextCounterpart));
599 message.setType(Message.TYPE_PRIVATE);
600 }
601 }
602 } else {
603 message = conversation.getCorrectingMessage();
604 message.setBody(body);
605 message.setEdited(message.getUuid());
606 message.setUuid(UUID.randomUUID().toString());
607 }
608 switch (message.getConversation().getNextEncryption()) {
609 case Message.ENCRYPTION_PGP:
610 sendPgpMessage(message);
611 break;
612 case Message.ENCRYPTION_AXOLOTL:
613 if (!trustKeysIfNeeded(REQUEST_TRUST_KEYS_TEXT)) {
614 sendAxolotlMessage(message);
615 }
616 break;
617 default:
618 sendPlainTextMessage(message);
619 }
620 }
621
622 protected boolean trustKeysIfNeeded(int requestCode) {
623 return trustKeysIfNeeded(requestCode, ATTACHMENT_CHOICE_INVALID);
624 }
625
626 protected boolean trustKeysIfNeeded(int requestCode, int attachmentChoice) {
627 AxolotlService axolotlService = conversation.getAccount().getAxolotlService();
628 final List<Jid> targets = axolotlService.getCryptoTargets(conversation);
629 boolean hasUnaccepted = !conversation.getAcceptedCryptoTargets().containsAll(targets);
630 boolean hasUndecidedOwn = !axolotlService.getKeysWithTrust(FingerprintStatus.createActiveUndecided()).isEmpty();
631 boolean hasUndecidedContacts = !axolotlService.getKeysWithTrust(FingerprintStatus.createActiveUndecided(), targets).isEmpty();
632 boolean hasPendingKeys = !axolotlService.findDevicesWithoutSession(conversation).isEmpty();
633 boolean hasNoTrustedKeys = axolotlService.anyTargetHasNoTrustedKeys(targets);
634 if (hasUndecidedOwn || hasUndecidedContacts || hasPendingKeys || hasNoTrustedKeys || hasUnaccepted) {
635 axolotlService.createSessionsIfNeeded(conversation);
636 Intent intent = new Intent(getActivity(), TrustKeysActivity.class);
637 String[] contacts = new String[targets.size()];
638 for (int i = 0; i < contacts.length; ++i) {
639 contacts[i] = targets.get(i).toString();
640 }
641 intent.putExtra("contacts", contacts);
642 intent.putExtra(EXTRA_ACCOUNT, conversation.getAccount().getJid().toBareJid().toString());
643 intent.putExtra("choice", attachmentChoice);
644 intent.putExtra("conversation", conversation.getUuid());
645 startActivityForResult(intent, requestCode);
646 return true;
647 } else {
648 return false;
649 }
650 }
651
652 public void updateChatMsgHint() {
653 final boolean multi = conversation.getMode() == Conversation.MODE_MULTI;
654 if (conversation.getCorrectingMessage() != null) {
655 this.binding.textinput.setHint(R.string.send_corrected_message);
656 } else if (multi && conversation.getNextCounterpart() != null) {
657 this.binding.textinput.setHint(getString(
658 R.string.send_private_message_to,
659 conversation.getNextCounterpart().getResourcepart()));
660 } else if (multi && !conversation.getMucOptions().participating()) {
661 this.binding.textinput.setHint(R.string.you_are_not_participating);
662 } else {
663 this.binding.textinput.setHint(UIHelper.getMessageHint(getActivity(), conversation));
664 getActivity().invalidateOptionsMenu();
665 }
666 }
667
668 public void setupIme() {
669 this.binding.textinput.refreshIme();
670 }
671
672 private void handleActivityResult(ActivityResult activityResult) {
673 if (activityResult.resultCode == Activity.RESULT_OK) {
674 handlePositiveActivityResult(activityResult.requestCode, activityResult.data);
675 } else {
676 handleNegativeActivityResult(activityResult.requestCode);
677 }
678 }
679
680 private void handlePositiveActivityResult(int requestCode, final Intent data) {
681 switch (requestCode) {
682 case REQUEST_TRUST_KEYS_TEXT:
683 final String body = this.binding.textinput.getText().toString();
684 Message message = new Message(conversation, body, conversation.getNextEncryption());
685 sendAxolotlMessage(message);
686 break;
687 case REQUEST_TRUST_KEYS_MENU:
688 int choice = data.getIntExtra("choice", ATTACHMENT_CHOICE_INVALID);
689 selectPresenceToAttachFile(choice);
690 break;
691 case REQUEST_CHOOSE_PGP_ID:
692 long id = data.getLongExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, 0);
693 if (id != 0) {
694 conversation.getAccount().setPgpSignId(id);
695 activity.announcePgp(conversation.getAccount(), null, null, activity.onOpenPGPKeyPublished);
696 } else {
697 activity.choosePgpSignId(conversation.getAccount());
698 }
699 break;
700 case REQUEST_ANNOUNCE_PGP:
701 activity.announcePgp(conversation.getAccount(), conversation, data, activity.onOpenPGPKeyPublished);
702 break;
703 case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
704 List<Uri> imageUris = AttachmentTool.extractUriFromIntent(data);
705 for (Iterator<Uri> i = imageUris.iterator(); i.hasNext(); i.remove()) {
706 Log.d(Config.LOGTAG, "ConversationsActivity.onActivityResult() - attaching image to conversations. CHOOSE_IMAGE");
707 attachImageToConversation(conversation, i.next());
708 }
709 break;
710 case ATTACHMENT_CHOICE_TAKE_PHOTO:
711 Uri takePhotoUri = pendingTakePhotoUri.pop();
712 if (takePhotoUri != null) {
713 attachImageToConversation(conversation, takePhotoUri);
714 } else {
715 Log.d(Config.LOGTAG, "lost take photo uri. unable to to attach");
716 }
717 break;
718 case ATTACHMENT_CHOICE_CHOOSE_FILE:
719 case ATTACHMENT_CHOICE_RECORD_VIDEO:
720 case ATTACHMENT_CHOICE_RECORD_VOICE:
721 final List<Uri> fileUris = AttachmentTool.extractUriFromIntent(data);
722 final PresenceSelector.OnPresenceSelected callback = () -> {
723 for (Iterator<Uri> i = fileUris.iterator(); i.hasNext(); i.remove()) {
724 Log.d(Config.LOGTAG, "ConversationsActivity.onActivityResult() - attaching file to conversations. CHOOSE_FILE/RECORD_VOICE/RECORD_VIDEO");
725 attachFileToConversation(conversation, i.next());
726 }
727 };
728 if (conversation == null || conversation.getMode() == Conversation.MODE_MULTI || FileBackend.allFilesUnderSize(getActivity(), fileUris, getMaxHttpUploadSize(conversation))) {
729 callback.onPresenceSelected();
730 } else {
731 activity.selectPresence(conversation, callback);
732 }
733 break;
734 case ATTACHMENT_CHOICE_LOCATION:
735 double latitude = data.getDoubleExtra("latitude", 0);
736 double longitude = data.getDoubleExtra("longitude", 0);
737 Uri geo = Uri.parse("geo:" + String.valueOf(latitude) + "," + String.valueOf(longitude));
738 attachLocationToConversation(conversation, geo);
739 break;
740 }
741 }
742
743 private void handleNegativeActivityResult(int requestCode) {
744 switch (requestCode) {
745 //nothing to do for now
746 }
747 }
748
749 @Override
750 public void onActivityResult(int requestCode, int resultCode, final Intent data) {
751 super.onActivityResult(requestCode, resultCode, data);
752 ActivityResult activityResult = ActivityResult.of(requestCode, resultCode, data);
753 if (activity != null && activity.xmppConnectionService != null) {
754 handleActivityResult(activityResult);
755 } else {
756 this.postponedActivityResult.push(activityResult);
757 }
758 }
759
760 public void unblockConversation(final Blockable conversation) {
761 activity.xmppConnectionService.sendUnblockRequest(conversation);
762 }
763
764 @Override
765 public void onAttach(Activity activity) {
766 super.onAttach(activity);
767 Log.d(Config.LOGTAG, "ConversationFragment.onAttach()");
768 if (activity instanceof ConversationActivity) {
769 this.activity = (ConversationActivity) activity;
770 } else {
771 throw new IllegalStateException("Trying to attach fragment to activity that is not the ConversationActivity");
772 }
773 }
774
775 @Override
776 public void onDetach() {
777 super.onDetach();
778 this.activity = null; //TODO maybe not a good idea since some callbacks really need it
779 }
780
781 @Override
782 public void onCreate(Bundle savedInstanceState) {
783 super.onCreate(savedInstanceState);
784 setHasOptionsMenu(true);
785 }
786
787 @Override
788 public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
789 menuInflater.inflate(R.menu.fragment_conversation, menu);
790 final MenuItem menuMucDetails = menu.findItem(R.id.action_muc_details);
791 final MenuItem menuContactDetails = menu.findItem(R.id.action_contact_details);
792 final MenuItem menuInviteContact = menu.findItem(R.id.action_invite);
793 final MenuItem menuMute = menu.findItem(R.id.action_mute);
794 final MenuItem menuUnmute = menu.findItem(R.id.action_unmute);
795
796
797 if (conversation != null) {
798 if (conversation.getMode() == Conversation.MODE_MULTI) {
799 menuContactDetails.setVisible(false);
800 menuInviteContact.setVisible(conversation.getMucOptions().canInvite());
801 } else {
802 menuContactDetails.setVisible(!this.conversation.withSelf());
803 menuMucDetails.setVisible(false);
804 final XmppConnectionService service = activity.xmppConnectionService;
805 menuInviteContact.setVisible(service != null && service.findConferenceServer(conversation.getAccount()) != null);
806 }
807 if (conversation.isMuted()) {
808 menuMute.setVisible(false);
809 } else {
810 menuUnmute.setVisible(false);
811 }
812 ConversationMenuConfigurator.configureAttachmentMenu(conversation, menu);
813 ConversationMenuConfigurator.configureEncryptionMenu(conversation, menu);
814 }
815 super.onCreateOptionsMenu(menu, menuInflater);
816 }
817
818 @Override
819 public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
820 this.binding = DataBindingUtil.inflate(inflater, R.layout.fragment_conversation, container, false);
821 binding.getRoot().setOnClickListener(null); //TODO why the fuck did we do this?
822
823 binding.textinput.addTextChangedListener(new StylingHelper.MessageEditorStyler(binding.textinput));
824
825 binding.textinput.setOnEditorActionListener(mEditorActionListener);
826 binding.textinput.setRichContentListener(new String[]{"image/*"}, mEditorContentListener);
827
828 binding.textSendButton.setOnClickListener(this.mSendButtonListener);
829
830 binding.messagesView.setOnScrollListener(mOnScrollListener);
831 binding.messagesView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
832 messageListAdapter = new MessageAdapter((XmppActivity) getActivity(), this.messageList);
833 messageListAdapter.setOnContactPictureClicked(message -> {
834 final boolean received = message.getStatus() <= Message.STATUS_RECEIVED;
835 if (received) {
836 if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
837 Jid user = message.getCounterpart();
838 if (user != null && !user.isBareJid()) {
839 if (!message.getConversation().getMucOptions().isUserInRoom(user)) {
840 Toast.makeText(getActivity(), activity.getString(R.string.user_has_left_conference, user.getResourcepart()), Toast.LENGTH_SHORT).show();
841 }
842 highlightInConference(user.getResourcepart());
843 }
844 return;
845 } else {
846 if (!message.getContact().isSelf()) {
847 String fingerprint;
848 if (message.getEncryption() == Message.ENCRYPTION_PGP
849 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
850 fingerprint = "pgp";
851 } else {
852 fingerprint = message.getFingerprint();
853 }
854 activity.switchToContactDetails(message.getContact(), fingerprint);
855 return;
856 }
857 }
858 }
859 Account account = message.getConversation().getAccount();
860 Intent intent;
861 if (activity.manuallyChangePresence() && !received) {
862 intent = new Intent(activity, SetPresenceActivity.class);
863 intent.putExtra(EXTRA_ACCOUNT, account.getJid().toBareJid().toString());
864 } else {
865 intent = new Intent(activity, EditAccountActivity.class);
866 intent.putExtra("jid", account.getJid().toBareJid().toString());
867 String fingerprint;
868 if (message.getEncryption() == Message.ENCRYPTION_PGP
869 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
870 fingerprint = "pgp";
871 } else {
872 fingerprint = message.getFingerprint();
873 }
874 intent.putExtra("fingerprint", fingerprint);
875 }
876 startActivity(intent);
877 });
878 messageListAdapter.setOnContactPictureLongClicked(message -> {
879 if (message.getStatus() <= Message.STATUS_RECEIVED) {
880 if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
881 final MucOptions mucOptions = conversation.getMucOptions();
882 if (!mucOptions.allowPm()) {
883 Toast.makeText(getActivity(), R.string.private_messages_are_disabled, Toast.LENGTH_SHORT).show();
884 return;
885 }
886 Jid user = message.getCounterpart();
887 if (user != null && !user.isBareJid()) {
888 if (mucOptions.isUserInRoom(user)) {
889 privateMessageWith(user);
890 } else {
891 Toast.makeText(getActivity(), activity.getString(R.string.user_has_left_conference, user.getResourcepart()), Toast.LENGTH_SHORT).show();
892 }
893 }
894 }
895 } else {
896 activity.showQrCode(conversation.getAccount().getShareableUri());
897 }
898 });
899 messageListAdapter.setOnQuoteListener(this::quoteText);
900 binding.messagesView.setAdapter(messageListAdapter);
901
902 registerForContextMenu(binding.messagesView);
903
904 return binding.getRoot();
905 }
906
907 private void quoteText(String text) {
908 if (binding.textinput.isEnabled()) {
909 text = text.replaceAll("(\n *){2,}", "\n").replaceAll("(^|\n)", "$1> ").replaceAll("\n$", "");
910 Editable editable = binding.textinput.getEditableText();
911 int position = binding.textinput.getSelectionEnd();
912 if (position == -1) position = editable.length();
913 if (position > 0 && editable.charAt(position - 1) != '\n') {
914 editable.insert(position++, "\n");
915 }
916 editable.insert(position, text);
917 position += text.length();
918 editable.insert(position++, "\n");
919 if (position < editable.length() && editable.charAt(position) != '\n') {
920 editable.insert(position, "\n");
921 }
922 binding.textinput.setSelection(position);
923 binding.textinput.requestFocus();
924 InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
925 if (inputMethodManager != null) {
926 inputMethodManager.showSoftInput(binding.textinput, InputMethodManager.SHOW_IMPLICIT);
927 }
928 }
929 }
930
931 private void quoteMessage(Message message) {
932 quoteText(MessageUtils.prepareQuote(message));
933 }
934
935 @Override
936 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
937 synchronized (this.messageList) {
938 super.onCreateContextMenu(menu, v, menuInfo);
939 AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
940 this.selectedMessage = this.messageList.get(acmi.position);
941 populateContextMenu(menu);
942 }
943 }
944
945 private void populateContextMenu(ContextMenu menu) {
946 final Message m = this.selectedMessage;
947 final Transferable t = m.getTransferable();
948 Message relevantForCorrection = m;
949 while (relevantForCorrection.mergeable(relevantForCorrection.next())) {
950 relevantForCorrection = relevantForCorrection.next();
951 }
952 if (m.getType() != Message.TYPE_STATUS) {
953 final boolean treatAsFile = m.getType() != Message.TYPE_TEXT
954 && m.getType() != Message.TYPE_PRIVATE
955 && t == null;
956 final boolean encrypted = m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED
957 || m.getEncryption() == Message.ENCRYPTION_PGP;
958 activity.getMenuInflater().inflate(R.menu.message_context, menu);
959 menu.setHeaderTitle(R.string.message_options);
960 MenuItem copyMessage = menu.findItem(R.id.copy_message);
961 MenuItem quoteMessage = menu.findItem(R.id.quote_message);
962 MenuItem retryDecryption = menu.findItem(R.id.retry_decryption);
963 MenuItem correctMessage = menu.findItem(R.id.correct_message);
964 MenuItem shareWith = menu.findItem(R.id.share_with);
965 MenuItem sendAgain = menu.findItem(R.id.send_again);
966 MenuItem copyUrl = menu.findItem(R.id.copy_url);
967 MenuItem downloadFile = menu.findItem(R.id.download_file);
968 MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
969 MenuItem deleteFile = menu.findItem(R.id.delete_file);
970 MenuItem showErrorMessage = menu.findItem(R.id.show_error_message);
971 if (!treatAsFile && !encrypted && !m.isGeoUri() && !m.treatAsDownloadable()) {
972 copyMessage.setVisible(true);
973 quoteMessage.setVisible(MessageUtils.prepareQuote(m).length() > 0);
974 }
975 if (m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED) {
976 retryDecryption.setVisible(true);
977 }
978 if (relevantForCorrection.getType() == Message.TYPE_TEXT
979 && relevantForCorrection.isLastCorrectableMessage()
980 && (m.getConversation().getMucOptions().nonanonymous() || m.getConversation().getMode() == Conversation.MODE_SINGLE)) {
981 correctMessage.setVisible(true);
982 }
983 if (treatAsFile || (m.getType() == Message.TYPE_TEXT && !m.treatAsDownloadable())) {
984 shareWith.setVisible(true);
985 }
986 if (m.getStatus() == Message.STATUS_SEND_FAILED) {
987 sendAgain.setVisible(true);
988 }
989 if (m.hasFileOnRemoteHost()
990 || m.isGeoUri()
991 || m.treatAsDownloadable()
992 || (t != null && t instanceof HttpDownloadConnection)) {
993 copyUrl.setVisible(true);
994 }
995 if ((m.isFileOrImage() && t instanceof TransferablePlaceholder && m.hasFileOnRemoteHost())) {
996 downloadFile.setVisible(true);
997 downloadFile.setTitle(activity.getString(R.string.download_x_file, UIHelper.getFileDescriptionString(activity, m)));
998 }
999 boolean waitingOfferedSending = m.getStatus() == Message.STATUS_WAITING
1000 || m.getStatus() == Message.STATUS_UNSEND
1001 || m.getStatus() == Message.STATUS_OFFERED;
1002 if ((t != null && !(t instanceof TransferablePlaceholder)) || waitingOfferedSending && m.needsUploading()) {
1003 cancelTransmission.setVisible(true);
1004 }
1005 if (treatAsFile) {
1006 String path = m.getRelativeFilePath();
1007 if (path == null || !path.startsWith("/")) {
1008 deleteFile.setVisible(true);
1009 deleteFile.setTitle(activity.getString(R.string.delete_x_file, UIHelper.getFileDescriptionString(activity, m)));
1010 }
1011 }
1012 if (m.getStatus() == Message.STATUS_SEND_FAILED && m.getErrorMessage() != null) {
1013 showErrorMessage.setVisible(true);
1014 }
1015 }
1016 }
1017
1018 @Override
1019 public boolean onContextItemSelected(MenuItem item) {
1020 switch (item.getItemId()) {
1021 case R.id.share_with:
1022 shareWith(selectedMessage);
1023 return true;
1024 case R.id.correct_message:
1025 correctMessage(selectedMessage);
1026 return true;
1027 case R.id.copy_message:
1028 copyMessage(selectedMessage);
1029 return true;
1030 case R.id.quote_message:
1031 quoteMessage(selectedMessage);
1032 return true;
1033 case R.id.send_again:
1034 resendMessage(selectedMessage);
1035 return true;
1036 case R.id.copy_url:
1037 copyUrl(selectedMessage);
1038 return true;
1039 case R.id.download_file:
1040 startDownloadable(selectedMessage);
1041 return true;
1042 case R.id.cancel_transmission:
1043 cancelTransmission(selectedMessage);
1044 return true;
1045 case R.id.retry_decryption:
1046 retryDecryption(selectedMessage);
1047 return true;
1048 case R.id.delete_file:
1049 deleteFile(selectedMessage);
1050 return true;
1051 case R.id.show_error_message:
1052 showErrorMessage(selectedMessage);
1053 return true;
1054 default:
1055 return super.onContextItemSelected(item);
1056 }
1057 }
1058
1059 @Override
1060 public boolean onOptionsItemSelected(final MenuItem item) {
1061 if (conversation == null) {
1062 return super.onOptionsItemSelected(item);
1063 }
1064 switch (item.getItemId()) {
1065 case R.id.encryption_choice_axolotl:
1066 case R.id.encryption_choice_pgp:
1067 case R.id.encryption_choice_none:
1068 handleEncryptionSelection(item);
1069 break;
1070 case R.id.attach_choose_picture:
1071 case R.id.attach_take_picture:
1072 case R.id.attach_record_video:
1073 case R.id.attach_choose_file:
1074 case R.id.attach_record_voice:
1075 case R.id.attach_location:
1076 handleAttachmentSelection(item);
1077 break;
1078 case R.id.action_archive:
1079 activity.xmppConnectionService.archiveConversation(conversation);
1080 activity.onConversationArchived(conversation);
1081 break;
1082 case R.id.action_contact_details:
1083 activity.switchToContactDetails(conversation.getContact());
1084 break;
1085 case R.id.action_muc_details:
1086 Intent intent = new Intent(getActivity(), ConferenceDetailsActivity.class);
1087 intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
1088 intent.putExtra("uuid", conversation.getUuid());
1089 startActivity(intent);
1090 break;
1091 case R.id.action_invite:
1092 activity.inviteToConversation(conversation);
1093 break;
1094 case R.id.action_clear_history:
1095 clearHistoryDialog(conversation);
1096 break;
1097 case R.id.action_mute:
1098 muteConversationDialog(conversation);
1099 break;
1100 case R.id.action_unmute:
1101 unmuteConversation(conversation);
1102 break;
1103 case R.id.action_block:
1104 case R.id.action_unblock:
1105 final Activity activity = getActivity();
1106 if (activity instanceof XmppActivity) {
1107 BlockContactDialog.show((XmppActivity) activity, conversation);
1108 }
1109 break;
1110 default:
1111 break;
1112 }
1113 return super.onOptionsItemSelected(item);
1114 }
1115
1116 private void handleAttachmentSelection(MenuItem item) {
1117 switch (item.getItemId()) {
1118 case R.id.attach_choose_picture:
1119 attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
1120 break;
1121 case R.id.attach_take_picture:
1122 attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
1123 break;
1124 case R.id.attach_record_video:
1125 attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO);
1126 break;
1127 case R.id.attach_choose_file:
1128 attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
1129 break;
1130 case R.id.attach_record_voice:
1131 attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
1132 break;
1133 case R.id.attach_location:
1134 attachFile(ATTACHMENT_CHOICE_LOCATION);
1135 break;
1136 }
1137 }
1138
1139 private void handleEncryptionSelection(MenuItem item) {
1140 if (conversation == null) {
1141 return;
1142 }
1143 switch (item.getItemId()) {
1144 case R.id.encryption_choice_none:
1145 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1146 item.setChecked(true);
1147 break;
1148 case R.id.encryption_choice_pgp:
1149 if (activity.hasPgp()) {
1150 if (conversation.getAccount().getPgpSignature() != null) {
1151 conversation.setNextEncryption(Message.ENCRYPTION_PGP);
1152 item.setChecked(true);
1153 } else {
1154 activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
1155 }
1156 } else {
1157 activity.showInstallPgpDialog();
1158 }
1159 break;
1160 case R.id.encryption_choice_axolotl:
1161 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(conversation.getAccount())
1162 + "Enabled axolotl for Contact " + conversation.getContact().getJid());
1163 conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
1164 item.setChecked(true);
1165 break;
1166 default:
1167 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1168 break;
1169 }
1170 activity.xmppConnectionService.updateConversation(conversation);
1171 updateChatMsgHint();
1172 getActivity().invalidateOptionsMenu();
1173 activity.refreshUi();
1174 }
1175
1176 public void attachFile(final int attachmentChoice) {
1177 if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
1178 if (!Config.ONLY_INTERNAL_STORAGE && !hasStoragePermission(attachmentChoice)) {
1179 return;
1180 }
1181 }
1182 try {
1183 activity.getPreferences().edit()
1184 .putString(RECENTLY_USED_QUICK_ACTION, SendButtonAction.of(attachmentChoice).toString())
1185 .apply();
1186 } catch (IllegalArgumentException e) {
1187 //just do not save
1188 }
1189 final int encryption = conversation.getNextEncryption();
1190 final int mode = conversation.getMode();
1191 if (encryption == Message.ENCRYPTION_PGP) {
1192 if (activity.hasPgp()) {
1193 if (mode == Conversation.MODE_SINGLE && conversation.getContact().getPgpKeyId() != 0) {
1194 activity.xmppConnectionService.getPgpEngine().hasKey(
1195 conversation.getContact(),
1196 new UiCallback<Contact>() {
1197
1198 @Override
1199 public void userInputRequried(PendingIntent pi, Contact contact) {
1200 startPendingIntent(pi, attachmentChoice);
1201 }
1202
1203 @Override
1204 public void success(Contact contact) {
1205 selectPresenceToAttachFile(attachmentChoice);
1206 }
1207
1208 @Override
1209 public void error(int error, Contact contact) {
1210 activity.replaceToast(getString(error));
1211 }
1212 });
1213 } else if (mode == Conversation.MODE_MULTI && conversation.getMucOptions().pgpKeysInUse()) {
1214 if (!conversation.getMucOptions().everybodyHasKeys()) {
1215 Toast warning = Toast.makeText(getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG);
1216 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
1217 warning.show();
1218 }
1219 selectPresenceToAttachFile(attachmentChoice);
1220 } else {
1221 final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
1222 .findFragmentByTag("conversation");
1223 if (fragment != null) {
1224 fragment.showNoPGPKeyDialog(false, (dialog, which) -> {
1225 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
1226 activity.xmppConnectionService.updateConversation(conversation);
1227 selectPresenceToAttachFile(attachmentChoice);
1228 });
1229 }
1230 }
1231 } else {
1232 activity.showInstallPgpDialog();
1233 }
1234 } else {
1235 if (encryption != Message.ENCRYPTION_AXOLOTL || !trustKeysIfNeeded(REQUEST_TRUST_KEYS_MENU, attachmentChoice)) {
1236 selectPresenceToAttachFile(attachmentChoice);
1237 }
1238 }
1239 }
1240
1241 @Override
1242 public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
1243 if (grantResults.length > 0)
1244 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
1245 if (requestCode == REQUEST_START_DOWNLOAD) {
1246 if (this.mPendingDownloadableMessage != null) {
1247 startDownloadable(this.mPendingDownloadableMessage);
1248 }
1249 } else if (requestCode == REQUEST_ADD_EDITOR_CONTENT) {
1250 if (this.mPendingEditorContent != null) {
1251 attachImageToConversation(this.mPendingEditorContent);
1252 }
1253 } else {
1254 attachFile(requestCode);
1255 }
1256 } else {
1257 Toast.makeText(getActivity(), R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
1258 }
1259 }
1260
1261 public void startDownloadable(Message message) {
1262 if (!Config.ONLY_INTERNAL_STORAGE && !hasStoragePermission(REQUEST_START_DOWNLOAD)) {
1263 this.mPendingDownloadableMessage = message;
1264 return;
1265 }
1266 Transferable transferable = message.getTransferable();
1267 if (transferable != null) {
1268 if (!transferable.start()) {
1269 Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT).show();
1270 }
1271 } else if (message.treatAsDownloadable()) {
1272 activity.xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message, true);
1273 }
1274 }
1275
1276 @SuppressLint("InflateParams")
1277 protected void clearHistoryDialog(final Conversation conversation) {
1278 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1279 builder.setTitle(getString(R.string.clear_conversation_history));
1280 final View dialogView = getActivity().getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
1281 final CheckBox endConversationCheckBox = dialogView.findViewById(R.id.end_conversation_checkbox);
1282 builder.setView(dialogView);
1283 builder.setNegativeButton(getString(R.string.cancel), null);
1284 builder.setPositiveButton(getString(R.string.delete_messages), (dialog, which) -> {
1285 this.activity.xmppConnectionService.clearConversationHistory(conversation);
1286 if (endConversationCheckBox.isChecked()) {
1287 this.activity.xmppConnectionService.archiveConversation(conversation);
1288 this.activity.onConversationArchived(conversation);
1289 } else {
1290 activity.onConversationsListItemUpdated();
1291 refresh();
1292 }
1293 });
1294 builder.create().show();
1295 }
1296
1297 protected void muteConversationDialog(final Conversation conversation) {
1298 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1299 builder.setTitle(R.string.disable_notifications);
1300 final int[] durations = getResources().getIntArray(R.array.mute_options_durations);
1301 builder.setItems(R.array.mute_options_descriptions, (dialog, which) -> {
1302 final long till;
1303 if (durations[which] == -1) {
1304 till = Long.MAX_VALUE;
1305 } else {
1306 till = System.currentTimeMillis() + (durations[which] * 1000);
1307 }
1308 conversation.setMutedTill(till);
1309 activity.xmppConnectionService.updateConversation(conversation);
1310 activity.onConversationsListItemUpdated();
1311 refresh();
1312 getActivity().invalidateOptionsMenu();
1313 });
1314 builder.create().show();
1315 }
1316
1317 private boolean hasStoragePermission(int requestCode) {
1318 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1319 if (activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
1320 requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
1321 return false;
1322 } else {
1323 return true;
1324 }
1325 } else {
1326 return true;
1327 }
1328 }
1329
1330 public void unmuteConversation(final Conversation conversation) {
1331 conversation.setMutedTill(0);
1332 this.activity.xmppConnectionService.updateConversation(conversation);
1333 this.activity.onConversationsListItemUpdated();
1334 refresh();
1335 getActivity().invalidateOptionsMenu();
1336 }
1337
1338 protected void selectPresenceToAttachFile(final int attachmentChoice) {
1339 final Account account = conversation.getAccount();
1340 final PresenceSelector.OnPresenceSelected callback = () -> {
1341 Intent intent = new Intent();
1342 boolean chooser = false;
1343 String fallbackPackageId = null;
1344 switch (attachmentChoice) {
1345 case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
1346 intent.setAction(Intent.ACTION_GET_CONTENT);
1347 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1348 intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
1349 }
1350 intent.setType("image/*");
1351 chooser = true;
1352 break;
1353 case ATTACHMENT_CHOICE_RECORD_VIDEO:
1354 intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
1355 break;
1356 case ATTACHMENT_CHOICE_TAKE_PHOTO:
1357 final Uri uri = activity.xmppConnectionService.getFileBackend().getTakePhotoUri();
1358 pendingTakePhotoUri.push(uri);
1359 intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
1360 intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
1361 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1362 intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
1363 break;
1364 case ATTACHMENT_CHOICE_CHOOSE_FILE:
1365 chooser = true;
1366 intent.setType("*/*");
1367 intent.addCategory(Intent.CATEGORY_OPENABLE);
1368 intent.setAction(Intent.ACTION_GET_CONTENT);
1369 break;
1370 case ATTACHMENT_CHOICE_RECORD_VOICE:
1371 intent.setAction(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
1372 fallbackPackageId = "eu.siacs.conversations.voicerecorder";
1373 break;
1374 case ATTACHMENT_CHOICE_LOCATION:
1375 intent.setAction("eu.siacs.conversations.location.request");
1376 fallbackPackageId = "eu.siacs.conversations.sharelocation";
1377 break;
1378 }
1379 if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
1380 if (chooser) {
1381 startActivityForResult(
1382 Intent.createChooser(intent, getString(R.string.perform_action_with)),
1383 attachmentChoice);
1384 } else {
1385 startActivityForResult(intent, attachmentChoice);
1386 }
1387 } else if (fallbackPackageId != null) {
1388 startActivity(getInstallApkIntent(fallbackPackageId));
1389 }
1390 };
1391 if (account.httpUploadAvailable() || attachmentChoice == ATTACHMENT_CHOICE_LOCATION) {
1392 conversation.setNextCounterpart(null);
1393 callback.onPresenceSelected();
1394 } else {
1395 activity.selectPresence(conversation, callback);
1396 }
1397 }
1398
1399 private Intent getInstallApkIntent(final String packageId) {
1400 Intent intent = new Intent(Intent.ACTION_VIEW);
1401 intent.setData(Uri.parse("market://details?id=" + packageId));
1402 if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
1403 return intent;
1404 } else {
1405 intent.setData(Uri.parse("http://play.google.com/store/apps/details?id=" + packageId));
1406 return intent;
1407 }
1408 }
1409
1410 @Override
1411 public void onResume() {
1412 new Handler().post(() -> {
1413 final Activity activity = getActivity();
1414 if (activity == null) {
1415 return;
1416 }
1417 final PackageManager packageManager = activity.getPackageManager();
1418 ConversationMenuConfigurator.updateAttachmentAvailability(packageManager);
1419 getActivity().invalidateOptionsMenu();
1420 });
1421 super.onResume();
1422 if (activity != null && this.conversation != null) {
1423 activity.onConversationRead(this.conversation);
1424 }
1425 }
1426
1427 private void showErrorMessage(final Message message) {
1428 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1429 builder.setTitle(R.string.error_message);
1430 builder.setMessage(message.getErrorMessage());
1431 builder.setPositiveButton(R.string.confirm, null);
1432 builder.create().show();
1433 }
1434
1435 private void shareWith(Message message) {
1436 Intent shareIntent = new Intent();
1437 shareIntent.setAction(Intent.ACTION_SEND);
1438 if (message.isGeoUri()) {
1439 shareIntent.putExtra(Intent.EXTRA_TEXT, message.getBody());
1440 shareIntent.setType("text/plain");
1441 } else if (!message.isFileOrImage()) {
1442 shareIntent.putExtra(Intent.EXTRA_TEXT, message.getMergedBody().toString());
1443 shareIntent.setType("text/plain");
1444 } else {
1445 final DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
1446 try {
1447 shareIntent.putExtra(Intent.EXTRA_STREAM, FileBackend.getUriForFile(getActivity(), file));
1448 } catch (SecurityException e) {
1449 Toast.makeText(getActivity(), activity.getString(R.string.no_permission_to_access_x, file.getAbsolutePath()), Toast.LENGTH_SHORT).show();
1450 return;
1451 }
1452 shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1453 String mime = message.getMimeType();
1454 if (mime == null) {
1455 mime = "*/*";
1456 }
1457 shareIntent.setType(mime);
1458 }
1459 try {
1460 startActivity(Intent.createChooser(shareIntent, getText(R.string.share_with)));
1461 } catch (ActivityNotFoundException e) {
1462 //This should happen only on faulty androids because normally chooser is always available
1463 Toast.makeText(getActivity(), R.string.no_application_found_to_open_file, Toast.LENGTH_SHORT).show();
1464 }
1465 }
1466
1467 private void copyMessage(Message message) {
1468 if (activity.copyTextToClipboard(message.getMergedBody().toString(), R.string.message)) {
1469 Toast.makeText(getActivity(), R.string.message_copied_to_clipboard, Toast.LENGTH_SHORT).show();
1470 }
1471 }
1472
1473 private void deleteFile(Message message) {
1474 if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) {
1475 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1476 activity.onConversationsListItemUpdated();
1477 refresh();
1478 }
1479 }
1480
1481 private void resendMessage(final Message message) {
1482 if (message.isFileOrImage()) {
1483 DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
1484 if (file.exists()) {
1485 final Conversation conversation = message.getConversation();
1486 final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection();
1487 if (!message.hasFileOnRemoteHost()
1488 && xmppConnection != null
1489 && !xmppConnection.getFeatures().httpUpload(message.getFileParams().size)) {
1490 activity.selectPresence(conversation, () -> {
1491 message.setCounterpart(conversation.getNextCounterpart());
1492 activity.xmppConnectionService.resendFailedMessages(message);
1493 });
1494 return;
1495 }
1496 } else {
1497 Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
1498 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1499 activity.onConversationsListItemUpdated();
1500 refresh();
1501 return;
1502 }
1503 }
1504 activity.xmppConnectionService.resendFailedMessages(message);
1505 }
1506
1507 private void copyUrl(Message message) {
1508 final String url;
1509 final int resId;
1510 if (message.isGeoUri()) {
1511 resId = R.string.location;
1512 url = message.getBody();
1513 } else if (message.hasFileOnRemoteHost()) {
1514 resId = R.string.file_url;
1515 url = message.getFileParams().url.toString();
1516 } else {
1517 url = message.getBody().trim();
1518 resId = R.string.file_url;
1519 }
1520 if (activity.copyTextToClipboard(url, resId)) {
1521 Toast.makeText(getActivity(), R.string.url_copied_to_clipboard, Toast.LENGTH_SHORT).show();
1522 }
1523 }
1524
1525 private void cancelTransmission(Message message) {
1526 Transferable transferable = message.getTransferable();
1527 if (transferable != null) {
1528 transferable.cancel();
1529 } else if (message.getStatus() != Message.STATUS_RECEIVED) {
1530 activity.xmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
1531 }
1532 }
1533
1534 private void retryDecryption(Message message) {
1535 message.setEncryption(Message.ENCRYPTION_PGP);
1536 activity.onConversationsListItemUpdated();
1537 refresh();
1538 conversation.getAccount().getPgpDecryptionService().decrypt(message, false);
1539 }
1540
1541 private void privateMessageWith(final Jid counterpart) {
1542 if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1543 activity.xmppConnectionService.sendChatState(conversation);
1544 }
1545 this.binding.textinput.setText("");
1546 this.conversation.setNextCounterpart(counterpart);
1547 updateChatMsgHint();
1548 updateSendButton();
1549 updateEditablity();
1550 }
1551
1552 private void correctMessage(Message message) {
1553 while (message.mergeable(message.next())) {
1554 message = message.next();
1555 }
1556 this.conversation.setCorrectingMessage(message);
1557 final Editable editable = binding.textinput.getText();
1558 this.conversation.setDraftMessage(editable.toString());
1559 this.binding.textinput.setText("");
1560 this.binding.textinput.append(message.getBody());
1561
1562 }
1563
1564 private void highlightInConference(String nick) {
1565 final Editable editable = this.binding.textinput.getText();
1566 String oldString = editable.toString().trim();
1567 final int pos = this.binding.textinput.getSelectionStart();
1568 if (oldString.isEmpty() || pos == 0) {
1569 editable.insert(0, nick + ": ");
1570 } else {
1571 final char before = editable.charAt(pos - 1);
1572 final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
1573 if (before == '\n') {
1574 editable.insert(pos, nick + ": ");
1575 } else {
1576 if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
1577 if (NickValidityChecker.check(conversation, Arrays.asList(editable.subSequence(0, pos - 2).toString().split(", ")))) {
1578 editable.insert(pos - 2, ", " + nick);
1579 return;
1580 }
1581 }
1582 editable.insert(pos, (Character.isWhitespace(before) ? "" : " ") + nick + (Character.isWhitespace(after) ? "" : " "));
1583 if (Character.isWhitespace(after)) {
1584 this.binding.textinput.setSelection(this.binding.textinput.getSelectionStart() + 1);
1585 }
1586 }
1587 }
1588 }
1589
1590 @Override
1591 public void onSaveInstanceState(Bundle outState) {
1592 super.onSaveInstanceState(outState);
1593 if (conversation != null) {
1594 outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
1595 final Uri uri = pendingTakePhotoUri.pop();
1596 if (uri != null) {
1597 outState.putString(STATE_PHOTO_URI, uri.toString());
1598 }
1599 final ScrollState scrollState = getScrollPosition();
1600 if (scrollState != null) {
1601 outState.putParcelable(STATE_SCROLL_POSITION, scrollState);
1602 }
1603 }
1604 }
1605
1606 @Override
1607 public void onActivityCreated(Bundle savedInstanceState) {
1608 super.onActivityCreated(savedInstanceState);
1609 if (savedInstanceState == null) {
1610 return;
1611 }
1612 String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID);
1613 if (uuid != null) {
1614 this.pendingConversationsUuid.push(uuid);
1615 String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI);
1616 if (takePhotoUri != null) {
1617 pendingTakePhotoUri.push(Uri.parse(takePhotoUri));
1618 }
1619 pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
1620 }
1621 }
1622
1623 @Override
1624 public void onStart() {
1625 super.onStart();
1626 if (this.reInitRequiredOnStart) {
1627 final Bundle extras = pendingExtras.pop();
1628 reInit(conversation, extras != null);
1629 if (extras != null) {
1630 processExtras(extras);
1631 }
1632 } else {
1633 Log.d(Config.LOGTAG, "skipped reinit on start");
1634 }
1635 }
1636
1637 @Override
1638 public void onStop() {
1639 super.onStop();
1640 final Activity activity = getActivity();
1641 if (activity == null || !activity.isChangingConfigurations()) {
1642 messageListAdapter.stopAudioPlayer();
1643 }
1644 if (this.conversation != null) {
1645 final String msg = this.binding.textinput.getText().toString();
1646 if (this.conversation.setNextMessage(msg)) {
1647 this.activity.xmppConnectionService.updateConversation(this.conversation);
1648 }
1649 updateChatState(this.conversation, msg);
1650 this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null);
1651 }
1652 this.reInitRequiredOnStart = true;
1653 }
1654
1655 private void updateChatState(final Conversation conversation, final String msg) {
1656 ChatState state = msg.length() == 0 ? Config.DEFAULT_CHATSTATE : ChatState.PAUSED;
1657 Account.State status = conversation.getAccount().getStatus();
1658 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
1659 activity.xmppConnectionService.sendChatState(conversation);
1660 }
1661 }
1662
1663 private void saveMessageDraftStopAudioPlayer() {
1664 final Conversation previousConversation = this.conversation;
1665 if (this.activity == null || this.binding == null || previousConversation == null) {
1666 return;
1667 }
1668 Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()");
1669 final String msg = this.binding.textinput.getText().toString();
1670 if (previousConversation.setNextMessage(msg)) {
1671 activity.xmppConnectionService.updateConversation(previousConversation);
1672 }
1673 updateChatState(this.conversation, msg);
1674 messageListAdapter.stopAudioPlayer();
1675 }
1676
1677 public void reInit(Conversation conversation, Bundle extras) {
1678 this.saveMessageDraftStopAudioPlayer();
1679 if (this.reInit(conversation, extras != null)) {
1680 if (extras != null) {
1681 processExtras(extras);
1682 }
1683 this.reInitRequiredOnStart = false;
1684 } else {
1685 this.reInitRequiredOnStart = true;
1686 pendingExtras.push(extras);
1687 }
1688 }
1689
1690 private void reInit(Conversation conversation) {
1691 reInit(conversation, false);
1692 }
1693
1694 private boolean reInit(final Conversation conversation, final boolean hasExtras) {
1695 if (conversation == null) {
1696 return false;
1697 }
1698 this.conversation = conversation;
1699 //once we set the conversation all is good and it will automatically do the right thing in onStart()
1700 if (this.activity == null || this.binding == null) {
1701 return false;
1702 }
1703 Log.d(Config.LOGTAG,"reInit(hasExtras="+Boolean.toString(hasExtras)+")");
1704
1705 if (this.conversation.isRead() && hasExtras) {
1706 Log.d(Config.LOGTAG,"trimming conversation");
1707 this.conversation.trim();
1708 }
1709
1710 setupIme();
1711
1712 this.binding.textSendButton.setContentDescription(activity.getString(R.string.send_message_to_x, conversation.getName()));
1713 this.binding.textinput.setKeyboardListener(null);
1714 this.binding.textinput.setText("");
1715 this.binding.textinput.append(this.conversation.getNextMessage());
1716 this.binding.textinput.setKeyboardListener(this);
1717 messageListAdapter.updatePreferences();
1718 refresh(false);
1719 this.conversation.messagesLoaded.set(true);
1720
1721 final boolean scrolledToBottomAndNoPending = this.scrolledToBottom() && pendingScrollState.peek() == null;
1722
1723 Log.d(Config.LOGTAG,"scrolledToBottomAndNoPending="+Boolean.toString(scrolledToBottomAndNoPending));
1724
1725 if (hasExtras || scrolledToBottomAndNoPending) {
1726 synchronized (this.messageList) {
1727 Log.d(Config.LOGTAG,"jump to first unread message");
1728 final Message first = conversation.getFirstUnreadMessage();
1729 final int bottom = Math.max(0, this.messageList.size() - 1);
1730 final int pos;
1731 if (first == null) {
1732 Log.d(Config.LOGTAG,"first unread message was null");
1733 pos = bottom;
1734 } else {
1735 int i = getIndexOf(first.getUuid(), this.messageList);
1736 pos = i < 0 ? bottom : i;
1737 }
1738 this.binding.messagesView.setSelection(pos);
1739 }
1740 }
1741
1742 activity.onConversationRead(this.conversation);
1743 //TODO if we only do this when this fragment is running on main it won't *bing* in tablet layout which might be unnecessary since we can *see* it
1744 activity.xmppConnectionService.getNotificationService().setOpenConversation(this.conversation);
1745 return true;
1746 }
1747
1748 private boolean scrolledToBottom() {
1749 if (this.binding == null) {
1750 return false;
1751 }
1752 final ListView listView = this.binding.messagesView;
1753 if (listView.getLastVisiblePosition() == listView.getAdapter().getCount() -1) {
1754 final View lastChild = listView.getChildAt(listView.getChildCount() -1);
1755 return lastChild != null && lastChild.getBottom() <= listView.getHeight();
1756 } else {
1757 return false;
1758 }
1759 }
1760
1761 private void processExtras(Bundle extras) {
1762 final String downloadUuid = extras.getString(ConversationActivity.EXTRA_DOWNLOAD_UUID);
1763 final String text = extras.getString(ConversationActivity.EXTRA_TEXT);
1764 final String nick = extras.getString(ConversationActivity.EXTRA_NICK);
1765 final boolean pm = extras.getBoolean(ConversationActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
1766 if (nick != null) {
1767 if (pm) {
1768 Jid jid = conversation.getJid();
1769 try {
1770 Jid next = Jid.fromParts(jid.getLocalpart(), jid.getDomainpart(), nick);
1771 privateMessageWith(next);
1772 } catch (final InvalidJidException ignored) {
1773 //do nothing
1774 }
1775 } else {
1776 highlightInConference(nick);
1777 }
1778 } else {
1779 appendText(text);
1780 }
1781 final Message message = downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
1782 if (message != null) {
1783 startDownloadable(message);
1784 }
1785 }
1786
1787 private boolean showBlockSubmenu(View view) {
1788 final Jid jid = conversation.getJid();
1789 if (jid.isDomainJid()) {
1790 BlockContactDialog.show(activity, conversation);
1791 } else {
1792 PopupMenu popupMenu = new PopupMenu(getActivity(), view);
1793 popupMenu.inflate(R.menu.block);
1794 popupMenu.setOnMenuItemClickListener(menuItem -> {
1795 Blockable blockable;
1796 switch (menuItem.getItemId()) {
1797 case R.id.block_domain:
1798 blockable = conversation.getAccount().getRoster().getContact(jid.toDomainJid());
1799 break;
1800 default:
1801 blockable = conversation;
1802 }
1803 BlockContactDialog.show(activity, blockable);
1804 return true;
1805 });
1806 popupMenu.show();
1807 }
1808 return true;
1809 }
1810
1811 private void updateSnackBar(final Conversation conversation) {
1812 final Account account = conversation.getAccount();
1813 final XmppConnection connection = account.getXmppConnection();
1814 final int mode = conversation.getMode();
1815 final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null;
1816 if (account.getStatus() == Account.State.DISABLED) {
1817 showSnackbar(R.string.this_account_is_disabled, R.string.enable, this.mEnableAccountListener);
1818 } else if (conversation.isBlocked()) {
1819 showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
1820 } else if (contact != null && !contact.showInRoster() && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1821 showSnackbar(R.string.contact_added_you, R.string.add_back, this.mAddBackClickListener, this.mLongPressBlockListener);
1822 } else if (contact != null && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1823 showSnackbar(R.string.contact_asks_for_presence_subscription, R.string.allow, this.mAllowPresenceSubscription, this.mLongPressBlockListener);
1824 } else if (mode == Conversation.MODE_MULTI
1825 && !conversation.getMucOptions().online()
1826 && account.getStatus() == Account.State.ONLINE) {
1827 switch (conversation.getMucOptions().getError()) {
1828 case NICK_IN_USE:
1829 showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
1830 break;
1831 case NO_RESPONSE:
1832 showSnackbar(R.string.joining_conference, 0, null);
1833 break;
1834 case SERVER_NOT_FOUND:
1835 if (conversation.receivedMessagesCount() > 0) {
1836 showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc);
1837 } else {
1838 showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc);
1839 }
1840 break;
1841 case PASSWORD_REQUIRED:
1842 showSnackbar(R.string.conference_requires_password, R.string.enter_password, enterPassword);
1843 break;
1844 case BANNED:
1845 showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
1846 break;
1847 case MEMBERS_ONLY:
1848 showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
1849 break;
1850 case KICKED:
1851 showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
1852 break;
1853 case UNKNOWN:
1854 showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc);
1855 break;
1856 case INVALID_NICK:
1857 showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc);
1858 case SHUTDOWN:
1859 showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc);
1860 break;
1861 default:
1862 hideSnackbar();
1863 break;
1864 }
1865 } else if (account.hasPendingPgpIntent(conversation)) {
1866 showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
1867 } else if (connection != null
1868 && connection.getFeatures().blocking()
1869 && conversation.countMessages() != 0
1870 && !conversation.isBlocked()
1871 && conversation.isWithStranger()) {
1872 showSnackbar(R.string.received_message_from_stranger, R.string.block, mBlockClickListener);
1873 } else {
1874 hideSnackbar();
1875 }
1876 }
1877
1878 @Override
1879 public void refresh() {
1880 if (this.binding == null) {
1881 Log.d(Config.LOGTAG, "ConversationFragment.refresh() skipped updated because view binding was null");
1882 return;
1883 }
1884 this.refresh(true);
1885 }
1886
1887 private void refresh(boolean notifyConversationRead) {
1888 synchronized (this.messageList) {
1889 if (this.conversation != null) {
1890 conversation.populateWithMessages(this.messageList);
1891 updateSnackBar(conversation);
1892 updateStatusMessages();
1893 this.messageListAdapter.notifyDataSetChanged();
1894 updateChatMsgHint();
1895 if (notifyConversationRead && activity != null) {
1896 activity.onConversationRead(this.conversation);
1897 }
1898 updateSendButton();
1899 updateEditablity();
1900 }
1901 }
1902 }
1903
1904 protected void messageSent() {
1905 mSendingPgpMessage.set(false);
1906 this.binding.textinput.setText("");
1907 if (conversation.setCorrectingMessage(null)) {
1908 this.binding.textinput.append(conversation.getDraftMessage());
1909 conversation.setDraftMessage(null);
1910 }
1911 if (conversation.setNextMessage(this.binding.textinput.getText().toString())) {
1912 activity.xmppConnectionService.updateConversation(conversation);
1913 }
1914 updateChatMsgHint();
1915 new Handler().post(() -> {
1916 int size = messageList.size();
1917 this.binding.messagesView.setSelection(size - 1);
1918 });
1919 }
1920
1921 public void setFocusOnInputField() {
1922 this.binding.textinput.requestFocus();
1923 }
1924
1925 public void doneSendingPgpMessage() {
1926 mSendingPgpMessage.set(false);
1927 }
1928
1929 public long getMaxHttpUploadSize(Conversation conversation) {
1930 final XmppConnection connection = conversation.getAccount().getXmppConnection();
1931 return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
1932 }
1933
1934 private void updateEditablity() {
1935 boolean canWrite = this.conversation.getMode() == Conversation.MODE_SINGLE || this.conversation.getMucOptions().participating() || this.conversation.getNextCounterpart() != null;
1936 this.binding.textinput.setFocusable(canWrite);
1937 this.binding.textinput.setFocusableInTouchMode(canWrite);
1938 this.binding.textSendButton.setEnabled(canWrite);
1939 this.binding.textinput.setCursorVisible(canWrite);
1940 }
1941
1942 public void updateSendButton() {
1943 boolean useSendButtonToIndicateStatus = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean("send_button_status", getResources().getBoolean(R.bool.send_button_status));
1944 final Conversation c = this.conversation;
1945 final Presence.Status status;
1946 final String text = this.binding.textinput == null ? "" : this.binding.textinput.getText().toString();
1947 final SendButtonAction action = SendButtonTool.getAction(getActivity(), c, text);
1948 if (useSendButtonToIndicateStatus && c.getAccount().getStatus() == Account.State.ONLINE) {
1949 if (activity.xmppConnectionService != null && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) {
1950 status = Presence.Status.OFFLINE;
1951 } else if (c.getMode() == Conversation.MODE_SINGLE) {
1952 status = c.getContact().getShownStatus();
1953 } else {
1954 status = c.getMucOptions().online() ? Presence.Status.ONLINE : Presence.Status.OFFLINE;
1955 }
1956 } else {
1957 status = Presence.Status.OFFLINE;
1958 }
1959 this.binding.textSendButton.setTag(action);
1960 this.binding.textSendButton.setImageResource(SendButtonTool.getSendButtonImageResource(getActivity(), action, status));
1961 }
1962
1963 protected void updateDateSeparators() {
1964 synchronized (this.messageList) {
1965 for (int i = 0; i < this.messageList.size(); ++i) {
1966 final Message current = this.messageList.get(i);
1967 if (i == 0 || !UIHelper.sameDay(this.messageList.get(i - 1).getTimeSent(), current.getTimeSent())) {
1968 this.messageList.add(i, Message.createDateSeparator(current));
1969 i++;
1970 }
1971 }
1972 }
1973 }
1974
1975 protected void updateStatusMessages() {
1976 updateDateSeparators();
1977 synchronized (this.messageList) {
1978 if (showLoadMoreMessages(conversation)) {
1979 this.messageList.add(0, Message.createLoadMoreMessage(conversation));
1980 }
1981 if (conversation.getMode() == Conversation.MODE_SINGLE) {
1982 ChatState state = conversation.getIncomingChatState();
1983 if (state == ChatState.COMPOSING) {
1984 this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_is_typing, conversation.getName())));
1985 } else if (state == ChatState.PAUSED) {
1986 this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_has_stopped_typing, conversation.getName())));
1987 } else {
1988 for (int i = this.messageList.size() - 1; i >= 0; --i) {
1989 if (this.messageList.get(i).getStatus() == Message.STATUS_RECEIVED) {
1990 return;
1991 } else {
1992 if (this.messageList.get(i).getStatus() == Message.STATUS_SEND_DISPLAYED) {
1993 this.messageList.add(i + 1,
1994 Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, conversation.getName())));
1995 return;
1996 }
1997 }
1998 }
1999 }
2000 } else {
2001 final MucOptions mucOptions = conversation.getMucOptions();
2002 final List<MucOptions.User> allUsers = mucOptions.getUsers();
2003 final Set<ReadByMarker> addedMarkers = new HashSet<>();
2004 ChatState state = ChatState.COMPOSING;
2005 List<MucOptions.User> users = conversation.getMucOptions().getUsersWithChatState(state, 5);
2006 if (users.size() == 0) {
2007 state = ChatState.PAUSED;
2008 users = conversation.getMucOptions().getUsersWithChatState(state, 5);
2009 }
2010 if (mucOptions.isPrivateAndNonAnonymous()) {
2011 for (int i = this.messageList.size() - 1; i >= 0; --i) {
2012 final Set<ReadByMarker> markersForMessage = messageList.get(i).getReadByMarkers();
2013 final List<MucOptions.User> shownMarkers = new ArrayList<>();
2014 for (ReadByMarker marker : markersForMessage) {
2015 if (!ReadByMarker.contains(marker, addedMarkers)) {
2016 addedMarkers.add(marker); //may be put outside this condition. set should do dedup anyway
2017 MucOptions.User user = mucOptions.findUser(marker);
2018 if (user != null && !users.contains(user)) {
2019 shownMarkers.add(user);
2020 }
2021 }
2022 }
2023 final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i));
2024 final Message statusMessage;
2025 final int size = shownMarkers.size();
2026 if (size > 1) {
2027 final String body;
2028 if (size <= 4) {
2029 body = getString(R.string.contacts_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers));
2030 } else {
2031 body = getString(R.string.contacts_and_n_more_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers, 3), size - 3);
2032 }
2033 statusMessage = Message.createStatusMessage(conversation, body);
2034 statusMessage.setCounterparts(shownMarkers);
2035 } else if (size == 1) {
2036 statusMessage = Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, UIHelper.getDisplayName(shownMarkers.get(0))));
2037 statusMessage.setCounterpart(shownMarkers.get(0).getFullJid());
2038 statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid());
2039 } else {
2040 statusMessage = null;
2041 }
2042 if (statusMessage != null) {
2043 this.messageList.add(i + 1, statusMessage);
2044 }
2045 addedMarkers.add(markerForSender);
2046 if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) {
2047 break;
2048 }
2049 }
2050 }
2051 if (users.size() > 0) {
2052 Message statusMessage;
2053 if (users.size() == 1) {
2054 MucOptions.User user = users.get(0);
2055 int id = state == ChatState.COMPOSING ? R.string.contact_is_typing : R.string.contact_has_stopped_typing;
2056 statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.getDisplayName(user)));
2057 statusMessage.setTrueCounterpart(user.getRealJid());
2058 statusMessage.setCounterpart(user.getFullJid());
2059 } else {
2060 int id = state == ChatState.COMPOSING ? R.string.contacts_are_typing : R.string.contacts_have_stopped_typing;
2061 statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.concatNames(users)));
2062 statusMessage.setCounterparts(users);
2063 }
2064 this.messageList.add(statusMessage);
2065 }
2066
2067 }
2068 }
2069 }
2070
2071 public void stopScrolling() {
2072 long now = SystemClock.uptimeMillis();
2073 MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
2074 binding.messagesView.dispatchTouchEvent(cancel);
2075 }
2076
2077 private boolean showLoadMoreMessages(final Conversation c) {
2078 final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked();
2079 final MessageArchiveService service = activity.xmppConnectionService.getMessageArchiveService();
2080 return mam && (c.getLastClearHistory().getTimestamp() != 0 || (c.countMessages() == 0 && c.messagesLoaded.get() && c.hasMessagesLeftOnServer() && !service.queryInProgress(c)));
2081 }
2082
2083 private boolean hasMamSupport(final Conversation c) {
2084 if (c.getMode() == Conversation.MODE_SINGLE) {
2085 final XmppConnection connection = c.getAccount().getXmppConnection();
2086 return connection != null && connection.getFeatures().mam();
2087 } else {
2088 return c.getMucOptions().mamSupport();
2089 }
2090 }
2091
2092 protected void showSnackbar(final int message, final int action, final OnClickListener clickListener) {
2093 showSnackbar(message, action, clickListener, null);
2094 }
2095
2096 protected void showSnackbar(final int message, final int action, final OnClickListener clickListener, final View.OnLongClickListener longClickListener) {
2097 this.binding.snackbar.setVisibility(View.VISIBLE);
2098 this.binding.snackbar.setOnClickListener(null);
2099 this.binding.snackbarMessage.setText(message);
2100 this.binding.snackbarMessage.setOnClickListener(null);
2101 this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE);
2102 if (action != 0) {
2103 this.binding.snackbarAction.setText(action);
2104 }
2105 this.binding.snackbarAction.setOnClickListener(clickListener);
2106 this.binding.snackbarAction.setOnLongClickListener(longClickListener);
2107 }
2108
2109 protected void hideSnackbar() {
2110 this.binding.snackbar.setVisibility(View.GONE);
2111 }
2112
2113 protected void sendPlainTextMessage(Message message) {
2114 activity.xmppConnectionService.sendMessage(message);
2115 messageSent();
2116 }
2117
2118 protected void sendPgpMessage(final Message message) {
2119 final XmppConnectionService xmppService = activity.xmppConnectionService;
2120 final Contact contact = message.getConversation().getContact();
2121 if (!activity.hasPgp()) {
2122 activity.showInstallPgpDialog();
2123 return;
2124 }
2125 if (conversation.getAccount().getPgpSignature() == null) {
2126 activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished);
2127 return;
2128 }
2129 if (!mSendingPgpMessage.compareAndSet(false, true)) {
2130 Log.d(Config.LOGTAG, "sending pgp message already in progress");
2131 }
2132 if (conversation.getMode() == Conversation.MODE_SINGLE) {
2133 if (contact.getPgpKeyId() != 0) {
2134 xmppService.getPgpEngine().hasKey(contact,
2135 new UiCallback<Contact>() {
2136
2137 @Override
2138 public void userInputRequried(PendingIntent pi, Contact contact) {
2139 startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE);
2140 }
2141
2142 @Override
2143 public void success(Contact contact) {
2144 encryptTextMessage(message);
2145 }
2146
2147 @Override
2148 public void error(int error, Contact contact) {
2149 activity.runOnUiThread(() -> Toast.makeText(activity,
2150 R.string.unable_to_connect_to_keychain,
2151 Toast.LENGTH_SHORT
2152 ).show());
2153 mSendingPgpMessage.set(false);
2154 }
2155 });
2156
2157 } else {
2158 showNoPGPKeyDialog(false, (dialog, which) -> {
2159 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2160 xmppService.updateConversation(conversation);
2161 message.setEncryption(Message.ENCRYPTION_NONE);
2162 xmppService.sendMessage(message);
2163 messageSent();
2164 });
2165 }
2166 } else {
2167 if (conversation.getMucOptions().pgpKeysInUse()) {
2168 if (!conversation.getMucOptions().everybodyHasKeys()) {
2169 Toast warning = Toast
2170 .makeText(getActivity(),
2171 R.string.missing_public_keys,
2172 Toast.LENGTH_LONG);
2173 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
2174 warning.show();
2175 }
2176 encryptTextMessage(message);
2177 } else {
2178 showNoPGPKeyDialog(true, (dialog, which) -> {
2179 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
2180 message.setEncryption(Message.ENCRYPTION_NONE);
2181 xmppService.updateConversation(conversation);
2182 xmppService.sendMessage(message);
2183 messageSent();
2184 });
2185 }
2186 }
2187 }
2188
2189 public void encryptTextMessage(Message message) {
2190 activity.xmppConnectionService.getPgpEngine().encrypt(message,
2191 new UiCallback<Message>() {
2192
2193 @Override
2194 public void userInputRequried(PendingIntent pi, Message message) {
2195 startPendingIntent(pi, REQUEST_SEND_MESSAGE);
2196 }
2197
2198 @Override
2199 public void success(Message message) {
2200 //TODO the following two call can be made before the callback
2201 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
2202 activity.xmppConnectionService.sendMessage(message);
2203 getActivity().runOnUiThread(() -> messageSent());
2204 }
2205
2206 @Override
2207 public void error(final int error, Message message) {
2208 getActivity().runOnUiThread(() -> {
2209 doneSendingPgpMessage();
2210 Toast.makeText(getActivity(), R.string.unable_to_connect_to_keychain, Toast.LENGTH_SHORT).show();
2211 });
2212
2213 }
2214 });
2215 }
2216
2217 public void showNoPGPKeyDialog(boolean plural, DialogInterface.OnClickListener listener) {
2218 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
2219 builder.setIconAttribute(android.R.attr.alertDialogIcon);
2220 if (plural) {
2221 builder.setTitle(getString(R.string.no_pgp_keys));
2222 builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
2223 } else {
2224 builder.setTitle(getString(R.string.no_pgp_key));
2225 builder.setMessage(getText(R.string.contact_has_no_pgp_key));
2226 }
2227 builder.setNegativeButton(getString(R.string.cancel), null);
2228 builder.setPositiveButton(getString(R.string.send_unencrypted), listener);
2229 builder.create().show();
2230 }
2231
2232 protected void sendAxolotlMessage(final Message message) {
2233 activity.xmppConnectionService.sendMessage(message);
2234 messageSent();
2235 }
2236
2237 public void appendText(String text) {
2238 if (text == null) {
2239 return;
2240 }
2241 String previous = this.binding.textinput.getText().toString();
2242 if (previous.length() != 0 && !previous.endsWith(" ")) {
2243 text = " " + text;
2244 }
2245 this.binding.textinput.append(text);
2246 }
2247
2248 @Override
2249 public boolean onEnterPressed() {
2250 SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity());
2251 final boolean enterIsSend = p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send));
2252 if (enterIsSend) {
2253 sendMessage();
2254 return true;
2255 } else {
2256 return false;
2257 }
2258 }
2259
2260 @Override
2261 public void onTypingStarted() {
2262 final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2263 if (service == null) {
2264 return;
2265 }
2266 Account.State status = conversation.getAccount().getStatus();
2267 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
2268 service.sendChatState(conversation);
2269 }
2270 updateSendButton();
2271 }
2272
2273 @Override
2274 public void onTypingStopped() {
2275 final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2276 if (service == null) {
2277 return;
2278 }
2279 Account.State status = conversation.getAccount().getStatus();
2280 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
2281 service.sendChatState(conversation);
2282 }
2283 }
2284
2285 @Override
2286 public void onTextDeleted() {
2287 final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
2288 if (service == null) {
2289 return;
2290 }
2291 Account.State status = conversation.getAccount().getStatus();
2292 if (status == Account.State.ONLINE && conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
2293 service.sendChatState(conversation);
2294 }
2295 updateSendButton();
2296 }
2297
2298 @Override
2299 public void onTextChanged() {
2300 if (conversation != null && conversation.getCorrectingMessage() != null) {
2301 updateSendButton();
2302 }
2303 }
2304
2305 @Override
2306 public boolean onTabPressed(boolean repeated) {
2307 if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) {
2308 return false;
2309 }
2310 if (repeated) {
2311 completionIndex++;
2312 } else {
2313 lastCompletionLength = 0;
2314 completionIndex = 0;
2315 final String content = this.binding.textinput.getText().toString();
2316 lastCompletionCursor = this.binding.textinput.getSelectionEnd();
2317 int start = lastCompletionCursor > 0 ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1 : 0;
2318 firstWord = start == 0;
2319 incomplete = content.substring(start, lastCompletionCursor);
2320 }
2321 List<String> completions = new ArrayList<>();
2322 for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
2323 String name = user.getName();
2324 if (name != null && name.startsWith(incomplete)) {
2325 completions.add(name + (firstWord ? ": " : " "));
2326 }
2327 }
2328 Collections.sort(completions);
2329 if (completions.size() > completionIndex) {
2330 String completion = completions.get(completionIndex).substring(incomplete.length());
2331 this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
2332 this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion);
2333 lastCompletionLength = completion.length();
2334 } else {
2335 completionIndex = -1;
2336 this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength);
2337 lastCompletionLength = 0;
2338 }
2339 return true;
2340 }
2341
2342 private void startPendingIntent(PendingIntent pendingIntent, int requestCode) {
2343 try {
2344 getActivity().startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0);
2345 } catch (final SendIntentException ignored) {
2346 }
2347 }
2348
2349 @Override
2350 public void onBackendConnected() {
2351 Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()");
2352 String uuid = pendingConversationsUuid.pop();
2353 if (uuid != null) {
2354 Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid);
2355 if (conversation == null) {
2356 Log.d(Config.LOGTAG, "unable to restore activity");
2357 clearPending();
2358 return;
2359 }
2360 reInit(conversation);
2361 ScrollState scrollState = pendingScrollState.pop();
2362 if (scrollState != null) {
2363 setScrollPosition(scrollState);
2364 }
2365 }
2366 ActivityResult activityResult = postponedActivityResult.pop();
2367 if (activityResult != null) {
2368 handleActivityResult(activityResult);
2369 }
2370 }
2371
2372 public void clearPending() {
2373 if (postponedActivityResult.pop() != null) {
2374 Log.d(Config.LOGTAG, "cleared pending intent with unhandled result left");
2375 }
2376 pendingScrollState.pop();
2377 pendingTakePhotoUri.pop();
2378 }
2379
2380 public Conversation getConversation() {
2381 return conversation;
2382 }
2383}