This repository has been archived by the owner on Apr 3, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 652
/
XWalkContent.java
1157 lines (980 loc) · 43.2 KB
/
XWalkContent.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 2013 The Chromium Authors. All rights reserved.
// Copyright (c) 2013-2014 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.xwalk.core.internal;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.net.http.SslCertificate;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Base64;
import android.util.Log;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.ViewGroup;
import android.view.View.OnTouchListener;
import android.webkit.ValueCallback;
import android.webkit.WebResourceResponse;
import android.widget.FrameLayout;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.Locale;
import java.util.Map;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.ThreadUtils;
import org.chromium.components.navigation_interception.InterceptNavigationDelegate;
import org.chromium.content.browser.ContentView;
import org.chromium.content.browser.ContentViewCore;
import org.chromium.content.browser.ContentViewRenderView;
import org.chromium.content.browser.ContentViewRenderView.CompositingSurfaceType;
import org.chromium.content.browser.ContentViewStatics;
import org.chromium.content.common.CleanupReference;
import org.chromium.content_public.browser.ContentBitmapCallback;
import org.chromium.content_public.browser.JavaScriptCallback;
import org.chromium.content_public.browser.LoadUrlParams;
import org.chromium.content_public.browser.NavigationHistory;
import org.chromium.content_public.browser.NavigationController;
import org.chromium.content_public.browser.WebContents;
import org.chromium.content_public.browser.navigation_controller.UserAgentOverrideOption;
import org.chromium.media.MediaPlayerBridge;
import org.chromium.ui.base.ActivityWindowAndroid;
import org.chromium.ui.base.WindowAndroid;
import org.chromium.ui.gfx.DeviceDisplayInfo;
import org.json.JSONArray;
@JNINamespace("xwalk")
/**
* This class is the implementation class for XWalkViewInternal by calling internal
* various classes.
*/
class XWalkContent implements XWalkPreferencesInternal.KeyValueChangeListener {
private static String TAG = "XWalkContent";
private static Class<? extends Annotation> javascriptInterfaceClass = null;
private ContentViewCore mContentViewCore;
private Context mViewContext;
private XWalkContentView mContentView;
private ContentViewRenderView mContentViewRenderView;
private WindowAndroid mWindow;
private XWalkDevToolsServer mDevToolsServer;
private XWalkViewInternal mXWalkView;
private XWalkContentsClientBridge mContentsClientBridge;
private XWalkContentsIoThreadClient mIoThreadClient;
private XWalkWebContentsDelegateAdapter mXWalkContentsDelegateAdapter;
private XWalkSettingsInternal mSettings;
private XWalkGeolocationPermissions mGeolocationPermissions;
private XWalkLaunchScreenManager mLaunchScreenManager;
private NavigationController mNavigationController;
private WebContents mWebContents;
private boolean mIsLoaded = false;
private boolean mAnimated = false;
private XWalkAutofillClientAndroid mXWalkAutofillClient;
private XWalkGetBitmapCallbackInternal mXWalkGetBitmapCallbackInternal;
private ContentBitmapCallback mGetBitmapCallback;
private final HitTestData mPossiblyStaleHitTestData = new HitTestData();
long mNativeContent;
public static class HitTestData {
// Used in getHitTestResult
public int hitTestResultType;
public String hitTestResultExtraData;
// Used in requestFocusNodeHref(all three) and requestImageRef(only imageSrc)
public String href;
public String anchorText;
public String imgSrc;
}
// TODO(hengzhi.wu): This should be in a global context, not per XWalkView.
private double mDIPScale;
static void setJavascriptInterfaceClass(Class<? extends Annotation> clazz) {
assert(javascriptInterfaceClass == null);
javascriptInterfaceClass = clazz;
}
private static final class DestroyRunnable implements Runnable {
private final long mNativeContent;
private DestroyRunnable(long nativeXWalkContent) {
mNativeContent = nativeXWalkContent;
}
@Override
public void run() {
nativeDestroy(mNativeContent);
}
}
// Reference to the active mNativeContent pointer while it is active use
// (ie before it is destroyed).
private CleanupReference mCleanupReference;
public XWalkContent(Context context, String animatable, XWalkViewInternal xwView) {
// Initialize the WebContensDelegate.
mXWalkView = xwView;
mViewContext = mXWalkView.getContext();
mContentsClientBridge = new XWalkContentsClientBridge(mXWalkView);
mXWalkContentsDelegateAdapter = new XWalkWebContentsDelegateAdapter(
mContentsClientBridge);
mIoThreadClient = new XWalkIoThreadClientImpl();
// Initialize mWindow which is needed by content.
mWindow = WindowAndroid.activityFromContext(context) != null ?
new ActivityWindowAndroid(context) : new WindowAndroid(context);
SharedPreferences sharedPreferences = new InMemorySharedPreferences();
mGeolocationPermissions = new XWalkGeolocationPermissions(sharedPreferences);
MediaPlayerBridge.setResourceLoadingFilter(
new XWalkMediaPlayerResourceLoadingFilter());
setNativeContent(nativeInit(), animatable);
XWalkPreferencesInternal.load(this);
initCaptureBitmapAsync();
}
private void initCaptureBitmapAsync() {
mGetBitmapCallback = new ContentBitmapCallback() {
@Override
public void onFinishGetBitmap(Bitmap bitmap, int response) {
if (mXWalkGetBitmapCallbackInternal == null) return;
mXWalkGetBitmapCallbackInternal.onFinishGetBitmap(bitmap, response);
}
};
}
public void captureBitmapAsync(XWalkGetBitmapCallbackInternal callback) {
if (mNativeContent == 0) return;
mXWalkGetBitmapCallbackInternal = callback;
mWebContents.getContentBitmapAsync(Bitmap.Config.ARGB_8888, 1.0f,
new Rect(), mGetBitmapCallback);
}
private void setNativeContent(long newNativeContent, String animatable) {
if (mNativeContent != 0) {
destroy();
mContentViewCore = null;
}
assert mNativeContent == 0 && mCleanupReference == null && mContentViewCore == null;
// Initialize ContentViewRenderView
if(animatable == null)
mAnimated = XWalkPreferencesInternal.getValue(
XWalkPreferencesInternal.ANIMATABLE_XWALK_VIEW);
else
mAnimated = animatable.equalsIgnoreCase("true");
CompositingSurfaceType surfaceType =
mAnimated ? CompositingSurfaceType.TEXTURE_VIEW : CompositingSurfaceType.SURFACE_VIEW;
Log.d(TAG, "CompositingSurfaceType is " + (mAnimated ? "TextureView" : "SurfaceView"));
mContentViewRenderView = new ContentViewRenderView(mViewContext, surfaceType) {
protected void onReadyToRender() {
// Anything depending on the underlying Surface readiness should
// be placed here.
}
};
mContentViewRenderView.onNativeLibraryLoaded(mWindow);
mLaunchScreenManager = new XWalkLaunchScreenManager(mViewContext, mXWalkView);
mContentViewRenderView.registerFirstRenderedFrameListener(mLaunchScreenManager);
mXWalkView.addView(mContentViewRenderView, new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT));
mNativeContent = newNativeContent;
// The native side object has been bound to this java instance, so now is the time to
// bind all the native->java relationships.
mCleanupReference = new CleanupReference(this, new DestroyRunnable(mNativeContent));
mWebContents = nativeGetWebContents(mNativeContent);
// Initialize ContentView.
mContentViewCore = new ContentViewCore(mViewContext);
mContentView = XWalkContentView.createContentView(
mViewContext, mContentViewCore, mXWalkView);
mContentViewCore.initialize(mContentView, mContentView, mWebContents, mWindow);
mNavigationController = mWebContents.getNavigationController();
mXWalkView.addView(mContentView, new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT));
mContentViewCore.setContentViewClient(mContentsClientBridge);
mContentViewRenderView.setCurrentContentViewCore(mContentViewCore);
// For addJavascriptInterface
mContentsClientBridge.installWebContentsObserver(mWebContents);
// Set the third argument isAccessFromFileURLsGrantedByDefault to false, so that
// the members mAllowUniversalAccessFromFileURLs and mAllowFileAccessFromFileURLs
// won't be changed from false to true at the same time in the constructor of
// XWalkSettings class.
mSettings = new XWalkSettingsInternal(mViewContext, mWebContents, false);
// Enable AllowFileAccessFromFileURLs, so that files under file:// path could be
// loaded by XMLHttpRequest.
mSettings.setAllowFileAccessFromFileURLs(true);
// Set DIP scale.
mDIPScale = DeviceDisplayInfo.create(mViewContext).getDIPScale();
mContentsClientBridge.setDIPScale(mDIPScale);
mSettings.setDIPScale(mDIPScale);
String language = Locale.getDefault().toString().replaceAll("_", "-").toLowerCase();
if (language.isEmpty()) language = "en";
mSettings.setAcceptLanguages(language);
XWalkSettingsInternal.ZoomSupportChangeListener zoomListener =
new XWalkSettingsInternal.ZoomSupportChangeListener() {
@Override
public void onGestureZoomSupportChanged(
boolean supportsDoubleTapZoom, boolean supportsMultiTouchZoom) {
mContentViewCore.updateDoubleTapSupport(supportsDoubleTapZoom);
mContentViewCore.updateMultiTouchZoomSupport(supportsMultiTouchZoom);
}
};
mSettings.setZoomListener(zoomListener);
nativeSetJavaPeers(mNativeContent, this, mXWalkContentsDelegateAdapter, mContentsClientBridge,
mIoThreadClient, mContentsClientBridge.getInterceptNavigationDelegate());
}
public void supplyContentsForPopup(XWalkContent newContents) {
if (mNativeContent == 0) return;
long popupNativeXWalkContent = nativeReleasePopupXWalkContent(mNativeContent);
if (popupNativeXWalkContent == 0) {
Log.w(TAG, "Popup XWalkView bind failed: no pending content.");
if (newContents != null) newContents.destroy();
return;
}
if (newContents == null) {
nativeDestroy(popupNativeXWalkContent);
return;
}
newContents.receivePopupContents(popupNativeXWalkContent);
}
private void receivePopupContents(long popupNativeXWalkContents) {
setNativeContent(popupNativeXWalkContents, null);
mContentViewCore.onShow();
}
private void doLoadUrl(LoadUrlParams params) {
params.setOverrideUserAgent(UserAgentOverrideOption.TRUE);
mNavigationController.loadUrl(params);
mContentView.requestFocus();
mIsLoaded = true;
}
private static String fixupBase(String url) {
return TextUtils.isEmpty(url) ? "about:blank" : url;
}
private static String fixupData(String data) {
return TextUtils.isEmpty(data) ? "" : data;
}
private static String fixupHistory(String url) {
return TextUtils.isEmpty(url) ? "about:blank" : url;
}
private static String fixupMimeType(String mimeType) {
return TextUtils.isEmpty(mimeType) ? "text/html" : mimeType;
}
private static boolean isBase64Encoded(String encoding) {
return "base64".equals(encoding);
}
public void loadData(String data, String mimeType, String encoding) {
if (mNativeContent == 0) return;
data = TextUtils.isEmpty(data) ? "" : data;
mimeType = TextUtils.isEmpty(mimeType) ? "text/html" : mimeType;
doLoadUrl(LoadUrlParams.createLoadDataParams(
fixupData(data), fixupMimeType(mimeType),isBase64Encoded(encoding)));
}
public void loadDataWithBaseURL(
String baseUrl, String data, String mimeType, String encoding, String historyUrl) {
if (mNativeContent == 0) return;
data = fixupData(data);
mimeType = fixupMimeType(mimeType);
LoadUrlParams loadUrlParams;
baseUrl = fixupBase(baseUrl);
historyUrl = fixupHistory(historyUrl);
// When loading data with a non-data: base URL, the classic WebView would effectively
// "dump" that string of data into the WebView without going through regular URL
// loading steps such as decoding URL-encoded entities. We achieve this same behavior by
// base64 encoding the data that is passed here and then loading that as a data: URL.
try {
loadUrlParams = LoadUrlParams.createLoadDataParamsWithBaseUrl(
Base64.encodeToString(data.getBytes("utf-8"), Base64.DEFAULT), mimeType,
true, baseUrl, historyUrl, "utf-8");
} catch (java.io.UnsupportedEncodingException e) {
Log.w(TAG, "Unable to load data string " + data, e);
return;
}
doLoadUrl(loadUrlParams);
}
public void loadUrl(String url) {
// Early out to match the old classic Android WebView's implementation.
if (url == null) {
return;
}
loadUrl(url, null);
}
public void loadUrl(String url, Map<String, String> additionalHttpHeaders) {
if (mNativeContent == 0) return;
LoadUrlParams params = new LoadUrlParams(url);
if (additionalHttpHeaders != null) params.setExtraHeaders(additionalHttpHeaders);
doLoadUrl(params);
}
public void reload(int mode) {
if (mNativeContent == 0) return;
switch (mode) {
case XWalkViewInternal.RELOAD_IGNORE_CACHE:
mNavigationController.reloadBypassingCache(true);
break;
case XWalkViewInternal.RELOAD_NORMAL:
default:
mNavigationController.reload(true);
}
mIsLoaded = true;
}
public String getUrl() {
if (mNativeContent == 0) return null;
String url = mWebContents.getUrl();
if (url == null || url.trim().isEmpty()) return null;
return url;
}
public String getTitle() {
if (mNativeContent == 0) return null;
String title = mWebContents.getTitle().trim();
if (title == null) title = "";
return title;
}
public void addJavascriptInterface(Object object, String name) {
if (mNativeContent == 0) return;
mContentViewCore.addPossiblyUnsafeJavascriptInterface(object, name,
javascriptInterfaceClass);
}
public void removeJavascriptInterface(String name) {
if (mNativeContent == 0) return;
mContentViewCore.removeJavascriptInterface(name);
}
public void evaluateJavascript(String script, ValueCallback<String> callback) {
if (mNativeContent == 0) return;
final ValueCallback<String> fCallback = callback;
JavaScriptCallback coreCallback = null;
if (fCallback != null) {
coreCallback = new JavaScriptCallback() {
@Override
public void handleJavaScriptResult(String jsonResult) {
fCallback.onReceiveValue(jsonResult);
}
};
}
mContentViewCore.getWebContents().evaluateJavaScript(script, coreCallback);
}
public void setUIClient(XWalkUIClientInternal client) {
if (mNativeContent == 0) return;
mContentsClientBridge.setUIClient(client);
}
public void setResourceClient(XWalkResourceClientInternal client) {
if (mNativeContent == 0) return;
mContentsClientBridge.setResourceClient(client);
}
public void setXWalkWebChromeClient(XWalkWebChromeClient client) {
if (mNativeContent == 0) return;
mContentsClientBridge.setXWalkWebChromeClient(client);
}
public XWalkWebChromeClient getXWalkWebChromeClient() {
if (mNativeContent == 0) return null;
return mContentsClientBridge.getXWalkWebChromeClient();
}
public int getContentHeight() {
return (int)Math.ceil(mContentViewCore.getContentHeightCss());
}
public void setXWalkClient(XWalkClient client) {
if (mNativeContent == 0) return;
mContentsClientBridge.setXWalkClient(client);
}
public void setDownloadListener(XWalkDownloadListenerInternal listener) {
if (mNativeContent == 0) return;
mContentsClientBridge.setDownloadListener(listener);
}
public void setNavigationHandler(XWalkNavigationHandler handler) {
if (mNativeContent == 0) return;
mContentsClientBridge.setNavigationHandler(handler);
}
public void setNotificationService(XWalkNotificationService service) {
if (mNativeContent == 0) return;
mContentsClientBridge.setNotificationService(service);
}
public void onPause() {
if (mNativeContent == 0) return;
mContentViewCore.onHide();
}
public void onResume() {
if (mNativeContent == 0) return;
mContentViewCore.onShow();
}
public boolean onNewIntent(Intent intent) {
if (mNativeContent == 0) return false;
return mContentsClientBridge.onNewIntent(intent);
}
public void clearCache(boolean includeDiskFiles) {
if (mNativeContent == 0) return;
nativeClearCache(mNativeContent, includeDiskFiles);
}
public void clearCacheForSingleFile(final String url) {
if (mNativeContent == 0) return;
if (mIsLoaded == false) {
mXWalkView.post(new Runnable() {
@Override
public void run() {
clearCacheForSingleFile(url);
}
});
return;
}
nativeClearCacheForSingleFile(mNativeContent, url);
}
public void clearHistory() {
if (mNativeContent == 0) return;
mNavigationController.clearHistory();
}
public boolean canGoBack() {
return (mNativeContent == 0) ? false : mNavigationController.canGoBack();
}
public void goBack() {
if (mNativeContent == 0) return;
mNavigationController.goBack();
}
public boolean canGoForward() {
return (mNativeContent == 0) ? false : mNavigationController.canGoForward();
}
public void goForward() {
if (mNativeContent == 0) return;
mNavigationController.goForward();
}
void navigateTo(int offset) {
mNavigationController.goToOffset(offset);
}
public void stopLoading() {
if (mNativeContent == 0) return;
mWebContents.stop();
mContentsClientBridge.onStopLoading();
}
public Bitmap getFavicon() {
if (mNativeContent == 0) return null;
return mContentsClientBridge.getFavicon();
}
// Currently, timer pause/resume is actually
// a global setting. And multiple pause will fail the
// DCHECK in content (content_view_statics.cc:57).
// Here uses a static boolean to avoid this issue.
private static boolean timerPaused = false;
// TODO(Guangzhen): ContentViewStatics will be removed in upstream,
// details in content_view_statics.cc.
// We need follow up after upstream updates that.
public void pauseTimers() {
if (timerPaused || (mNativeContent == 0)) return;
ContentViewStatics.setWebKitSharedTimersSuspended(true);
timerPaused = true;
}
public void resumeTimers() {
if (!timerPaused || (mNativeContent == 0)) return;
ContentViewStatics.setWebKitSharedTimersSuspended(false);
timerPaused = false;
}
public String getOriginalUrl() {
if (mNativeContent == 0) return null;
NavigationHistory history = mNavigationController.getNavigationHistory();
int currentIndex = history.getCurrentEntryIndex();
if (currentIndex >= 0 && currentIndex < history.getEntryCount()) {
return history.getEntryAtIndex(currentIndex).getOriginalUrl();
}
return null;
}
public HitTestData getLastHitTestResult() {
if (mNativeContent == 0) return null;
nativeUpdateLastHitTestData(mNativeContent);
return mPossiblyStaleHitTestData;
}
public String getXWalkVersion() {
if (mNativeContent == 0) return "";
return nativeGetVersion(mNativeContent);
}
private boolean isOpaque(int color) {
return ((color >> 24) & 0xFF) == 0xFF;
}
@CalledByNative
public void setBackgroundColor(final int color) {
if (mNativeContent == 0) return;
if (!mIsLoaded) {
mXWalkView.post(new Runnable() {
@Override
public void run() {
setBackgroundColor(color);
}
});
return;
}
if (isOpaque(color)) {
setOverlayVideoMode(false);
mContentViewCore.setBackgroundOpaque(true);
} else {
setOverlayVideoMode(true);
mContentViewCore.setBackgroundOpaque(false);
}
mContentViewCore.setBackgroundColor(color);
mContentViewRenderView.setSurfaceViewBackgroundColor(color);
nativeSetBackgroundColor(mNativeContent, color);
}
public void setNetworkAvailable(boolean networkUp) {
if (mNativeContent == 0) return;
nativeSetJsOnlineProperty(mNativeContent, networkUp);
}
// For instrumentation test.
public ContentViewCore getContentViewCoreForTest() {
return mContentViewCore;
}
// For instrumentation test.
public void installWebContentsObserverForTest(XWalkContentsClient contentClient) {
if (mNativeContent == 0) return;
contentClient.installWebContentsObserver(mContentViewCore.getWebContents());
}
public String devToolsAgentId() {
if (mNativeContent == 0) return "";
return nativeDevToolsAgentId(mNativeContent);
}
public XWalkSettingsInternal getSettings() {
return mSettings;
}
public void loadAppFromManifest(String url, String data) {
if (mNativeContent == 0 ||
((url == null || url.isEmpty()) &&
(data == null || data.isEmpty()))) {
return;
}
String content = data;
// If the data of manifest.json is not set, try to load it.
if (data == null || data.isEmpty()) {
try {
content = AndroidProtocolHandler.getUrlContent(mXWalkView.getContext(), url);
} catch (IOException e) {
throw new RuntimeException("Failed to read the manifest: " + url);
}
}
// Calculate the base url of manifestUrl. Used by native side.
// TODO(yongsheng): It's from runtime side. Need to find a better way
// to get base url.
String baseUrl = url;
int position = url.lastIndexOf("/");
if (position != -1) {
baseUrl = url.substring(0, position + 1);
} else {
Log.w(TAG, "The url of manifest.json is probably not set correctly.");
}
if (!nativeSetManifest(mNativeContent, baseUrl, content)) {
throw new RuntimeException("Failed to parse the manifest file: " + url);
}
mIsLoaded = true;
}
public void setOriginAccessWhitelist(String url, String[] patterns) {
if (mNativeContent == 0 || TextUtils.isEmpty(url)) return;
// Reset origin access whitelists if pattern is null.
String matchPatterns = "";
if (patterns != null) {
JSONArray arrays = new JSONArray(Arrays.asList(patterns));
matchPatterns = arrays.toString();
}
nativeSetOriginAccessWhitelist(mNativeContent, url, matchPatterns);
}
public XWalkNavigationHistoryInternal getNavigationHistory() {
if (mNativeContent == 0) return null;
return new XWalkNavigationHistoryInternal(mXWalkView, mNavigationController.getNavigationHistory());
}
public static final String SAVE_RESTORE_STATE_KEY = "XWALKVIEW_STATE";
public XWalkNavigationHistoryInternal saveState(Bundle outState) {
if (mNativeContent == 0 || outState == null) return null;
byte[] state = nativeGetState(mNativeContent);
if (state == null) return null;
outState.putByteArray(SAVE_RESTORE_STATE_KEY, state);
return getNavigationHistory();
}
public XWalkNavigationHistoryInternal restoreState(Bundle inState) {
if (mNativeContent == 0 || inState == null) return null;
byte[] state = inState.getByteArray(SAVE_RESTORE_STATE_KEY);
if (state == null) return null;
boolean result = nativeSetState(mNativeContent, state);
// The onUpdateTitle callback normally happens when a page is loaded,
// but is optimized out in the restoreState case because the title is
// already restored. See WebContentsImpl::UpdateTitleForEntry. So we
// call the callback explicitly here.
if (result) mContentsClientBridge.onUpdateTitle(mWebContents.getTitle());
return result ? getNavigationHistory() : null;
}
boolean hasEnteredFullscreen() {
return mContentsClientBridge.hasEnteredFullscreen();
}
void exitFullscreen() {
if (hasEnteredFullscreen()) {
mWebContents.exitFullscreen();
}
}
@CalledByNative
public void onGetUrlFromManifest(String url) {
if (url != null && !url.isEmpty()) {
loadUrl(url);
}
}
@CalledByNative
public void onGetUrlAndLaunchScreenFromManifest(String url, String readyWhen, String imageBorder) {
if (url == null || url.isEmpty()) return;
mLaunchScreenManager.displayLaunchScreen(readyWhen, imageBorder);
mContentsClientBridge.registerPageLoadListener(mLaunchScreenManager);
loadUrl(url);
}
@CalledByNative
public void onGetFullscreenFlagFromManifest(boolean enterFullscreen) {
if (!(mXWalkView.getContext() instanceof Activity)) return;
Activity activity = (Activity) mXWalkView.getContext();
if (enterFullscreen) {
if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
View decorView = activity.getWindow().getDecorView();
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_FULLSCREEN |
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
} else {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
}
}
public void destroy() {
if (mNativeContent == 0) return;
XWalkPreferencesInternal.unload(this);
// Reset existing notification service in order to destruct it.
setNotificationService(null);
// Remove its children used for page rendering from view hierarchy.
mXWalkView.removeView(mContentView);
mXWalkView.removeView(mContentViewRenderView);
mContentViewRenderView.setCurrentContentViewCore(null);
// Destroy the native resources.
mCleanupReference.cleanupNow();
mContentViewRenderView.destroy();
mContentViewCore.destroy();
mCleanupReference = null;
mNativeContent = 0;
}
public int getRoutingID() {
return nativeGetRoutingID(mNativeContent);
}
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
return mContentView.onCreateInputConnectionSuper(outAttrs);
}
public boolean onTouchEvent(MotionEvent event) {
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
// Note this will trigger IPC back to browser even if nothing is
// hit.
nativeRequestNewHitTestDataAt(mNativeContent,
event.getX() / (float) mDIPScale,
event.getY() / (float) mDIPScale,
event.getTouchMajor() / (float) mDIPScale);
}
return mContentViewCore.onTouchEvent(event);
}
public void setOnTouchListener(OnTouchListener l) {
mContentView.setOnTouchListener(l);
}
public void scrollTo(int x, int y) {
mContentView.scrollTo(x, y);
}
public void scrollBy(int x, int y) {
mContentView.scrollBy(x, y);
}
public int computeHorizontalScrollRange() {
return mContentView.computeHorizontalScrollRangeDelegate();
}
public int computeHorizontalScrollOffset() {
return mContentView.computeHorizontalScrollOffsetDelegate();
}
public int computeVerticalScrollRange() {
return mContentView.computeVerticalScrollRangeDelegate();
}
public int computeVerticalScrollOffset() {
return mContentView.computeVerticalScrollOffsetDelegate();
}
public int computeVerticalScrollExtent() {
return mContentView.computeVerticalScrollExtentDelegate();
}
//--------------------------------------------------------------------------------------------
private class XWalkIoThreadClientImpl extends XWalkContentsIoThreadClient {
// All methods are called on the IO thread.
@Override
public int getCacheMode() {
return mSettings.getCacheMode();
}
@Override
public XWalkWebResourceResponseInternal shouldInterceptRequest(
XWalkContentsClient.WebResourceRequestInner request) {
// Notify a resource load is started. This is not the best place to start the callback
// but it's a workable way.
mContentsClientBridge.getCallbackHelper().postOnResourceLoadStarted(request.url);
XWalkWebResourceResponseInternal xwalkWebResourceResponse =
mContentsClientBridge.shouldInterceptRequest(request);
if (xwalkWebResourceResponse == null) {
mContentsClientBridge.getCallbackHelper().postOnLoadResource(request.url);
} else {
if (request.isMainFrame && xwalkWebResourceResponse.getData() == null) {
mContentsClientBridge.getCallbackHelper().postOnReceivedError(
XWalkResourceClientInternal.ERROR_UNKNOWN, null, request.url);
}
}
return xwalkWebResourceResponse;
}
@Override
public boolean shouldBlockContentUrls() {
return !mSettings.getAllowContentAccess();
}
@Override
public boolean shouldBlockFileUrls() {
return !mSettings.getAllowFileAccess();
}
@Override
public boolean shouldBlockNetworkLoads() {
return mSettings.getBlockNetworkLoads();
}
@Override
public void onDownloadStart(String url,
String userAgent,
String contentDisposition,
String mimeType,
long contentLength) {
mContentsClientBridge.getCallbackHelper().postOnDownloadStart(url, userAgent,
contentDisposition, mimeType, contentLength);
}
@Override
public void newLoginRequest(String realm, String account, String args) {
mContentsClientBridge.getCallbackHelper().postOnReceivedLoginRequest(realm, account, args);
}
@Override
public void onReceivedResponseHeaders(XWalkContentsClient.WebResourceRequestInner request,
XWalkWebResourceResponseInternal response) {
mContentsClientBridge.getCallbackHelper().postOnReceivedResponseHeaders(request, response);
}
}
private class XWalkGeolocationCallback implements XWalkGeolocationPermissions.Callback {
@Override
public void invoke(final String origin, final boolean allow, final boolean retain) {
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
if (retain) {
if (allow) {
mGeolocationPermissions.allow(origin);
} else {
mGeolocationPermissions.deny(origin);
}
}
nativeInvokeGeolocationCallback(mNativeContent, allow, origin);
}
});
}
}
@CalledByNative
private void onGeolocationPermissionsShowPrompt(String origin) {
if (mNativeContent == 0) return;
// Reject if geolocation is disabled, or the origin has a retained deny.
if (!mSettings.getGeolocationEnabled()) {
nativeInvokeGeolocationCallback(mNativeContent, false, origin);
return;
}
// Allow if the origin has a retained allow.
if (mGeolocationPermissions.hasOrigin(origin)) {
nativeInvokeGeolocationCallback(mNativeContent,
mGeolocationPermissions.isOriginAllowed(origin),
origin);
return;
}
mContentsClientBridge.onGeolocationPermissionsShowPrompt(
origin, new XWalkGeolocationCallback());
}
@CalledByNative
public void onGeolocationPermissionsHidePrompt() {
mContentsClientBridge.onGeolocationPermissionsHidePrompt();
}
@CalledByNative
private void updateHitTestData(
int type, String extra, String href, String anchorText, String imgSrc) {
mPossiblyStaleHitTestData.hitTestResultType = type;
mPossiblyStaleHitTestData.hitTestResultExtraData = extra;
mPossiblyStaleHitTestData.href = href;
mPossiblyStaleHitTestData.anchorText = anchorText;
mPossiblyStaleHitTestData.imgSrc = imgSrc;
}
public void enableRemoteDebugging() {
// Chrome looks for "devtools_remote" pattern in the name of a unix domain socket
// to identify a debugging page
final String socketName = mViewContext.getApplicationContext().getPackageName() + "_devtools_remote";
if (mDevToolsServer == null) {
mDevToolsServer = new XWalkDevToolsServer(socketName);
mDevToolsServer.setRemoteDebuggingEnabled(
true, XWalkDevToolsServer.Security.ALLOW_SOCKET_ACCESS);
}
}
void disableRemoteDebugging() {
if (mDevToolsServer == null) return;
if (mDevToolsServer.isRemoteDebuggingEnabled()) {
mDevToolsServer.setRemoteDebuggingEnabled(false);
}
mDevToolsServer.destroy();
mDevToolsServer = null;
}
public String getRemoteDebuggingUrl() {
if (mDevToolsServer == null) return "";
// devtools/page is hardcoded in devtools_http_handler_impl.cc (kPageUrlPrefix)
return "ws://" + mDevToolsServer.getSocketName() + "/devtools/page/" + devToolsAgentId();
}
@Override
public void onKeyValueChanged(String key, XWalkPreferencesInternal.PreferenceValue value) {
if (key == null) return;
if (key.equals(XWalkPreferencesInternal.REMOTE_DEBUGGING)) {
if (value.getBooleanValue()) enableRemoteDebugging();
else disableRemoteDebugging();
} else if (key.equals(XWalkPreferencesInternal.ENABLE_JAVASCRIPT)) {
if (mSettings != null) {
mSettings.setJavaScriptEnabled(value.getBooleanValue());
}
} else if (key.equals(XWalkPreferencesInternal.JAVASCRIPT_CAN_OPEN_WINDOW)) {
if (mSettings != null) {
mSettings.setJavaScriptCanOpenWindowsAutomatically(value.getBooleanValue());
}
} else if (key.equals(XWalkPreferencesInternal.ALLOW_UNIVERSAL_ACCESS_FROM_FILE)) {
if (mSettings != null) {
mSettings.setAllowUniversalAccessFromFileURLs(value.getBooleanValue());
}
} else if (key.equals(XWalkPreferencesInternal.SUPPORT_MULTIPLE_WINDOWS)) {
if (mSettings != null) {
mSettings.setSupportMultipleWindows(value.getBooleanValue());
}
} else if (key.equals(XWalkPreferencesInternal.SPATIAL_NAVIGATION)) {
if (mSettings != null) {
mSettings.setSupportSpatialNavigation(value.getBooleanValue());
}
}
}