-
Notifications
You must be signed in to change notification settings - Fork 4k
/
WPAndroidGlueCode.java
1177 lines (1011 loc) · 53.1 KB
/
WPAndroidGlueCode.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.mobile.WPAndroidGlue;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.MutableContextWrapper;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout.LayoutParams;
import androidx.annotation.Nullable;
import androidx.core.util.Consumer;
import androidx.core.util.Pair;
import androidx.fragment.app.Fragment;
import com.BV.LinearGradient.LinearGradientPackage;
import com.brentvatne.react.ReactVideoPackage;
import com.dylanvann.fastimage.FastImageViewPackage;
import com.facebook.hermes.reactexecutor.HermesExecutorFactory;
import com.facebook.imagepipeline.backends.okhttp3.OkHttpImagePipelineConfigFactory;
import com.facebook.imagepipeline.core.ImagePipelineConfig;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactInstanceManagerBuilder;
import com.facebook.react.ReactPackage;
import com.facebook.react.ReactRootView;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableMapKeySetIterator;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.common.LifecycleState;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.shell.MainPackageConfig;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import com.horcrux.svg.SvgPackage;
import com.reactnativecommunity.clipboard.ClipboardPackage;
import com.reactnativecommunity.slider.ReactSliderPackage;
import com.reactnativecommunity.webview.RNCWebViewPackage;
import com.swmansion.gesturehandler.RNGestureHandlerPackage;
import com.swmansion.reanimated.ReanimatedPackage;
import com.swmansion.rnscreens.RNScreensPackage;
import com.th3rdwave.safeareacontext.SafeAreaContextPackage;
import org.linusu.RNGetRandomValuesPackage;
import org.reactnative.maskedview.RNCMaskedViewPackage;
import org.wordpress.android.util.AppLog;
import org.wordpress.android.util.AppLog.T;
import org.wordpress.mobile.ReactNativeAztec.ReactAztecPackage;
import org.wordpress.mobile.ReactNativeGutenbergBridge.BuildConfig;
import org.wordpress.mobile.ReactNativeGutenbergBridge.GutenbergBridgeJS2Parent;
import org.wordpress.mobile.ReactNativeGutenbergBridge.GutenbergBridgeJS2Parent.LogExceptionCallback;
import org.wordpress.mobile.ReactNativeGutenbergBridge.GutenbergBridgeJS2Parent.MediaSelectedCallback;
import org.wordpress.mobile.ReactNativeGutenbergBridge.GutenbergBridgeJS2Parent.ReplaceUnsupportedBlockCallback;
import org.wordpress.mobile.ReactNativeGutenbergBridge.RNMedia;
import org.wordpress.mobile.ReactNativeGutenbergBridge.RNReactNativeGutenbergBridgePackage;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
public class WPAndroidGlueCode {
private ReactRootView mReactRootView;
private ReactInstanceManager mReactInstanceManager;
private ReactContext mReactContext;
private RNReactNativeGutenbergBridgePackage mRnReactNativeGutenbergBridgePackage;
private MediaSelectedCallback mMediaSelectedCallback;
private DeferredEventEmitter mDeferredEventEmitter = new DeferredEventEmitter();
private boolean mMediaPickedByUserOnBlock;
/**
* Flag to append as siblings when allowMultipleSelection = false is not respected
*/
private boolean mAppendsMultipleSelectedToSiblingBlocks = false;
private OnMediaLibraryButtonListener mOnMediaLibraryButtonListener;
private OnReattachMediaUploadQueryListener mOnReattachMediaUploadQueryListener;
private OnSetFeaturedImageListener mOnSetFeaturedImageListener;
private OnEditorMountListener mOnEditorMountListener;
private OnEditorAutosaveListener mOnEditorAutosaveListener;
private OnImageFullscreenPreviewListener mOnImageFullscreenPreviewListener;
private OnMediaEditorListener mOnMediaEditorListener;
private OnGutenbergDidRequestUnsupportedBlockFallbackListener mOnGutenbergDidRequestUnsupportedBlockFallbackListener;
private OnGutenbergDidRequestEmbedFullscreenPreviewListener mOnGutenbergDidRequestEmbedFullscreenPreviewListener;
private OnGutenbergDidSendButtonPressedActionListener mOnGutenbergDidSendButtonPressedActionListener;
private ReplaceUnsupportedBlockCallback mReplaceUnsupportedBlockCallback;
private OnFocalPointPickerTooltipShownEventListener mOnFocalPointPickerTooltipShownListener;
private OnGutenbergDidRequestPreviewListener mOnGutenbergDidRequestPreviewListener;
private OnBlockTypeImpressionsEventListener mOnBlockTypeImpressionsEventListener;
private OnCustomerSupportOptionsListener mOnCustomerSupportOptionsListener;
private OnSendEventToHostListener mOnSendEventToHostListener;
private OnToggleUndoButtonListener mOnToggleUndoButtonListener;
private OnToggleRedoButtonListener mOnToggleRedoButtonListener;
private OnConnectionStatusEventListener mOnConnectionStatusEventListener;
private OnBackHandlerEventListener mOnBackHandlerEventListener;
private OnLogExceptionListener mOnLogExceptionListener;
private boolean mIsEditorMounted;
private String mContentHtml = "";
private boolean mContentInitialized;
private HashMap<Integer, Media> mMediaToAddAfterMounting = new HashMap<>();
private String mTitle = "";
private boolean mTitleInitialized;
private boolean mContentChanged;
private ReadableMap mContentInfo;
private boolean mShouldUpdateContent;
private CountDownLatch mGetContentCountDownLatch;
private WeakReference<View> mLastFocusedView = null;
private RequestExecutor mRequestExecutor;
private ShowSuggestionsUtil mShowSuggestionsUtil;
private @Nullable Bundle mEditorTheme = null;
private static OkHttpHeaderInterceptor sAddCookiesInterceptor = new OkHttpHeaderInterceptor();
private static OkHttpClient sOkHttpClient = new OkHttpClient.Builder().addInterceptor(sAddCookiesInterceptor).build();
private boolean mIsDarkMode;
private Consumer<Exception> mExceptionLogger;
private Consumer<String> mBreadcrumbLogger;
private boolean mShouldHandleBackPress = false;
public void onCreate(Context context) {
SoLoader.init(context, /* native exopackage */ false);
}
public boolean hasReactRootView() {
return mReactRootView != null;
}
public boolean hasReactContext() {
return mReactContext != null;
}
public boolean shouldHandleBackPress() {
return mShouldHandleBackPress;
}
public boolean isContentChanged() {
return mContentChanged;
}
public interface OnMediaLibraryButtonListener {
void onMediaLibraryImageButtonClicked(boolean allowMultipleSelection);
void onMediaLibraryVideoButtonClicked(boolean allowMultipleSelection);
void onMediaLibraryMediaButtonClicked(boolean allowMultipleSelection);
void onMediaLibraryFileButtonClicked(boolean allowMultipleSelection);
void onMediaLibraryAudioButtonClicked(boolean allowMultipleSelection);
void onUploadPhotoButtonClicked(boolean allowMultipleSelection);
void onCapturePhotoButtonClicked();
void onUploadVideoButtonClicked(boolean allowMultipleSelection);
void onUploadMediaButtonClicked(boolean allowMultipleSelection);
void onCaptureVideoButtonClicked();
void onRetryUploadForMediaClicked(int mediaId);
void onCancelUploadForMediaClicked(int mediaId);
void onCancelUploadForMediaDueToDeletedBlock(int mediaId);
ArrayList<MediaOption> onGetOtherMediaImageOptions();
ArrayList<MediaOption> onGetOtherMediaFileOptions();
ArrayList<MediaOption> onGetOtherMediaAudioFileOptions();
void onOtherMediaButtonClicked(String mediaSource, boolean allowMultipleSelection);
}
public interface OnImageFullscreenPreviewListener {
void onImageFullscreenPreviewClicked(String mediaUrl);
}
public interface OnReattachMediaUploadQueryListener {
void onQueryCurrentProgressForUploadingMedia();
}
public interface OnSetFeaturedImageListener {
void onSetFeaturedImageButtonClicked(int mediaId);
}
public interface OnEditorMountListener {
void onEditorDidMount(ArrayList<Object> unsupportedBlockNames);
}
public interface OnAuthHeaderRequestedListener {
Map<String, String> onAuthHeaderRequested(String url);
}
public interface OnEditorAutosaveListener {
void onEditorAutosave();
}
public interface OnMediaEditorListener {
void onMediaEditorClicked(String mediaUrl);
}
public interface OnGutenbergDidRequestUnsupportedBlockFallbackListener {
void gutenbergDidRequestUnsupportedBlockFallback(UnsupportedBlock unsupportedBlock);
}
public interface OnGutenbergDidRequestEmbedFullscreenPreviewListener {
void gutenbergDidRequestEmbedFullscreenPreview(String html, String title);
}
public interface OnGutenbergDidSendButtonPressedActionListener {
void gutenbergDidSendButtonPressedAction(String buttonType);
}
public interface OnFocalPointPickerTooltipShownEventListener {
void onSetFocalPointPickerTooltipShown(boolean tooltipShown);
boolean onRequestFocalPointPickerTooltipShown();
}
public interface OnContentInfoReceivedListener {
void onContentInfoFailed();
void onEditorNotReady();
void onContentInfoReceived(HashMap<String, Object> contentInfo);
}
public interface OnGutenbergDidRequestPreviewListener {
void gutenbergDidRequestPreview();
}
public interface OnBlockTypeImpressionsEventListener {
void onSetBlockTypeImpressions(Map<String, Double> impressions);
Map<String, Double> onRequestBlockTypeImpressions();
}
public interface OnCustomerSupportOptionsListener {
void onContactCustomerSupport();
void onGotoCustomerSupportOptions();
}
public interface OnSendEventToHostListener {
void onSendEventToHost(String eventName, Map<String, Object> properties);
}
public interface OnToggleUndoButtonListener {
void onToggleUndoButton(boolean isDisabled);
}
public interface OnToggleRedoButtonListener {
void onToggleRedoButton(boolean isDisabled);
}
public interface OnConnectionStatusEventListener {
boolean onRequestConnectionStatus();
}
public interface OnBackHandlerEventListener {
void onBackHandler();
}
public interface OnLogExceptionListener {
void onLogException(GutenbergJsException exception, LogExceptionCallback logExceptionCallback);
}
public void mediaSelectionCancelled() {
mAppendsMultipleSelectedToSiblingBlocks = false;
}
protected List<ReactPackage> getPackages() {
mRnReactNativeGutenbergBridgePackage = new RNReactNativeGutenbergBridgePackage(new GutenbergBridgeJS2Parent() {
@Override
public void responseHtml(String title, String html, boolean changed, ReadableMap contentInfo) {
mContentHtml = html;
mTitle = title;
// This code is called twice. When getTitle and getContent are called.
// Make sure mContentChanged has the correct value (true) if one of the call returned with changes.
mContentChanged = mContentChanged || changed;
mContentInfo = contentInfo;
// Gutenberg mobile sends us html response even without we asking for it so, check if the latch is there.
// This is probably an indication of a bug on the RN side of things though.
// Related: https://github.com/WordPress/gutenberg/pull/16260#issuecomment-506727286
if (mGetContentCountDownLatch != null) {
mGetContentCountDownLatch.countDown();
}
}
@Override
public void requestMediaPickFromMediaLibrary(MediaSelectedCallback mediaSelectedCallback, Boolean allowMultipleSelection, MediaType mediaType) {
mMediaPickedByUserOnBlock = true;
mAppendsMultipleSelectedToSiblingBlocks = !allowMultipleSelection;
mMediaSelectedCallback = mediaSelectedCallback;
switch (mediaType) {
case IMAGE:
mOnMediaLibraryButtonListener.onMediaLibraryImageButtonClicked(allowMultipleSelection);
break;
case VIDEO:
mOnMediaLibraryButtonListener.onMediaLibraryVideoButtonClicked(allowMultipleSelection);
break;
case MEDIA:
mOnMediaLibraryButtonListener.onMediaLibraryMediaButtonClicked(allowMultipleSelection);
break;
case AUDIO:
mOnMediaLibraryButtonListener.onMediaLibraryAudioButtonClicked(allowMultipleSelection);
break;
case ANY:
mOnMediaLibraryButtonListener.onMediaLibraryFileButtonClicked(allowMultipleSelection);
break;
case OTHER:
break;
}
}
@Override
public void requestMediaPickFromDeviceLibrary(MediaSelectedCallback mediaSelectedCallback, Boolean allowMultipleSelection, MediaType mediaType) {
mMediaPickedByUserOnBlock = true;
// image blocks do not respect the multiple selection flag, so we set the append as siblings flag instead
mAppendsMultipleSelectedToSiblingBlocks = mediaType == MediaType.IMAGE && !allowMultipleSelection;
mMediaSelectedCallback = mediaSelectedCallback;
if (mediaType == MediaType.IMAGE) {
mOnMediaLibraryButtonListener.onUploadPhotoButtonClicked(true);
} else if (mediaType == MediaType.VIDEO) {
mOnMediaLibraryButtonListener.onUploadVideoButtonClicked(allowMultipleSelection);
} else if (mediaType == MediaType.MEDIA) {
mOnMediaLibraryButtonListener.onUploadMediaButtonClicked(allowMultipleSelection);
}
}
@Override
public void requestMediaPickerFromDeviceCamera(MediaSelectedCallback mediaSelectedCallback, MediaType mediaType) {
mMediaPickedByUserOnBlock = true;
mAppendsMultipleSelectedToSiblingBlocks = false;
mMediaSelectedCallback = mediaSelectedCallback;
if (mediaType == MediaType.IMAGE) {
mOnMediaLibraryButtonListener.onCapturePhotoButtonClicked();
} else if (mediaType == MediaType.VIDEO) {
mOnMediaLibraryButtonListener.onCaptureVideoButtonClicked();
}
}
@Override
public void requestMediaImport(String url, MediaSelectedCallback mediaSelectedCallback) {
// no op - we don't need to paste images on Android, but the method needs to exist
// to match the iOS counterpart
}
@Override
public void mediaUploadSync(MediaSelectedCallback mediaSelectedCallback) {
mMediaSelectedCallback = mediaSelectedCallback;
mOnReattachMediaUploadQueryListener.onQueryCurrentProgressForUploadingMedia();
}
@Override
public void requestImageFailedRetryDialog(int mediaId) {
mOnMediaLibraryButtonListener.onRetryUploadForMediaClicked(mediaId);
}
@Override
public void requestImageUploadCancelDialog(int mediaId) {
mOnMediaLibraryButtonListener.onCancelUploadForMediaClicked(mediaId);
}
@Override
public void requestImageUploadCancel(int mediaId) {
mOnMediaLibraryButtonListener.onCancelUploadForMediaDueToDeletedBlock(mediaId);
}
@Override
public void setFeaturedImage(int mediaId) {
mOnSetFeaturedImageListener.onSetFeaturedImageButtonClicked(mediaId);
}
@Override
public void editorDidMount(ReadableArray unsupportedBlockNames) {
mOnEditorMountListener.onEditorDidMount(unsupportedBlockNames.toArrayList());
mDeferredEventEmitter.setEmitter(mRnReactNativeGutenbergBridgePackage
.getRNReactNativeGutenbergBridgeModule());
mIsEditorMounted = true;
if (TextUtils.isEmpty(mTitle) && TextUtils.isEmpty(mContentHtml)) {
setFocusOnTitle();
// send signal to Editor to create a new image block and pass the media URL, start uploading, etc
// use mMediaUrlToAddAfterMounting
dispatchOneMediaToAddAtATimeIfAvailable();
}
refreshEditorTheme();
}
@Override
public void editorDidAutosave() {
if (mOnEditorAutosaveListener != null) {
mOnEditorAutosaveListener.onEditorAutosave();
}
}
@Override
public void editorDidEmitLog(String message, LogLevel logLevel) {
switch (logLevel) {
case TRACE:
AppLog.d(AppLog.T.EDITOR, message);
break;
case INFO:
AppLog.i(AppLog.T.EDITOR, message);
break;
case WARN:
AppLog.w(AppLog.T.EDITOR, message);
break;
case ERROR:
AppLog.e(AppLog.T.EDITOR, message);
break;
}
}
@Override
public void getOtherMediaPickerOptions(OtherMediaOptionsReceivedCallback otherMediaOptionsReceivedCallback,
MediaType mediaType) {
switch (mediaType){
case IMAGE:
case MEDIA:
ArrayList<MediaOption> otherMediaImageOptions = mOnMediaLibraryButtonListener.onGetOtherMediaImageOptions();
otherMediaOptionsReceivedCallback.onOtherMediaOptionsReceived(otherMediaImageOptions);
break;
case ANY:
ArrayList<MediaOption> otherMediaFileOptions = mOnMediaLibraryButtonListener.onGetOtherMediaFileOptions();
otherMediaOptionsReceivedCallback.onOtherMediaOptionsReceived(otherMediaFileOptions);
break;
case AUDIO:
ArrayList<MediaOption> otherMediaAudioFileOptions = mOnMediaLibraryButtonListener.onGetOtherMediaAudioFileOptions();
otherMediaOptionsReceivedCallback.onOtherMediaOptionsReceived(otherMediaAudioFileOptions);
break;
}
}
@Override
public void requestMediaPickFrom(String mediaSource,
MediaSelectedCallback mediaSelectedCallback,
Boolean allowMultipleSelection) {
mMediaSelectedCallback = mediaSelectedCallback;
mMediaPickedByUserOnBlock = true;
mAppendsMultipleSelectedToSiblingBlocks = false;
mOnMediaLibraryButtonListener.onOtherMediaButtonClicked(mediaSource, allowMultipleSelection);
}
@Override
public void performGetRequest(String pathFromJS, boolean enableCaching, Consumer<String> onSuccess, Consumer<Bundle> onError) {
mRequestExecutor.performGetRequest(pathFromJS, enableCaching, onSuccess, onError);
}
@Override
public void performPostRequest(String pathFromJS, ReadableMap data, Consumer<String> onSuccess, Consumer<Bundle> onError) {
mRequestExecutor.performPostRequest(pathFromJS, data, onSuccess, onError);
}
@Override
public void requestImageFullscreenPreview(String mediaUrl) {
mOnImageFullscreenPreviewListener.onImageFullscreenPreviewClicked(mediaUrl);
}
@Override
public void requestMediaEditor(MediaSelectedCallback mediaSelectedCallback, String mediaUrl) {
mMediaPickedByUserOnBlock = true;
mMediaSelectedCallback = mediaSelectedCallback;
mOnMediaEditorListener.onMediaEditorClicked(mediaUrl);
}
@Override
public void gutenbergDidRequestUnsupportedBlockFallback(ReplaceUnsupportedBlockCallback replaceUnsupportedBlockCallback,
String content,
String blockId,
String blockName,
String blockTitle) {
mReplaceUnsupportedBlockCallback = replaceUnsupportedBlockCallback;
mOnGutenbergDidRequestUnsupportedBlockFallbackListener.
gutenbergDidRequestUnsupportedBlockFallback(new UnsupportedBlock(blockId, blockName, blockTitle, content));
}
public void requestEmbedFullscreenPreview(String html, String title) {
mOnGutenbergDidRequestEmbedFullscreenPreviewListener.
gutenbergDidRequestEmbedFullscreenPreview(html, title);
}
@Override
public void gutenbergDidSendButtonPressedAction(String buttonType) {
mOnGutenbergDidSendButtonPressedActionListener.gutenbergDidSendButtonPressedAction(buttonType);
}
@Override
public void onShowUserSuggestions(Consumer<String> onResult) {
mShowSuggestionsUtil.showUserSuggestions(onResult);
}
@Override public void onShowXpostSuggestions(Consumer<String> onResult) {
mShowSuggestionsUtil.showXpostSuggestions(onResult);
}
@Override
public void setFocalPointPickerTooltipShown(boolean showTooltip) {
mOnFocalPointPickerTooltipShownListener.onSetFocalPointPickerTooltipShown(showTooltip);
}
@Override
public void requestFocalPointPickerTooltipShown(FocalPointPickerTooltipShownCallback focalPointPickerTooltipShownCallback) {
boolean tooltipShown = mOnFocalPointPickerTooltipShownListener.onRequestFocalPointPickerTooltipShown();
focalPointPickerTooltipShownCallback.onRequestFocalPointPickerTooltipShown(tooltipShown);
}
@Override
public void requestPreview() {
mOnGutenbergDidRequestPreviewListener.gutenbergDidRequestPreview();
}
@Override
public void requestBlockTypeImpressions(BlockTypeImpressionsCallback blockTypeImpressionsCallback) {
// Double utilized to satisfy both React Native's expectations (https://bit.ly/3f3tsT4)
// and Gson's deserialization which uses Double for all numbers (https://bit.ly/2VfpvUv)
Map<String, Double> storedImpressions = mOnBlockTypeImpressionsEventListener.onRequestBlockTypeImpressions();
WritableMap impressions = Arguments.createMap();
for (Map.Entry<String, Double> entry: storedImpressions.entrySet()) {
impressions.putDouble(entry.getKey(), entry.getValue());
}
blockTypeImpressionsCallback.onRequestBlockTypeImpressions(impressions);
}
@Override
public void setBlockTypeImpressions(ReadableMap newImpressions) {
Map<String, Double> impressions = new HashMap<>();
ReadableMapKeySetIterator iterator = newImpressions.keySetIterator();
while (iterator.hasNextKey()) {
String key = iterator.nextKey();
impressions.put(key, newImpressions.getDouble(key));
}
mOnBlockTypeImpressionsEventListener.onSetBlockTypeImpressions(impressions);
}
@Override
public void requestContactCustomerSupport() {
mOnCustomerSupportOptionsListener.onContactCustomerSupport();
}
@Override
public void requestGotoCustomerSupportOptions() {
mOnCustomerSupportOptionsListener.onGotoCustomerSupportOptions();
}
@Override
public void sendEventToHost(String eventName, ReadableMap properties) {
mOnSendEventToHostListener.onSendEventToHost(eventName, properties.toHashMap());
}
@Override
public void toggleUndoButton(boolean isDisabled) {
mOnToggleUndoButtonListener.onToggleUndoButton(isDisabled);
}
@Override
public void toggleRedoButton(boolean isDisabled) {
mOnToggleRedoButtonListener.onToggleRedoButton(isDisabled);
}
@Override
public void requestConnectionStatus(ConnectionStatusCallback connectionStatusCallback) {
boolean isConnected = mOnConnectionStatusEventListener.onRequestConnectionStatus();
connectionStatusCallback.onRequestConnectionStatus(isConnected);
}
@Override
public void logException(GutenbergJsException exception, LogExceptionCallback logExceptionCallback) {
mOnLogExceptionListener.onLogException(exception, logExceptionCallback);
}
}, mIsDarkMode);
return Arrays.asList(
new MainReactPackage(getMainPackageConfig(getImagePipelineConfig(sOkHttpClient))),
new SvgPackage(),
new LinearGradientPackage(),
new ReactAztecPackage(mExceptionLogger, mBreadcrumbLogger),
new ReactVideoPackage(),
new ReactSliderPackage(),
new RNGetRandomValuesPackage(),
new RNGestureHandlerPackage(),
new RNScreensPackage(),
new SafeAreaContextPackage(),
new RNCMaskedViewPackage(),
new ReanimatedPackage() {
// Reanimated assumes that the app implements "ReactApplication" in order to get the React instance
// manager. Since this is not the case, as Gutenberg is integrated as a library, we have to override
// "getReactInstanceManager" in order to provide the proper instance.
@Override
public ReactInstanceManager getReactInstanceManager(ReactApplicationContext reactContext) {
return mReactInstanceManager;
}
},
new RNCWebViewPackage(),
new ClipboardPackage(),
new FastImageViewPackage(),
mRnReactNativeGutenbergBridgePackage);
}
private MainPackageConfig getMainPackageConfig(ImagePipelineConfig imagePipelineConfig) {
return new MainPackageConfig.Builder().setFrescoConfig(imagePipelineConfig).build();
}
private ImagePipelineConfig getImagePipelineConfig(OkHttpClient client) {
return OkHttpImagePipelineConfigFactory
.newBuilder(mReactRootView.getContext(), client).build();
}
public void onCreateView(Context initContext,
Application application,
boolean isDebug,
int colorBackground,
Consumer<Exception> exceptionLogger,
Consumer<String> breadcrumbLogger,
GutenbergProps gutenbergProps) {
mIsDarkMode = gutenbergProps.isDarkMode();
mExceptionLogger = exceptionLogger;
mBreadcrumbLogger = breadcrumbLogger;
mReactRootView = new ReactRootView(new MutableContextWrapper(initContext));
mReactRootView.setBackgroundColor(colorBackground);
// Workaround to prevent saving large RN view hierarchies that lead to a `TransactionTooLargeException`
// Ref: https://github.com/wordpress-mobile/WordPress-Android/issues/9685#issuecomment-1908452392
mReactRootView.setSaveFromParentEnabled(false);
ReactInstanceManagerBuilder builder =
ReactInstanceManager.builder()
.setApplication(application)
.setJSMainModulePath("index")
.addPackages(getPackages())
.setUseDeveloperSupport(isDebug)
.setJavaScriptExecutorFactory(new HermesExecutorFactory())
.setInitialLifecycleState(LifecycleState.BEFORE_CREATE);
if (BuildConfig.SHOULD_ATTACH_JS_BUNDLE) {
builder.setBundleAssetName("index.android.bundle");
}
mReactInstanceManager = builder.build();
mReactInstanceManager.addReactInstanceEventListener(context -> {
mReactContext = context;
});
Bundle initialProps = gutenbergProps.getInitialProps(mReactRootView.getAppProperties());
mReactRootView.setAppProperties(initialProps);
}
public void attachToContainer(ViewGroup viewGroup,
OnMediaLibraryButtonListener onMediaLibraryButtonListener,
OnReattachMediaUploadQueryListener onReattachMediaUploadQueryListener,
OnSetFeaturedImageListener onSetFeaturedImageListener,
OnEditorMountListener onEditorMountListener,
OnEditorAutosaveListener onEditorAutosaveListener,
OnAuthHeaderRequestedListener onAuthHeaderRequestedListener,
RequestExecutor fetchExecutor,
OnImageFullscreenPreviewListener onImageFullscreenPreviewListener,
OnMediaEditorListener onMediaEditorListener,
OnGutenbergDidRequestUnsupportedBlockFallbackListener onGutenbergDidRequestUnsupportedBlockFallbackListener,
OnGutenbergDidRequestEmbedFullscreenPreviewListener onGutenbergDidRequestEmbedFullscreenPreviewListener,
OnGutenbergDidSendButtonPressedActionListener onGutenbergDidSendButtonPressedActionListener,
ShowSuggestionsUtil showSuggestionsUtil,
OnFocalPointPickerTooltipShownEventListener onFocalPointPickerTooltipListener,
OnGutenbergDidRequestPreviewListener onGutenbergDidRequestPreviewListener,
OnBlockTypeImpressionsEventListener onBlockTypeImpressionsEventListener,
OnCustomerSupportOptionsListener onCustomerSupportOptionsListener,
OnSendEventToHostListener onSendEventToHostListener,
OnToggleUndoButtonListener onToggleUndoButtonListener,
OnToggleRedoButtonListener onToggleRedoButtonListener,
OnConnectionStatusEventListener onConnectionStatusEventListener,
OnBackHandlerEventListener onBackHandlerEventListener,
OnLogExceptionListener onLogExceptionListener,
boolean isDarkMode) {
MutableContextWrapper contextWrapper = (MutableContextWrapper) mReactRootView.getContext();
contextWrapper.setBaseContext(viewGroup.getContext());
mOnMediaLibraryButtonListener = onMediaLibraryButtonListener;
mOnReattachMediaUploadQueryListener = onReattachMediaUploadQueryListener;
mOnSetFeaturedImageListener = onSetFeaturedImageListener;
mOnEditorMountListener = onEditorMountListener;
mOnEditorAutosaveListener = onEditorAutosaveListener;
mRequestExecutor = fetchExecutor;
mOnImageFullscreenPreviewListener = onImageFullscreenPreviewListener;
mOnMediaEditorListener = onMediaEditorListener;
mOnGutenbergDidRequestUnsupportedBlockFallbackListener = onGutenbergDidRequestUnsupportedBlockFallbackListener;
mOnGutenbergDidRequestEmbedFullscreenPreviewListener = onGutenbergDidRequestEmbedFullscreenPreviewListener;
mOnGutenbergDidSendButtonPressedActionListener = onGutenbergDidSendButtonPressedActionListener;
mShowSuggestionsUtil = showSuggestionsUtil;
mOnFocalPointPickerTooltipShownListener = onFocalPointPickerTooltipListener;
mOnGutenbergDidRequestPreviewListener = onGutenbergDidRequestPreviewListener;
mOnBlockTypeImpressionsEventListener = onBlockTypeImpressionsEventListener;
mOnCustomerSupportOptionsListener = onCustomerSupportOptionsListener;
mOnSendEventToHostListener = onSendEventToHostListener;
mOnToggleUndoButtonListener = onToggleUndoButtonListener;
mOnToggleRedoButtonListener = onToggleRedoButtonListener;
mOnConnectionStatusEventListener = onConnectionStatusEventListener;
mOnBackHandlerEventListener = onBackHandlerEventListener;
mOnLogExceptionListener = onLogExceptionListener;
sAddCookiesInterceptor.setOnAuthHeaderRequestedListener(onAuthHeaderRequestedListener);
if (mReactRootView.getParent() != null) {
((ViewGroup) mReactRootView.getParent()).removeView(mReactRootView);
}
viewGroup.addView(mReactRootView, 0,
new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
if (hasReactContext()) {
setPreferredColorScheme(isDarkMode);
}
refocus();
}
private void refocus() {
if (mLastFocusedView != null) {
// schedule a request for focus
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override public void run() {
// Check if View reference is still alive and in the view hierarchy
if (mLastFocusedView != null
&& mLastFocusedView.get() != null
&& mLastFocusedView.get().getParent() != null) {
// request focus to the last focused child
mLastFocusedView.get().requestFocus();
}
}
});
}
}
public void onPause(Activity activity) {
mShouldHandleBackPress = false;
if (mReactInstanceManager != null) {
// get the focused view so we re-focus it later if needed. WeakReference so we don't leak it.
mLastFocusedView = new WeakReference<>(mReactRootView.findFocus());
mReactInstanceManager.onHostPause(activity);
}
}
public void onResume(final Fragment fragment, final Activity activity) {
mShouldHandleBackPress = true;
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostResume(activity,
new DefaultHardwareBackBtnHandler() {
@Override
public void invokeDefaultOnBackPressed() {
if (fragment.isAdded()) {
mOnBackHandlerEventListener.onBackHandler();
}
}
});
}
}
public void onDetach(Activity activity) {
mShouldHandleBackPress = false;
mReactInstanceManager.onHostDestroy(activity);
mRnReactNativeGutenbergBridgePackage.getRNReactNativeGutenbergBridgeModule().notifyModalClosed();
}
public void onDestroy(Activity activity) {
mShouldHandleBackPress = false;
if (mReactRootView != null) {
mReactRootView.unmountReactApplication();
mReactRootView = null;
sAddCookiesInterceptor.setOnAuthHeaderRequestedListener(null);
}
if (mReactInstanceManager != null) {
// onDestroy may be called on a ReactFragment after another ReactFragment has been
// created and resumed with the same React Instance Manager. Make sure we only clean up
// host's React Instance Manager if no other React Fragment is actively using it.
if (mReactInstanceManager.getLifecycleState() != LifecycleState.RESUMED) {
mReactInstanceManager.onHostDestroy(activity);
}
}
}
public void onBackPressed() {
if (mReactInstanceManager != null) {
mReactInstanceManager.onBackPressed();
}
}
public void showDevOptionsDialog() {
mReactInstanceManager.showDevOptionsDialog();
}
public void setFocusOnTitle() {
mRnReactNativeGutenbergBridgePackage.getRNReactNativeGutenbergBridgeModule().setFocusOnTitleInJS();
}
public void appendNewMediaBlock(int mediaId, String mediaUri, String mediaType) {
mRnReactNativeGutenbergBridgePackage.getRNReactNativeGutenbergBridgeModule()
.appendNewMediaBlock(mediaId, mediaUri, mediaType);
}
public void setPreferredColorScheme(boolean isDarkMode) {
if (mIsDarkMode != isDarkMode) {
mIsDarkMode = isDarkMode;
mRnReactNativeGutenbergBridgePackage.getRNReactNativeGutenbergBridgeModule()
.setPreferredColorScheme(isDarkMode);
}
}
public void updateTheme(@Nullable Bundle editorTheme) {
if (mIsEditorMounted) {
mRnReactNativeGutenbergBridgePackage.getRNReactNativeGutenbergBridgeModule()
.updateTheme(editorTheme);
} else {
// Editor hasn't mounted yet. Save theme and load once editor loads
AppLog.d(AppLog.T.EDITOR, "Editor theme not applied reason: Editor not mounted");
mEditorTheme = editorTheme;
}
}
private void refreshEditorTheme() {
if (mEditorTheme != null) {
mRnReactNativeGutenbergBridgePackage.getRNReactNativeGutenbergBridgeModule()
.updateTheme(mEditorTheme);
mEditorTheme = null;
}
}
public void showNotice(String message) {
if (message != null) {
mRnReactNativeGutenbergBridgePackage.getRNReactNativeGutenbergBridgeModule().showNoticeInJS(message);
} else {
AppLog.d(AppLog.T.EDITOR, "Notice not shown because message is null");
}
}
public void showEditorHelp() {
mRnReactNativeGutenbergBridgePackage.getRNReactNativeGutenbergBridgeModule().showEditorHelp();
}
public void onUndoPressed() {
mRnReactNativeGutenbergBridgePackage.getRNReactNativeGutenbergBridgeModule().onUndoPressed();
}
public void onRedoPressed() {
mRnReactNativeGutenbergBridgePackage.getRNReactNativeGutenbergBridgeModule().onRedoPressed();
}
public void onContentUpdate(String content) {
mRnReactNativeGutenbergBridgePackage.getRNReactNativeGutenbergBridgeModule().onContentUpdate(content);
}
public void setTitle(String title) {
mTitleInitialized = true;
mTitle = title;
setContent(mTitle, mContentHtml);
}
public void setContent(String postContent) {
mContentInitialized = true;
mContentHtml = postContent;
setContent(mTitle, mContentHtml);
}
public boolean hasReceivedInitialTitleAndContent() {
return mTitleInitialized && mContentInitialized;
}
private void setContent(String title, String postContent) {
if (mReactRootView == null) {
return;
}
// wait for both title and content to have been set at least once. Legacy editor implementation had the two as
// separate calls but, we only want a single call to correctly boot the GB editor
if (!hasReceivedInitialTitleAndContent()) {
return;
}
// Content can be set directly to RootView only once (per RootView instance)
// because we don't want to bootstrap the whole Gutenberg state.
// Otherwise it should be done through module interface
if (mShouldUpdateContent) {
updateContent(title, postContent);
} else {
mShouldUpdateContent = true;
initContent(title, postContent);
}
}
private void initContent(String title, String content) {
if (content != null) {
mContentHtml = content;
}
if (title != null) {
mTitle = title;
}
Bundle appProps = GutenbergProps.Companion.initContent(mReactRootView.getAppProperties(), title, content);
mReactRootView.startReactApplication(mReactInstanceManager, "gutenberg", appProps);
}
private void updateContent(String title, String content) {
if (content != null) {
mContentHtml = content;
}
if (title != null) {
mTitle = title;
}
if (hasReactContext()) {
if (content != null) {
mRnReactNativeGutenbergBridgePackage.getRNReactNativeGutenbergBridgeModule().setHtmlInJS(content);
}
if (title != null) {
mRnReactNativeGutenbergBridgePackage.getRNReactNativeGutenbergBridgeModule().setTitleInJS(title);
}
}
}
public interface OnGetContentInterrupted {
void onGetContentInterrupted(InterruptedException ie);
}
public synchronized CharSequence getContent(CharSequence originalContent,
OnGetContentInterrupted onGetContentInterrupted) {
if (hasReactContext()) {
mGetContentCountDownLatch = new CountDownLatch(1);
mRnReactNativeGutenbergBridgePackage.getRNReactNativeGutenbergBridgeModule().getHtmlFromJS();
try {
boolean success = mGetContentCountDownLatch.await(10, TimeUnit.SECONDS);
if (!success) {
AppLog.e(T.EDITOR, "Timeout reached before response from requestGetHtml.");
}
} catch (InterruptedException ie) {
onGetContentInterrupted.onGetContentInterrupted(ie);
}
return mContentChanged ? (mContentHtml == null ? "" : mContentHtml) : originalContent;
} else {
AppLog.e(T.EDITOR, "getContent was called when there was no React context.");
}
return originalContent;
}
/** This method retrieves both the title and the content from the Gutenberg editor by the emission of a single
* event. This is useful to avoid redundant events, since {@link #getContent} already retrieves the title as well,
* using same event, and also shares the same mechanism to suspend execution until a response is received (or a
* timeout is reached).
* @param originalContent fallback content to return in case the timeout is reached, or the thread is interrupted
* @param onGetContentInterrupted callback to invoke if thread is interrupted before the timeout
* @return A Pair of CharSequence with the first being the title and the second being the content
*/
public synchronized Pair<CharSequence, CharSequence> getTitleAndContent(CharSequence originalContent,
OnGetContentInterrupted onGetContentInterrupted) {
if (hasReactContext()) {
mGetContentCountDownLatch = new CountDownLatch(1);
mRnReactNativeGutenbergBridgePackage.getRNReactNativeGutenbergBridgeModule().getHtmlFromJS();
try {
boolean success = mGetContentCountDownLatch.await(10, TimeUnit.SECONDS);
if (!success) {
AppLog.e(T.EDITOR, "Timeout reached before response from requestGetHtml.");
}
} catch (InterruptedException ie) {
onGetContentInterrupted.onGetContentInterrupted(ie);
}
return new Pair<>(
mTitle == null ? "" : mTitle,
mContentChanged ? (mContentHtml == null ? "" : mContentHtml) : originalContent
);
} else {
AppLog.e(T.EDITOR, "getTitleAndContent was called when there was no React context.");
}
return new Pair<>("", originalContent);
}
public boolean triggerGetContentInfo(OnContentInfoReceivedListener onContentInfoReceivedListener) {
if (hasReactContext() && (mGetContentCountDownLatch == null || mGetContentCountDownLatch.getCount() == 0)) {
if (!mIsEditorMounted) {
onContentInfoReceivedListener.onEditorNotReady();
return false;
}
new Thread(new Runnable() {
@Override public void run() {
// We need to synchronize access to (and overwriting of) the latch to avoid race conditions
synchronized (WPAndroidGlueCode.this) {
mGetContentCountDownLatch = new CountDownLatch(1);
mRnReactNativeGutenbergBridgePackage.getRNReactNativeGutenbergBridgeModule().getHtmlFromJS();
try {
boolean success = mGetContentCountDownLatch.await(5, TimeUnit.SECONDS);
if (!success) {
AppLog.e(T.EDITOR, "Timeout reached before response from requestGetHtml.");