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