-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
AztecEditorFragment.java
1696 lines (1417 loc) · 71.2 KB
/
AztecEditorFragment.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
package org.wordpress.android.editor;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.ClipDescription;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatTextView;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.DragEvent;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.URLUtil;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;
import org.wordpress.android.editor.MetadataUtils.AttributesWithClass;
import org.wordpress.android.util.AppLog;
import org.wordpress.android.util.DisplayUtils;
import org.wordpress.android.util.ImageUtils;
import org.wordpress.android.util.JSONUtils;
import org.wordpress.android.util.ProfilingUtils;
import org.wordpress.android.util.StringUtils;
import org.wordpress.android.util.ToastUtils;
import org.wordpress.android.util.UrlUtils;
import org.wordpress.android.util.helpers.MediaFile;
import org.wordpress.android.util.helpers.MediaGallery;
import org.wordpress.aztec.Aztec;
import org.wordpress.aztec.AztecAttributes;
import org.wordpress.aztec.AztecParser;
import org.wordpress.aztec.AztecText;
import org.wordpress.aztec.AztecTextFormat;
import org.wordpress.aztec.Html;
import org.wordpress.aztec.IHistoryListener;
import org.wordpress.aztec.ITextFormat;
import org.wordpress.aztec.plugins.IAztecPlugin;
import org.wordpress.aztec.plugins.shortcodes.AudioShortcodePlugin;
import org.wordpress.aztec.plugins.shortcodes.CaptionShortcodePlugin;
import org.wordpress.aztec.plugins.shortcodes.VideoShortcodePlugin;
import org.wordpress.aztec.plugins.shortcodes.handlers.CaptionHandler;
import org.wordpress.aztec.plugins.wpcomments.CommentsTextFormat;
import org.wordpress.aztec.plugins.wpcomments.WordPressCommentsPlugin;
import org.wordpress.aztec.plugins.wpcomments.toolbar.MoreToolbarButton;
import org.wordpress.aztec.source.SourceViewEditText;
import org.wordpress.aztec.spans.AztecMediaSpan;
import org.wordpress.aztec.spans.IAztecAttributedSpan;
import org.wordpress.aztec.toolbar.AztecToolbar;
import org.wordpress.aztec.toolbar.IAztecToolbarClickListener;
import org.wordpress.aztec.watchers.BlockElementWatcher;
import org.xml.sax.Attributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
public class AztecEditorFragment extends EditorFragmentAbstract implements
AztecText.OnImeBackListener,
AztecText.OnImageTappedListener,
AztecText.OnVideoTappedListener,
AztecText.OnMediaDeletedListener,
EditorMediaUploadListener,
IAztecToolbarClickListener,
IHistoryListener {
private static final String ATTR_ALIGN_DASH = "align-";
private static final String ATTR_CLASS = "class";
private static final String ATTR_ID_WP = "data-wpid";
private static final String ATTR_IMAGE_WP_DASH = "wp-image-";
private static final String ATTR_SIZE = "size";
private static final String ATTR_SIZE_DASH = "size-";
private static final String TEMP_IMAGE_ID = "data-temp-aztec-id";
private static final String TEMP_VIDEO_UPLOADING_CLASS = "data-temp-aztec-video";
private static final int MIN_BITMAP_DIMENSION_DP = 48;
public static final int DEFAULT_MEDIA_PLACEHOLDER_DIMENSION_DP = 196;
private static final int MAX_ACTION_TIME_MS = 2000;
private static final MediaFile DEFAULT_MEDIA = new MediaFile();
private static final int DEFAULT_MEDIA_HEIGHT = DEFAULT_MEDIA.getHeight();
private static final int DEFAULT_MEDIA_WIDTH = DEFAULT_MEDIA.getWidth();
private static final List<String> DRAGNDROP_SUPPORTED_MIMETYPES_TEXT = Arrays.asList(ClipDescription
.MIMETYPE_TEXT_PLAIN, ClipDescription.MIMETYPE_TEXT_HTML);
private static final List<String> DRAGNDROP_SUPPORTED_MIMETYPES_IMAGE = Arrays.asList("image/jpeg", "image/png");
private static boolean mIsToolbarExpanded = false;
private boolean mIsKeyboardOpen = false;
private boolean mEditorWasPaused = false;
private boolean mHideActionBarOnSoftKeyboardUp = false;
private AztecText title;
private AztecText content;
private boolean mAztecReady;
private SourceViewEditText source;
private AztecToolbar formattingToolbar;
private Html.ImageGetter aztecImageLoader;
private Html.VideoThumbnailGetter aztecVideoLoader;
private Handler invalidateOptionsHandler;
private Runnable invalidateOptionsRunnable;
private HashMap<String, Float> mUploadingMediaProgressMax;
private Set<String> mFailedMediaIds;
private long mActionStartedAt = -1;
private MediaPredicate mTappedMediaPredicate;
private EditorBetaClickListener mEditorBetaClickListener;
public static AztecEditorFragment newInstance(String title, String content, boolean isExpanded) {
mIsToolbarExpanded = isExpanded;
AztecEditorFragment fragment = new AztecEditorFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM_TITLE, title);
args.putString(ARG_PARAM_CONTENT, content);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ProfilingUtils.start("Visual Editor Startup");
ProfilingUtils.split("EditorFragment.onCreate");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_aztec_editor, container, false);
// request dependency injection
if (getActivity() instanceof EditorFragmentActivity) {
((EditorFragmentActivity)getActivity()).initializeEditorFragment();
}
mUploadingMediaProgressMax = new HashMap<>();
mFailedMediaIds = new HashSet<>();
title = (AztecText) view.findViewById(R.id.title);
content = (AztecText)view.findViewById(R.id.aztec);
source = (SourceViewEditText) view.findViewById(R.id.source);
source.setHint("<p>" + getString(R.string.editor_content_hint) + "</p>");
formattingToolbar = (AztecToolbar) view.findViewById(R.id.formatting_toolbar);
formattingToolbar.setExpanded(mIsToolbarExpanded);
title.setOnFocusChangeListener(
new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
formattingToolbar.enableFormatButtons(!hasFocus);
}
}
);
content.setOnDragListener(mOnDragListener);
source.setOnDragListener(mOnDragListener);
setHasOptionsMenu(true);
invalidateOptionsHandler = new Handler();
invalidateOptionsRunnable = new Runnable() {
@Override
public void run() {
if (isAdded()) {
getActivity().invalidateOptionsMenu();
}
}
};
content.refreshText();
mAztecReady = true;
AppCompatTextView titleBeta = (AppCompatTextView) view.findViewById(R.id.title_beta);
titleBeta.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mEditorBetaClickListener.onBetaClicked();
}
});
Aztec.Factory.with(content, source, formattingToolbar, this)
.setImageGetter(aztecImageLoader)
.setVideoThumbnailGetter(aztecVideoLoader)
.setOnImeBackListener(this)
.setHistoryListener(this)
.setOnImageTappedListener(this)
.setOnVideoTappedListener(this)
.setOnMediaDeletedListener(this)
.addPlugin(new WordPressCommentsPlugin(content))
.addPlugin(new MoreToolbarButton(content))
.addPlugin(new CaptionShortcodePlugin())
.addPlugin(new VideoShortcodePlugin())
.addPlugin(new AudioShortcodePlugin());
new BlockElementWatcher(content)
.add(new CaptionHandler())
.install(content);
mEditorFragmentListener.onEditorFragmentInitialized();
return view;
}
public void setEditorBetaClickListener(EditorBetaClickListener listener) {
mEditorBetaClickListener = listener;
}
public void setAztecImageLoader(Html.ImageGetter imageLoader) {
this.aztecImageLoader = imageLoader;
}
public void setAztecVideoLoader(Html.VideoThumbnailGetter videoLoader) {
this.aztecVideoLoader = videoLoader;
}
@Override
public void onPause() {
super.onPause();
mEditorWasPaused = true;
mIsKeyboardOpen = false;
}
@Override
public void onResume() {
super.onResume();
// If the editor was previously paused and the current orientation is landscape,
// hide the actionbar because the keyboard is going to appear (even if it was hidden
// prior to being paused).
if (mEditorWasPaused
&& (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
&& !getResources().getBoolean(R.bool.is_large_tablet_landscape)) {
mIsKeyboardOpen = true;
mHideActionBarOnSoftKeyboardUp = true;
hideActionBarIfNeeded();
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mEditorDragAndDropListener = (EditorDragAndDropListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement EditorDragAndDropListener");
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putCharSequence(ATTR_TITLE, getTitle());
outState.putCharSequence(ATTR_CONTENT, getContent());
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_aztec, menu);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
// TODO: disable undo/redo in media mode
boolean canRedo = content.history.redoValid();
boolean canUndo = content.history.undoValid();
if (menu != null && menu.findItem(R.id.redo) != null) {
menu.findItem(R.id.redo).setEnabled(canRedo);
}
if (menu != null && menu.findItem(R.id.undo) != null) {
menu.findItem(R.id.undo).setEnabled(canUndo);
}
super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.undo) {
if (content.getVisibility() == View.VISIBLE) {
content.undo();
mEditorFragmentListener.onUndoMediaCheck(content.toHtml(false));
} else {
source.undo();
}
return true;
} else if (item.getItemId() == R.id.redo) {
if (content.getVisibility() == View.VISIBLE) {
content.redo();
} else {
source.redo();
}
return true;
}
return false;
}
@Override
public void onRedoEnabled() {
invalidateOptionsHandler.removeCallbacks(invalidateOptionsRunnable);
invalidateOptionsHandler.postDelayed(invalidateOptionsRunnable, getResources().getInteger(android.R.integer.config_mediumAnimTime) );
}
@Override
public void onUndoEnabled() {
invalidateOptionsHandler.removeCallbacks(invalidateOptionsRunnable);
invalidateOptionsHandler.postDelayed(invalidateOptionsRunnable, getResources().getInteger(android.R.integer.config_mediumAnimTime) );
}
private ActionBar getActionBar() {
if (!isAdded()) {
return null;
}
if (getActivity() instanceof AppCompatActivity) {
return ((AppCompatActivity) getActivity()).getSupportActionBar();
} else {
return null;
}
}
/**
* Intercept back button press while soft keyboard is visible.
*/
@Override
public void onImeBack() {
mIsKeyboardOpen = false;
showActionBarIfNeeded();
}
@Override
public void setTitle(CharSequence text) {
title.setText(text);
}
@Override
public void setContent(CharSequence text) {
content.fromHtml(text.toString());
updateFailedMediaList();
overlayFailedMedia();
updateUploadingMediaList();
overlayProgressingMedia();
mAztecReady = true;
}
/**
* Returns the contents of the title field from the JavaScript editor. Should be called from a background thread
* where possible.
*/
@Override
public CharSequence getTitle() {
if (!isAdded()) {
return "";
}
// TODO: Aztec returns a ZeroWidthJoiner when empty so, strip it. Aztec needs fixing to return empty string.
return StringUtils.notNullStr(title.getText().toString().replaceAll(" $", "").replaceAll("\u200B", ""));
}
@Override
public void onToolbarCollapseButtonClicked() {
mEditorFragmentListener.onTrackableEvent(TrackableEvent.ELLIPSIS_COLLAPSE_BUTTON_TAPPED);
}
@Override
public void onToolbarExpandButtonClicked() {
mEditorFragmentListener.onTrackableEvent(TrackableEvent.ELLIPSIS_EXPAND_BUTTON_TAPPED);
}
@Override
public void onToolbarFormatButtonClicked(ITextFormat format, boolean isKeyboardShortcut) {
if (format.equals(AztecTextFormat.FORMAT_PARAGRAPH)) {
mEditorFragmentListener.onTrackableEvent(TrackableEvent.PARAGRAPH_BUTTON_TAPPED);
} else if (format.equals(AztecTextFormat.FORMAT_PREFORMAT)) {
mEditorFragmentListener.onTrackableEvent(TrackableEvent.PREFORMAT_BUTTON_TAPPED);
} else if (format.equals(AztecTextFormat.FORMAT_HEADING_1)) {
mEditorFragmentListener.onTrackableEvent(TrackableEvent.HEADING_1_BUTTON_TAPPED);
} else if (format.equals(AztecTextFormat.FORMAT_HEADING_2)) {
mEditorFragmentListener.onTrackableEvent(TrackableEvent.HEADING_2_BUTTON_TAPPED);
} else if (format.equals(AztecTextFormat.FORMAT_HEADING_3)) {
mEditorFragmentListener.onTrackableEvent(TrackableEvent.HEADING_3_BUTTON_TAPPED);
} else if (format.equals(AztecTextFormat.FORMAT_HEADING_4)) {
mEditorFragmentListener.onTrackableEvent(TrackableEvent.HEADING_4_BUTTON_TAPPED);
} else if (format.equals(AztecTextFormat.FORMAT_HEADING_5)) {
mEditorFragmentListener.onTrackableEvent(TrackableEvent.HEADING_5_BUTTON_TAPPED);
} else if (format.equals(AztecTextFormat.FORMAT_HEADING_6)) {
mEditorFragmentListener.onTrackableEvent(TrackableEvent.HEADING_6_BUTTON_TAPPED);
} else if (format.equals(AztecTextFormat.FORMAT_ORDERED_LIST)) {
mEditorFragmentListener.onTrackableEvent(TrackableEvent.LIST_ORDERED_BUTTON_TAPPED);
} else if (format.equals(AztecTextFormat.FORMAT_UNORDERED_LIST)) {
mEditorFragmentListener.onTrackableEvent(TrackableEvent.LIST_UNORDERED_BUTTON_TAPPED);
} else if (format.equals(AztecTextFormat.FORMAT_BOLD)) {
mEditorFragmentListener.onTrackableEvent(TrackableEvent.BOLD_BUTTON_TAPPED);
} else if (format.equals(AztecTextFormat.FORMAT_ITALIC)) {
mEditorFragmentListener.onTrackableEvent(TrackableEvent.ITALIC_BUTTON_TAPPED);
} else if (format.equals(AztecTextFormat.FORMAT_STRIKETHROUGH)) {
mEditorFragmentListener.onTrackableEvent(TrackableEvent.STRIKETHROUGH_BUTTON_TAPPED);
} else if (format.equals(AztecTextFormat.FORMAT_UNDERLINE)) {
mEditorFragmentListener.onTrackableEvent(TrackableEvent.UNDERLINE_BUTTON_TAPPED);
} else if (format.equals(AztecTextFormat.FORMAT_QUOTE)) {
mEditorFragmentListener.onTrackableEvent(TrackableEvent.BLOCKQUOTE_BUTTON_TAPPED);
} else if (format.equals(AztecTextFormat.FORMAT_LINK)) {
mEditorFragmentListener.onTrackableEvent(TrackableEvent.LINK_ADDED_BUTTON_TAPPED);
} else if (format.equals(CommentsTextFormat.FORMAT_MORE)) {
mEditorFragmentListener.onTrackableEvent(TrackableEvent.READ_MORE_BUTTON_TAPPED);
} else if (format.equals(CommentsTextFormat.FORMAT_PAGE)) {
mEditorFragmentListener.onTrackableEvent(TrackableEvent.NEXT_PAGE_BUTTON_TAPPED);
}
}
@Override
public void onToolbarHeadingButtonClicked() {
mEditorFragmentListener.onTrackableEvent(TrackableEvent.HEADING_BUTTON_TAPPED);
}
@Override
public void onToolbarHtmlButtonClicked() {
if (!isAdded()) {
return;
}
checkForFailedUploadAndSwitchToHtmlMode();
}
@Override
public void onToolbarListButtonClicked() {
mEditorFragmentListener.onTrackableEvent(TrackableEvent.LIST_BUTTON_TAPPED);
}
private void checkForFailedUploadAndSwitchToHtmlMode() {
// Show an Alert Dialog asking the user if he wants to remove all failed media before upload
if (hasFailedMediaUploads()) {
new AlertDialog.Builder(getActivity())
.setMessage(R.string.editor_failed_uploads_switch_html)
.setPositiveButton(R.string.editor_remove_failed_uploads, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Clear failed uploads and switch to HTML mode
removeAllFailedMediaUploads();
toggleHtmlMode();
}
}).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// nothing special to do
}
})
.create()
.show();
} else {
toggleHtmlMode();
}
}
private void toggleHtmlMode() {
mEditorFragmentListener.onTrackableEvent(TrackableEvent.HTML_BUTTON_TAPPED);
// Don't switch to HTML mode if currently uploading media
if (!mUploadingMediaProgressMax.isEmpty() || isActionInProgress()) {
ToastUtils.showToast(getActivity(), R.string.alert_action_while_uploading, ToastUtils.Duration.LONG);
return;
}
formattingToolbar.toggleEditorMode();
if (source.getVisibility() == View.VISIBLE) {
updateFailedMediaList();
}
}
public void enableMediaMode(boolean enable) {
formattingToolbar.enableMediaMode(enable);
getActivity().invalidateOptionsMenu();
}
@Override
public boolean isActionInProgress() {
return System.currentTimeMillis() - mActionStartedAt < MAX_ACTION_TIME_MS;
}
private void updateUploadingMediaList() {
AztecText.AttributePredicate uploadingPredicate = getPredicateWithClass(ATTR_STATUS_UPLOADING);
mUploadingMediaProgressMax.clear();
// update all items with upload progress of zero
for (Attributes attrs : content.getAllElementAttributes(uploadingPredicate)) {
String localMediaId = attrs.getValue(ATTR_ID_WP);
if (!TextUtils.isEmpty(localMediaId)) {
mUploadingMediaProgressMax.put(localMediaId, 0f);
}
}
}
private void safeAddMediaIdToSet(Set<String> setToAddTo, String wpId){
if (!TextUtils.isEmpty(wpId)) {
setToAddTo.add(wpId);
}
}
static private AztecText.AttributePredicate getPredicateWithClass(final String classToUse) {
AztecText.AttributePredicate predicate = new AztecText.AttributePredicate() {
@Override
public boolean matches(@NonNull Attributes attrs) {
AttributesWithClass attributesWithClass = new AttributesWithClass(attrs);
return attributesWithClass.hasClass(classToUse);
}
};
return predicate;
}
private void updateFailedMediaList() {
AztecText.AttributePredicate failedPredicate = getPredicateWithClass(ATTR_STATUS_FAILED);
mFailedMediaIds.clear();
for (Attributes attrs : content.getAllElementAttributes(failedPredicate)) {
String localMediaId = attrs.getValue(ATTR_ID_WP);
safeAddMediaIdToSet(mFailedMediaIds, localMediaId);
}
}
private void overlayProgressingMedia() {
for (String localMediaId : mUploadingMediaProgressMax.keySet()) {
MediaPredicate predicate = MediaPredicate.getLocalMediaIdPredicate(localMediaId);
overlayProgressingMedia(predicate);
// here check if this is a video uploading in progress or not; if it is, show the video play icon
for (Attributes attrs : content.getAllElementAttributes(predicate)) {
AttributesWithClass attributesWithClass = new AttributesWithClass(attrs);
if (attributesWithClass.hasClass(TEMP_VIDEO_UPLOADING_CLASS)) {
overlayVideoIcon(2, predicate);
}
}
}
}
private void overlayVideoIcon(int overlayLevel, AztecText.AttributePredicate predicate) {
Drawable videoDrawable = getResources().getDrawable(R.drawable.ic_overlay_video);
content.setOverlay(predicate, overlayLevel, videoDrawable, Gravity.BOTTOM | Gravity.START);
}
private void overlayProgressingMedia(MediaPredicate predicate) {
// set intermediate shade overlay
content.setOverlay(predicate, 0,
new ColorDrawable(getResources().getColor(R.color.media_shade_overlay_color)),
Gravity.FILL);
Drawable progressDrawable = getResources().getDrawable(android.R.drawable.progress_horizontal);
// set the height of the progress bar to 2 (it's in dp since the drawable will be adjusted by the span)
progressDrawable.setBounds(0, 0, 0, 4);
content.setOverlay(predicate, 1, progressDrawable,
Gravity.FILL_HORIZONTAL | Gravity.TOP);
content.resetAttributedMediaSpan(predicate);
}
private void overlayFailedMedia() {
for (String localMediaId : mFailedMediaIds) {
Attributes attributes = content.getElementAttributes(MediaPredicate.getLocalMediaIdPredicate(localMediaId));
overlayFailedMedia(localMediaId, attributes);
}
}
private void overlayFailedMedia(String localMediaId, Attributes attributes) {
// set intermediate shade overlay
AztecText.AttributePredicate localMediaIdPredicate = MediaPredicate.getLocalMediaIdPredicate(localMediaId);
content.setOverlay(localMediaIdPredicate, 0,
new ColorDrawable(getResources().getColor(R.color.media_shade_overlay_error_color)),
Gravity.FILL);
Drawable alertDrawable = getResources().getDrawable(R.drawable.media_retry_image);
content.setOverlay(localMediaIdPredicate, 1, alertDrawable, Gravity.CENTER);
content.updateElementAttributes(localMediaIdPredicate, new AztecAttributes(attributes));
}
/**
* Returns the contents of the content field from the JavaScript editor. Should be called from a background thread
* where possible.
*/
@Override
public CharSequence getContent() {
if (!isAdded()) {
return "";
}
if (content.getVisibility() == View.VISIBLE) {
return content.toHtml(false);
} else {
return source.getPureHtml(false);
}
}
@Override
public void appendMediaFile(final MediaFile mediaFile, final String mediaUrl, ImageLoader imageLoader) {
// load a scaled version of the image to prevent OOM exception
final int maxWidth = ImageUtils.getMaximumThumbnailWidthForEditor(getActivity());
if (URLUtil.isNetworkUrl(mediaUrl)) {
// We're download the image/video from the network. Show the placeholder immediately since it could require time.
final Drawable placeholder;
if(mediaFile.isVideo()) {
placeholder = getResources().getDrawable(R.drawable.ic_gridicons_video_camera);
} else {
placeholder = getResources().getDrawable(R.drawable.ic_gridicons_image);
}
placeholder.setBounds(0, 0, DEFAULT_MEDIA_PLACEHOLDER_DIMENSION_DP, DEFAULT_MEDIA_PLACEHOLDER_DIMENSION_DP);
AztecAttributes attributes = new AztecAttributes();
attributes.setValue(ATTR_SRC, mediaUrl);
setAttributeValuesIfNotDefault(attributes, mediaFile);
if(mediaFile.isVideo()) {
addVideoUploadingClassIfMissing(attributes);
content.insertVideo(placeholder, attributes);
overlayVideoIcon(0, new MediaPredicate(mediaUrl, ATTR_SRC));
} else {
content.insertImage(placeholder, attributes);
}
final String posterURL = mediaFile.isVideo() ? Utils.escapeQuotes(StringUtils.notNullStr(mediaFile.getThumbnailURL())) : mediaUrl;
imageLoader.get(posterURL, new ImageLoader.ImageListener() {
private void replaceDrawable(Drawable newDrawable){
AztecMediaSpan[] imageOrVideoSpans = content.getText().getSpans(0, content.getText().length(), AztecMediaSpan.class);
for (AztecMediaSpan currentClass: imageOrVideoSpans) {
if (currentClass.getAttributes().hasAttribute(ATTR_SRC) &&
mediaUrl.equals(currentClass.getAttributes().getValue(ATTR_SRC))) {
currentClass.setDrawable(newDrawable);
}
}
content.refreshText();
}
private void showErrorPlaceholder() {
// Show failed placeholder.
ToastUtils.showToast(getActivity(), R.string.error_media_load);
Drawable drawable = getResources().getDrawable(R.drawable.ic_image_failed_grey_a_40_48dp);
replaceDrawable(drawable);
}
@Override
public void onErrorResponse(VolleyError error) {
if (!isAdded()) {
// the fragment is detached
return;
}
showErrorPlaceholder();
}
@Override
public void onResponse(ImageLoader.ImageContainer container, boolean isImmediate) {
if (!isAdded()) {
// the fragment is detached
return;
}
Bitmap downloadedBitmap = container.getBitmap();
if (downloadedBitmap == null) {
if (isImmediate) {
// Bitmap is null but isImmediate is true (as soon as the request starts).
return;
}
showErrorPlaceholder();
return;
}
AztecAttributes attributes = new AztecAttributes();
attributes.setValue(ATTR_SRC, mediaUrl);
setAttributeValuesIfNotDefault(attributes, mediaFile);
int minimumDimension = DisplayUtils.dpToPx(getActivity(), MIN_BITMAP_DIMENSION_DP);
if (downloadedBitmap.getHeight() < minimumDimension || downloadedBitmap.getWidth() < minimumDimension) {
// Bitmap is too small. Show image placeholder.
ToastUtils.showToast(getActivity(), R.string.error_media_small);
Drawable drawable = getResources().getDrawable(R.drawable.ic_image_loading_grey_a_40_48dp);
replaceDrawable(drawable);
return;
}
Bitmap resizedBitmap = ImageUtils.getScaledBitmapAtLongestSide(downloadedBitmap, maxWidth);
replaceDrawable(new BitmapDrawable(getResources(), resizedBitmap));
}
}, maxWidth, 0);
mActionStartedAt = System.currentTimeMillis();
} else {
String localMediaId = String.valueOf(mediaFile.getId());
final String safeMediaPreviewUrl = mediaFile.isVideo() ?
Utils.escapeQuotes(StringUtils.notNullStr(mediaFile.getThumbnailURL())) :
Utils.escapeQuotes(mediaUrl);
AztecAttributes attrs = new AztecAttributes();
attrs.setValue(ATTR_ID_WP, localMediaId);
attrs.setValue(ATTR_SRC, Utils.escapeQuotes(mediaUrl));
attrs.setValue(ATTR_CLASS, ATTR_STATUS_UPLOADING);
addDefaultSizeClassIfMissing(attrs);
Bitmap bitmapToShow = ImageUtils.getWPImageSpanThumbnailFromFilePath(getActivity(), safeMediaPreviewUrl, maxWidth);
MediaPredicate localMediaIdPredicate = MediaPredicate.getLocalMediaIdPredicate(localMediaId);
if (bitmapToShow != null) {
if(mediaFile.isVideo()) {
addVideoUploadingClassIfMissing(attrs);
content.insertVideo(new BitmapDrawable(getResources(), bitmapToShow), attrs);
} else {
content.insertImage(new BitmapDrawable(getResources(), bitmapToShow), attrs);
}
} else {
// Failed to retrieve bitmap. Show failed placeholder.
ToastUtils.showToast(getActivity(), R.string.error_media_load);
Drawable drawable = getResources().getDrawable(R.drawable.ic_image_failed_grey_a_40_48dp);
drawable.setBounds(0, 0, maxWidth, maxWidth);
content.insertImage(drawable, attrs);
}
// set intermediate shade overlay
overlayProgressingMedia(localMediaIdPredicate);
mUploadingMediaProgressMax.put(localMediaId, 0f);
if (mediaFile.isVideo()) {
overlayVideoIcon(2, localMediaIdPredicate);
}
content.updateElementAttributes(localMediaIdPredicate, attrs);
content.resetAttributedMediaSpan(localMediaIdPredicate);
}
}
@Override
public void appendGallery(MediaGallery mediaGallery) {
ToastUtils.showToast(getActivity(), R.string.media_insert_unimplemented);
}
@Override
public void setUrlForVideoPressId(final String videoId, final String videoUrl, final String posterUrl) {
}
@Override
public boolean isUploadingMedia() {
return (mUploadingMediaProgressMax.size() > 0);
}
@Override
public boolean hasFailedMediaUploads() {
return (mFailedMediaIds.size() > 0);
}
@Override
public void removeAllFailedMediaUploads() {
content.removeMedia(new AztecText.AttributePredicate() {
@Override
public boolean matches(@NotNull Attributes attrs) {
return new AttributesWithClass(attrs).hasClass(ATTR_STATUS_FAILED);
}
});
mFailedMediaIds.clear();
}
@Override
public Spanned getSpannedContent() {
return null;
}
@Override
public void setTitlePlaceholder(CharSequence placeholderText) {
}
@Override
public void setContentPlaceholder(CharSequence placeholderText) {
}
@Override
public void onMediaUploadReattached(String localId, float currentProgress) {
mUploadingMediaProgressMax.put(localId, currentProgress);
}
@Override
public void onMediaUploadSucceeded(final String localMediaId, final MediaFile mediaFile) {
if(!isAdded() || content == null || !mAztecReady) {
return;
}
if (mediaFile != null) {
String remoteUrl = Utils.escapeQuotes(mediaFile.getFileURL());
// we still need to refresh the screen visually, no matter whether the service already
// saved the post to Db or not
MediaType mediaType = EditorFragmentAbstract.getEditorMimeType(mediaFile);
if (mediaType.equals(MediaType.IMAGE) || mediaType.equals(MediaType.VIDEO)) {
// clear overlay
MediaPredicate predicate = MediaPredicate.getLocalMediaIdPredicate(localMediaId);
// remove the uploading class
AttributesWithClass attributesWithClass = new AttributesWithClass(
content.getElementAttributes(predicate));
attributesWithClass.removeClass(ATTR_STATUS_UPLOADING);
if (mediaFile.isVideo()) {
attributesWithClass.removeClass(TEMP_VIDEO_UPLOADING_CLASS);
}
// add then new src property with the remoteUrl
AztecAttributes attrs = attributesWithClass.getAttributes();
attrs.setValue("src", remoteUrl);
/* TODO add video press attribute -> value here
if (mediaType.equals(MediaType.VIDEO)) {
String videoPressId = ShortcodeUtils.getVideoPressIdFromShortCode(
mediaFile.getVideoPressShortCode());
attrs.setValue( ?? , videoPressId);
}
*/
addDefaultSizeClassIfMissing(attrs);
// clear overlay
content.clearOverlays(predicate);
if (mediaType.equals(MediaType.VIDEO)) {
overlayVideoIcon(0, predicate);
}
content.updateElementAttributes(predicate, attrs);
content.resetAttributedMediaSpan(predicate);
mUploadingMediaProgressMax.remove(localMediaId);
}
}
}
@Override
public void onMediaDeleted(AztecAttributes aztecAttributes) {
String localMediaId = aztecAttributes.getValue(ATTR_ID_WP);
if (!TextUtils.isEmpty(localMediaId)) {
mEditorFragmentListener.onMediaDeleted(localMediaId);
}
}
private static class MediaPredicate implements AztecText.AttributePredicate {
private final String mId;
private final String mAttributeName;
static MediaPredicate getLocalMediaIdPredicate(String id) {
return new MediaPredicate(id, ATTR_ID_WP);
}
static MediaPredicate getTempMediaIdPredicate(String id) {
return new MediaPredicate(id, TEMP_IMAGE_ID);
}
MediaPredicate(String id, String attributeName) {
mId = id;
mAttributeName = attributeName;
}
@Override
public boolean matches(@NotNull Attributes attrs) {
return attrs.getIndex(mAttributeName) > -1 && attrs.getValue(mAttributeName).equals(mId);
}
}
@Override
public void onMediaUploadProgress(final String localMediaId, final float progress) {
if(!isAdded() || content == null || !mAztecReady || TextUtils.isEmpty(localMediaId)) {
return;
}
// check a previous maximum for this localMediaId exists
// if there is not, we've probably already gotten the upload fail/success signal, thus
// we already removed this id from the array. Nothing left to do, disregard this event.
if (mUploadingMediaProgressMax.get(localMediaId) == null) {
return;
}
// first obtain the latest maximum
float maxProgressForLocalMediaId = mUploadingMediaProgressMax.get(localMediaId);
// only update if the new progress value is greater than the latest maximum reflected on the
// screen
if (progress > maxProgressForLocalMediaId) {
synchronized (AztecEditorFragment.this) {
maxProgressForLocalMediaId = progress;
mUploadingMediaProgressMax.put(localMediaId, maxProgressForLocalMediaId);
try {
AztecText.AttributePredicate localMediaIdPredicate = MediaPredicate.getLocalMediaIdPredicate(localMediaId);
content.setOverlayLevel(localMediaIdPredicate, 1, (int) (progress * 10000));
content.resetAttributedMediaSpan(localMediaIdPredicate);
} catch (IndexOutOfBoundsException ex) {
/*
* it could happen that the localMediaId is not found, because FluxC events are not
* guaranteed to be received in order, so we might have received the `upload
* finished` event (thus clearing the id from within the Post html), and then
* still receive some more progress events for the same file, which we can't
* avoid but disregard.
* ex.printStackTrace();
*/
AppLog.d(AppLog.T.EDITOR, localMediaId + " - not found trying to update progress ");
}
}
}
}
@Override
public void onMediaUploadFailed(final String localMediaId, final EditorFragmentAbstract.MediaType
mediaType, final String errorMessage) {
if(!isAdded() || content == null) {
return;
}
if (mediaType != null) {
switch (mediaType) {
case IMAGE:
case VIDEO:
MediaPredicate localMediaIdPredicate = MediaPredicate.getLocalMediaIdPredicate(localMediaId);
AttributesWithClass attributesWithClass = new AttributesWithClass(
content.getElementAttributes(localMediaIdPredicate));
attributesWithClass.removeClass(ATTR_STATUS_UPLOADING);
attributesWithClass.addClass(ATTR_STATUS_FAILED);
content.clearOverlays(localMediaIdPredicate);
overlayFailedMedia(localMediaId, attributesWithClass.getAttributes());
content.resetAttributedMediaSpan(localMediaIdPredicate);
break;
}
mFailedMediaIds.add(localMediaId);
mUploadingMediaProgressMax.remove(localMediaId);
}
}
@Override
public void onGalleryMediaUploadSucceeded(final long galleryId, long remoteMediaId, int remaining) {
}
/**
* Hide the action bar if needed.
*/
private void hideActionBarIfNeeded() {
ActionBar actionBar = getActionBar();
if (actionBar != null
&& !isHardwareKeyboardPresent()
&& mHideActionBarOnSoftKeyboardUp
&& mIsKeyboardOpen
&& actionBar.isShowing()) {
getActionBar().hide();
}
}
/**
* Show the action bar if needed.
*/
private void showActionBarIfNeeded() {