This repository has been archived by the owner on Nov 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 237
/
WorkingMessage.java
executable file
·1751 lines (1526 loc) · 66.3 KB
/
WorkingMessage.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.data;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SqliteWrapper;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Telephony.Mms;
import android.provider.Telephony.MmsSms;
import android.provider.Telephony.MmsSms.PendingMessages;
import android.provider.Telephony.Sms;
import android.telephony.SmsMessage;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import com.android.common.contacts.DataUsageStatUpdater;
import com.android.common.userhappiness.UserHappinessSignals;
import com.android.mms.ExceedMessageSizeException;
import com.android.mms.LogTag;
import com.android.mms.MmsApp;
import com.android.mms.MmsConfig;
import com.android.mms.ResolutionException;
import com.android.mms.UnsupportContentTypeException;
import com.android.mms.model.ImageModel;
import com.android.mms.model.SlideModel;
import com.android.mms.model.SlideshowModel;
import com.android.mms.model.TextModel;
import com.android.mms.transaction.MessageSender;
import com.android.mms.transaction.MmsMessageSender;
import com.android.mms.transaction.SmsMessageSender;
import com.android.mms.ui.ComposeMessageActivity;
import com.android.mms.ui.MessageUtils;
import com.android.mms.ui.SlideshowEditor;
import com.android.mms.util.DraftCache;
import com.android.mms.util.Recycler;
import com.android.mms.util.ThumbnailManager;
import com.android.mms.widget.MmsWidgetProvider;
import com.google.android.mms.ContentType;
import com.google.android.mms.MmsException;
import com.google.android.mms.pdu.EncodedStringValue;
import com.google.android.mms.pdu.PduBody;
import com.google.android.mms.pdu.PduHeaders;
import com.google.android.mms.pdu.PduPersister;
import com.google.android.mms.pdu.SendReq;
/**
* Contains all state related to a message being edited by the user.
*/
public class WorkingMessage {
private static final String TAG = "WorkingMessage";
private static final boolean DEBUG = false;
// Public intents
public static final String ACTION_SENDING_SMS = "android.intent.action.SENDING_SMS";
// Intent extras
public static final String EXTRA_SMS_MESSAGE = "android.mms.extra.MESSAGE";
public static final String EXTRA_SMS_RECIPIENTS = "android.mms.extra.RECIPIENTS";
public static final String EXTRA_SMS_THREAD_ID = "android.mms.extra.THREAD_ID";
// Database access stuff
private final Activity mActivity;
private final ContentResolver mContentResolver;
// States that can require us to save or send a message as MMS.
private static final int RECIPIENTS_REQUIRE_MMS = (1 << 0); // 1
private static final int HAS_SUBJECT = (1 << 1); // 2
private static final int HAS_ATTACHMENT = (1 << 2); // 4
private static final int LENGTH_REQUIRES_MMS = (1 << 3); // 8
private static final int FORCE_MMS = (1 << 4); // 16
// A bitmap of the above indicating different properties of the message;
// any bit set will require the message to be sent via MMS.
private int mMmsState;
// Errors from setAttachment()
public static final int OK = 0;
public static final int UNKNOWN_ERROR = -1;
public static final int MESSAGE_SIZE_EXCEEDED = -2;
public static final int UNSUPPORTED_TYPE = -3;
public static final int IMAGE_TOO_LARGE = -4;
// Attachment types
public static final int TEXT = 0;
public static final int IMAGE = 1;
public static final int VIDEO = 2;
public static final int AUDIO = 3;
public static final int SLIDESHOW = 4;
// Current attachment type of the message; one of the above values.
private int mAttachmentType;
// Conversation this message is targeting.
private Conversation mConversation;
// Text of the message.
private CharSequence mText;
// Slideshow for this message, if applicable. If it's a simple attachment,
// i.e. not SLIDESHOW, it will contain only one slide.
private SlideshowModel mSlideshow;
// Data URI of an MMS message if we have had to save it.
private Uri mMessageUri;
// MMS subject line for this message
private CharSequence mSubject;
// Set to true if this message has been discarded.
private boolean mDiscarded = false;
// Track whether we have drafts
private volatile boolean mHasMmsDraft;
private volatile boolean mHasSmsDraft;
// Cached value of mms enabled flag
private static boolean sMmsEnabled = MmsConfig.getMmsEnabled();
// Our callback interface
private final MessageStatusListener mStatusListener;
private List<String> mWorkingRecipients;
// Message sizes in Outbox
private static final String[] MMS_OUTBOX_PROJECTION = {
Mms._ID, // 0
Mms.MESSAGE_SIZE // 1
};
private static final int MMS_MESSAGE_SIZE_INDEX = 1;
/**
* Callback interface for communicating important state changes back to
* ComposeMessageActivity.
*/
public interface MessageStatusListener {
/**
* Called when the protocol for sending the message changes from SMS
* to MMS, and vice versa.
*
* @param mms If true, it changed to MMS. If false, to SMS.
*/
void onProtocolChanged(boolean mms);
/**
* Called when an attachment on the message has changed.
*/
void onAttachmentChanged();
/**
* Called just before the process of sending a message.
*/
void onPreMessageSent();
/**
* Called once the process of sending a message, triggered by
* {@link send} has completed. This doesn't mean the send succeeded,
* just that it has been dispatched to the network.
*/
void onMessageSent();
/**
* Called if there are too many unsent messages in the queue and we're not allowing
* any more Mms's to be sent.
*/
void onMaxPendingMessagesReached();
/**
* Called if there's an attachment error while resizing the images just before sending.
*/
void onAttachmentError(int error);
}
private WorkingMessage(ComposeMessageActivity activity) {
mActivity = activity;
mContentResolver = mActivity.getContentResolver();
mStatusListener = activity;
mAttachmentType = TEXT;
mText = "";
}
/**
* Creates a new working message.
*/
public static WorkingMessage createEmpty(ComposeMessageActivity activity) {
// Make a new empty working message.
WorkingMessage msg = new WorkingMessage(activity);
return msg;
}
/**
* Create a new WorkingMessage from the specified data URI, which typically
* contains an MMS message.
*/
public static WorkingMessage load(ComposeMessageActivity activity, Uri uri) {
// If the message is not already in the draft box, move it there.
if (!uri.toString().startsWith(Mms.Draft.CONTENT_URI.toString())) {
PduPersister persister = PduPersister.getPduPersister(activity);
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
LogTag.debug("load: moving %s to drafts", uri);
}
try {
uri = persister.move(uri, Mms.Draft.CONTENT_URI);
} catch (MmsException e) {
LogTag.error("Can't move %s to drafts", uri);
return null;
}
}
WorkingMessage msg = new WorkingMessage(activity);
if (msg.loadFromUri(uri)) {
msg.mHasMmsDraft = true;
return msg;
}
return null;
}
private void correctAttachmentState() {
int slideCount = mSlideshow.size();
// If we get an empty slideshow, tear down all MMS
// state and discard the unnecessary message Uri.
if (slideCount == 0) {
removeAttachment(false);
} else if (slideCount > 1) {
mAttachmentType = SLIDESHOW;
} else {
SlideModel slide = mSlideshow.get(0);
if (slide.hasImage()) {
mAttachmentType = IMAGE;
} else if (slide.hasVideo()) {
mAttachmentType = VIDEO;
} else if (slide.hasAudio()) {
mAttachmentType = AUDIO;
}
}
updateState(HAS_ATTACHMENT, hasAttachment(), false);
}
private boolean loadFromUri(Uri uri) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) LogTag.debug("loadFromUri %s", uri);
try {
mSlideshow = SlideshowModel.createFromMessageUri(mActivity, uri);
} catch (MmsException e) {
LogTag.error("Couldn't load URI %s", uri);
return false;
}
mMessageUri = uri;
// Make sure all our state is as expected.
syncTextFromSlideshow();
correctAttachmentState();
return true;
}
/**
* Load the draft message for the specified conversation, or a new empty message if
* none exists.
*/
public static WorkingMessage loadDraft(ComposeMessageActivity activity,
final Conversation conv,
final Runnable onDraftLoaded) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) LogTag.debug("loadDraft %s", conv);
final WorkingMessage msg = createEmpty(activity);
if (conv.getThreadId() <= 0) {
if (onDraftLoaded != null) {
onDraftLoaded.run();
}
return msg;
}
new AsyncTask<Void, Void, Pair<String, String>>() {
// Return a Pair where:
// first - non-empty String representing the text of an SMS draft
// second - non-null String representing the text of an MMS subject
@Override
protected Pair<String, String> doInBackground(Void... none) {
// Look for an SMS draft first.
String draftText = msg.readDraftSmsMessage(conv);
String subject = null;
if (TextUtils.isEmpty(draftText)) {
// No SMS draft so look for an MMS draft.
StringBuilder sb = new StringBuilder();
Uri uri = readDraftMmsMessage(msg.mActivity, conv, sb);
if (uri != null) {
if (msg.loadFromUri(uri)) {
// If there was an MMS message, readDraftMmsMessage
// will put the subject in our supplied StringBuilder.
subject = sb.toString();
}
}
}
Pair<String, String> result = new Pair<String, String>(draftText, subject);
return result;
}
@Override
protected void onPostExecute(Pair<String, String> result) {
if (!TextUtils.isEmpty(result.first)) {
msg.mHasSmsDraft = true;
msg.setText(result.first);
}
if (result.second != null) {
msg.mHasMmsDraft = true;
if (!TextUtils.isEmpty(result.second)) {
msg.setSubject(result.second, false);
}
}
if (onDraftLoaded != null) {
onDraftLoaded.run();
}
}
}.execute();
return msg;
}
/**
* Sets the text of the message to the specified CharSequence.
*/
public void setText(CharSequence s) {
mText = s;
}
/**
* Returns the current message text.
*/
public CharSequence getText() {
return mText;
}
/**
* @return True if the message has any text. A message with just whitespace is not considered
* to have text.
*/
public boolean hasText() {
return mText != null && TextUtils.getTrimmedLength(mText) > 0;
}
public void removeAttachment(boolean notify) {
removeThumbnailsFromCache(mSlideshow);
mAttachmentType = TEXT;
mSlideshow = null;
if (mMessageUri != null) {
asyncDelete(mMessageUri, null, null);
mMessageUri = null;
}
// mark this message as no longer having an attachment
updateState(HAS_ATTACHMENT, false, notify);
if (notify) {
// Tell ComposeMessageActivity (or other listener) that the attachment has changed.
// In the case of ComposeMessageActivity, it will remove its attachment panel because
// this working message no longer has an attachment.
mStatusListener.onAttachmentChanged();
}
}
public static void removeThumbnailsFromCache(SlideshowModel slideshow) {
if (slideshow != null) {
ThumbnailManager thumbnailManager = MmsApp.getApplication().getThumbnailManager();
boolean removedSomething = false;
Iterator<SlideModel> iterator = slideshow.iterator();
while (iterator.hasNext()) {
SlideModel slideModel = iterator.next();
if (slideModel.hasImage()) {
thumbnailManager.removeThumbnail(slideModel.getImage().getUri());
removedSomething = true;
} else if (slideModel.hasVideo()) {
thumbnailManager.removeThumbnail(slideModel.getVideo().getUri());
removedSomething = true;
}
}
if (removedSomething) {
// HACK: the keys to the thumbnail cache are the part uris, such as mms/part/3
// Because the part table doesn't have auto-increment ids, the part ids are reused
// when a message or thread is deleted. For now, we're clearing the whole thumbnail
// cache so we don't retrieve stale images when part ids are reused. This will be
// fixed in the next release in the mms provider.
MmsApp.getApplication().getThumbnailManager().clearBackingStore();
}
}
}
/**
* Adds an attachment to the message, replacing an old one if it existed.
* @param type Type of this attachment, such as {@link IMAGE}
* @param dataUri Uri containing the attachment data (or null for {@link TEXT})
* @param append true if we should add the attachment to a new slide
* @return An error code such as {@link UNKNOWN_ERROR} or {@link OK} if successful
*/
public int setAttachment(int type, Uri dataUri, boolean append) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
LogTag.debug("setAttachment type=%d uri %s", type, dataUri);
}
int result = OK;
SlideshowEditor slideShowEditor = new SlideshowEditor(mActivity, mSlideshow);
// Special case for deleting a slideshow. When ComposeMessageActivity gets told to
// remove an attachment (search for AttachmentEditor.MSG_REMOVE_ATTACHMENT), it calls
// this function setAttachment with a type of TEXT and a null uri. Basically, it's turning
// the working message from an MMS back to a simple SMS. The various attachment types
// use slide[0] as a special case. The call to ensureSlideshow below makes sure there's
// a slide zero. In the case of an already attached slideshow, ensureSlideshow will do
// nothing and the slideshow will remain such that if a user adds a slideshow again, they'll
// see their old slideshow they previously deleted. Here we really delete the slideshow.
if (type == TEXT && mAttachmentType == SLIDESHOW && mSlideshow != null && dataUri == null
&& !append) {
slideShowEditor.removeAllSlides();
}
// Make sure mSlideshow is set up and has a slide.
ensureSlideshow(); // mSlideshow can be null before this call, won't be afterwards
slideShowEditor.setSlideshow(mSlideshow);
// Change the attachment
result = append ? appendMedia(type, dataUri, slideShowEditor)
: changeMedia(type, dataUri, slideShowEditor);
// If we were successful, update mAttachmentType and notify
// the listener than there was a change.
if (result == OK) {
mAttachmentType = type;
}
correctAttachmentState();
if (type == IMAGE) {
// Prime the image's cache; helps A LOT when the image is coming from the network
// (e.g. Picasa album). See b/5445690.
int numSlides = mSlideshow.size();
if (numSlides > 0) {
ImageModel imgModel = mSlideshow.get(numSlides - 1).getImage();
if (imgModel != null) {
cancelThumbnailLoading();
imgModel.loadThumbnailBitmap(null);
}
}
}
mStatusListener.onAttachmentChanged(); // have to call whether succeeded or failed,
// because a replace that fails, removes the slide
if (!append && mAttachmentType == TEXT && type == TEXT) {
int[] params = SmsMessage.calculateLength(getText(), false);
/* SmsMessage.calculateLength returns an int[4] with:
* int[0] being the number of SMS's required,
* int[1] the number of code units used,
* int[2] is the number of code units remaining until the next message.
* int[3] is the encoding type that should be used for the message.
*/
int smsSegmentCount = params[0];
if (!MmsConfig.getMultipartSmsEnabled()) {
// The provider doesn't support multi-part sms's so as soon as the user types
// an sms longer than one segment, we have to turn the message into an mms.
setLengthRequiresMms(smsSegmentCount > 1, false);
} else {
int threshold = MmsConfig.getSmsToMmsTextThreshold();
setLengthRequiresMms(threshold > 0 && smsSegmentCount > threshold, false);
}
} else {
// Set HAS_ATTACHMENT if we need it.
updateState(HAS_ATTACHMENT, hasAttachment(), true);
}
return result;
}
/**
* Returns true if this message contains anything worth saving.
*/
public boolean isWorthSaving() {
// If it actually contains anything, it's of course not empty.
if (hasText() || hasSubject() || hasAttachment() || hasSlideshow()) {
return true;
}
// When saveAsMms() has been called, we set FORCE_MMS to represent
// sort of an "invisible attachment" so that the message isn't thrown
// away when we are shipping it off to other activities.
if (isFakeMmsForDraft()) {
return true;
}
return false;
}
private void cancelThumbnailLoading() {
int numSlides = mSlideshow != null ? mSlideshow.size() : 0;
if (numSlides > 0) {
ImageModel imgModel = mSlideshow.get(numSlides - 1).getImage();
if (imgModel != null) {
imgModel.cancelThumbnailLoading();
}
}
}
/**
* Returns true if FORCE_MMS is set.
* When saveAsMms() has been called, we set FORCE_MMS to represent
* sort of an "invisible attachment" so that the message isn't thrown
* away when we are shipping it off to other activities.
*/
public boolean isFakeMmsForDraft() {
return (mMmsState & FORCE_MMS) > 0;
}
/**
* Makes sure mSlideshow is set up.
*/
private void ensureSlideshow() {
if (mSlideshow != null) {
return;
}
SlideshowModel slideshow = SlideshowModel.createNew(mActivity);
SlideModel slide = new SlideModel(slideshow);
slideshow.add(slide);
mSlideshow = slideshow;
}
/**
* Change the message's attachment to the data in the specified Uri.
* Used only for single-slide ("attachment mode") messages. If the attachment fails to
* attach, restore the slide to its original state.
*/
private int changeMedia(int type, Uri uri, SlideshowEditor slideShowEditor) {
SlideModel originalSlide = mSlideshow.get(0);
if (originalSlide != null) {
slideShowEditor.removeSlide(0); // remove the original slide
}
slideShowEditor.addNewSlide(0);
SlideModel slide = mSlideshow.get(0); // get the new empty slide
int result = OK;
if (slide == null) {
Log.w(LogTag.TAG, "[WorkingMessage] changeMedia: no slides!");
return result;
}
// Clear the attachment type since we removed all the attachments. If this isn't cleared
// and the slide.add fails (for instance, a selected video could be too big), we'll be
// left in a state where we think we have an attachment, but it's been removed from the
// slide.
mAttachmentType = TEXT;
// If we're changing to text, just bail out.
if (type == TEXT) {
return result;
}
result = internalChangeMedia(type, uri, 0, slideShowEditor);
if (result != OK) {
slideShowEditor.removeSlide(0); // remove the failed slide
if (originalSlide != null) {
slideShowEditor.addSlide(0, originalSlide); // restore the original slide.
}
}
return result;
}
/**
* Add the message's attachment to the data in the specified Uri to a new slide.
*/
private int appendMedia(int type, Uri uri, SlideshowEditor slideShowEditor) {
int result = OK;
// If we're changing to text, just bail out.
if (type == TEXT) {
return result;
}
// The first time this method is called, mSlideshow.size() is going to be
// one (a newly initialized slideshow has one empty slide). The first time we
// attach the picture/video to that first empty slide. From then on when this
// function is called, we've got to create a new slide and add the picture/video
// to that new slide.
boolean addNewSlide = true;
if (mSlideshow.size() == 1 && !mSlideshow.isSimple()) {
addNewSlide = false;
}
if (addNewSlide) {
if (!slideShowEditor.addNewSlide()) {
return result;
}
}
int slideNum = mSlideshow.size() - 1;
result = internalChangeMedia(type, uri, slideNum, slideShowEditor);
if (result != OK) {
// We added a new slide and what we attempted to insert on the slide failed.
// Delete that slide, otherwise we could end up with a bunch of blank slides.
// It's ok that we're removing the slide even if we didn't add it (because it was
// the first default slide). If adding the first slide fails, we want to remove it.
slideShowEditor.removeSlide(slideNum);
}
return result;
}
private int internalChangeMedia(int type, Uri uri, int slideNum,
SlideshowEditor slideShowEditor) {
int result = OK;
try {
if (type == IMAGE) {
slideShowEditor.changeImage(slideNum, uri);
} else if (type == VIDEO) {
slideShowEditor.changeVideo(slideNum, uri);
} else if (type == AUDIO) {
slideShowEditor.changeAudio(slideNum, uri);
} else {
result = UNSUPPORTED_TYPE;
}
} catch (MmsException e) {
Log.e(TAG, "internalChangeMedia:", e);
result = UNKNOWN_ERROR;
} catch (UnsupportContentTypeException e) {
Log.e(TAG, "internalChangeMedia:", e);
result = UNSUPPORTED_TYPE;
} catch (ExceedMessageSizeException e) {
Log.e(TAG, "internalChangeMedia:", e);
result = MESSAGE_SIZE_EXCEEDED;
} catch (ResolutionException e) {
Log.e(TAG, "internalChangeMedia:", e);
result = IMAGE_TOO_LARGE;
}
return result;
}
/**
* Returns true if the message has an attachment (including slideshows).
*/
public boolean hasAttachment() {
return (mAttachmentType > TEXT);
}
/**
* Returns the slideshow associated with this message.
*/
public SlideshowModel getSlideshow() {
return mSlideshow;
}
/**
* Returns true if the message has a real slideshow, as opposed to just
* one image attachment, for example.
*/
public boolean hasSlideshow() {
return (mAttachmentType == SLIDESHOW);
}
/**
* Sets the MMS subject of the message. Passing null indicates that there
* is no subject. Passing "" will result in an empty subject being added
* to the message, possibly triggering a conversion to MMS. This extra
* bit of state is needed to support ComposeMessageActivity converting to
* MMS when the user adds a subject. An empty subject will be removed
* before saving to disk or sending, however.
*/
public void setSubject(CharSequence s, boolean notify) {
mSubject = s;
updateState(HAS_SUBJECT, (s != null), notify);
}
/**
* Returns the MMS subject of the message.
*/
public CharSequence getSubject() {
return mSubject;
}
/**
* Returns true if this message has an MMS subject. A subject has to be more than just
* whitespace.
* @return
*/
public boolean hasSubject() {
return mSubject != null && TextUtils.getTrimmedLength(mSubject) > 0;
}
/**
* Moves the message text into the slideshow. Should be called any time
* the message is about to be sent or written to disk.
*/
private void syncTextToSlideshow() {
if (mSlideshow == null || mSlideshow.size() != 1)
return;
SlideModel slide = mSlideshow.get(0);
TextModel text;
if (!slide.hasText()) {
// Add a TextModel to slide 0 if one doesn't already exist
text = new TextModel(mActivity, ContentType.TEXT_PLAIN, "text_0.txt",
mSlideshow.getLayout().getTextRegion());
slide.add(text);
} else {
// Otherwise just reuse the existing one.
text = slide.getText();
}
text.setText(mText);
}
/**
* Sets the message text out of the slideshow. Should be called any time
* a slideshow is loaded from disk.
*/
private void syncTextFromSlideshow() {
// Don't sync text for real slideshows.
if (mSlideshow.size() != 1) {
return;
}
SlideModel slide = mSlideshow.get(0);
if (slide == null || !slide.hasText()) {
return;
}
mText = slide.getText().getText();
}
/**
* Removes the subject if it is empty, possibly converting back to SMS.
*/
private void removeSubjectIfEmpty(boolean notify) {
if (!hasSubject()) {
setSubject(null, notify);
}
}
/**
* Gets internal message state ready for storage. Should be called any
* time the message is about to be sent or written to disk.
*/
private void prepareForSave(boolean notify) {
// Make sure our working set of recipients is resolved
// to first-class Contact objects before we save.
syncWorkingRecipients();
if (requiresMms()) {
ensureSlideshow();
syncTextToSlideshow();
}
}
/**
* Resolve the temporary working set of recipients to a ContactList.
*/
public void syncWorkingRecipients() {
if (mWorkingRecipients != null) {
ContactList recipients = ContactList.getByNumbers(mWorkingRecipients, false);
mConversation.setRecipients(recipients); // resets the threadId to zero
mWorkingRecipients = null;
}
}
public String getWorkingRecipients() {
// this function is used for DEBUG only
if (mWorkingRecipients == null) {
return null;
}
ContactList recipients = ContactList.getByNumbers(mWorkingRecipients, false);
return recipients.serialize();
}
// Call when we've returned from adding an attachment. We're no longer forcing the message
// into a Mms message. At this point we either have the goods to make the message a Mms
// or we don't. No longer fake it.
public void removeFakeMmsForDraft() {
updateState(FORCE_MMS, false, false);
}
/**
* Force the message to be saved as MMS and return the Uri of the message.
* Typically used when handing a message off to another activity.
*/
public Uri saveAsMms(boolean notify) {
if (DEBUG) LogTag.debug("saveAsMms mConversation=%s", mConversation);
// If we have discarded the message, just bail out.
if (mDiscarded) {
LogTag.warn("saveAsMms mDiscarded: true mConversation: " + mConversation +
" returning NULL uri and bailing");
return null;
}
// FORCE_MMS behaves as sort of an "invisible attachment", making
// the message seem non-empty (and thus not discarded). This bit
// is sticky until the last other MMS bit is removed, at which
// point the message will fall back to SMS.
updateState(FORCE_MMS, true, notify);
// Collect our state to be written to disk.
prepareForSave(true /* notify */);
try {
// Make sure we are saving to the correct thread ID.
DraftCache.getInstance().setSavingDraft(true);
if (!mConversation.getRecipients().isEmpty()) {
mConversation.ensureThreadId();
}
mConversation.setDraftState(true);
PduPersister persister = PduPersister.getPduPersister(mActivity);
SendReq sendReq = makeSendReq(mConversation, mSubject);
// If we don't already have a Uri lying around, make a new one. If we do
// have one already, make sure it is synced to disk.
if (mMessageUri == null) {
mMessageUri = createDraftMmsMessage(persister, sendReq, mSlideshow, null);
} else {
updateDraftMmsMessage(mMessageUri, persister, mSlideshow, sendReq);
}
mHasMmsDraft = true;
} finally {
DraftCache.getInstance().setSavingDraft(false);
}
return mMessageUri;
}
/**
* Save this message as a draft in the conversation previously specified
* to {@link setConversation}.
*/
public void saveDraft(final boolean isStopping) {
// If we have discarded the message, just bail out.
if (mDiscarded) {
LogTag.warn("saveDraft mDiscarded: true mConversation: " + mConversation +
" skipping saving draft and bailing");
return;
}
// Make sure setConversation was called.
if (mConversation == null) {
throw new IllegalStateException("saveDraft() called with no conversation");
}
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
LogTag.debug("saveDraft for mConversation " + mConversation);
}
// Get ready to write to disk. But don't notify message status when saving draft
prepareForSave(false /* notify */);
if (requiresMms()) {
asyncUpdateDraftMmsMessage(mConversation, isStopping);
mHasMmsDraft = true;
} else {
String content = mText.toString();
// bug 2169583: don't bother creating a thread id only to delete the thread
// because the content is empty. When we delete the thread in updateDraftSmsMessage,
// we didn't nullify conv.mThreadId, causing a temperary situation where conv
// is holding onto a thread id that isn't in the database. If a new message arrives
// and takes that thread id (because it's the next thread id to be assigned), the
// new message will be merged with the draft message thread, causing confusion!
if (!TextUtils.isEmpty(content)) {
asyncUpdateDraftSmsMessage(mConversation, content);
mHasSmsDraft = true;
} else {
// When there's no associated text message, we have to handle the case where there
// might have been a previous mms draft for this message. This can happen when a
// user turns an mms back into a sms, such as creating an mms draft with a picture,
// then removing the picture.
asyncDeleteDraftMmsMessage(mConversation);
mMessageUri = null;
}
}
// Update state of the draft cache.
mConversation.setDraftState(true);
}
synchronized public void discard() {
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
LogTag.debug("[WorkingMessage] discard");
}
if (mDiscarded == true) {
return;
}
// Mark this message as discarded in order to make saveDraft() no-op.
mDiscarded = true;
cancelThumbnailLoading();
// Delete any associated drafts if there are any.
if (mHasMmsDraft) {
asyncDeleteDraftMmsMessage(mConversation);
}
if (mHasSmsDraft) {
asyncDeleteDraftSmsMessage(mConversation);
}
clearConversation(mConversation, true);
}
public void unDiscard() {
if (DEBUG) LogTag.debug("unDiscard");
mDiscarded = false;
}
/**
* Returns true if discard() has been called on this message.
*/
public boolean isDiscarded() {
return mDiscarded;
}
/**
* To be called from our Activity's onSaveInstanceState() to give us a chance
* to stow our state away for later retrieval.
*
* @param bundle The Bundle passed in to onSaveInstanceState
*/
public void writeStateToBundle(Bundle bundle) {
if (hasSubject()) {
bundle.putString("subject", mSubject.toString());
}
if (mMessageUri != null) {
bundle.putParcelable("msg_uri", mMessageUri);
} else if (hasText()) {
bundle.putString("sms_body", mText.toString());
}
}
/**
* To be called from our Activity's onCreate() if the activity manager
* has given it a Bundle to reinflate
* @param bundle The Bundle passed in to onCreate
*/
public void readStateFromBundle(Bundle bundle) {
if (bundle == null) {
return;
}
String subject = bundle.getString("subject");
setSubject(subject, false);
Uri uri = (Uri)bundle.getParcelable("msg_uri");
if (uri != null) {
loadFromUri(uri);
return;
} else {
String body = bundle.getString("sms_body");
mText = body;
}
}
/**
* Update the temporary list of recipients, used when setting up a
* new conversation. Will be converted to a ContactList on any
* save event (send, save draft, etc.)
*/
public void setWorkingRecipients(List<String> numbers) {
mWorkingRecipients = numbers;
String s = null;
if (numbers != null) {
int size = numbers.size();
switch (size) {
case 1:
s = numbers.get(0);
break;
case 0:
s = "empty";
break;
default:
s = "{...} len=" + size;
}
}
}