1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Copyright (c) 2013-2014 Intel Corporation. All rights reserved.
3 // Use of this source code is governed by a BSD-style license that can be
4 // found in the LICENSE file.
6 package org.xwalk.core.internal;
8 import android.app.Activity;
9 import android.content.Context;
10 import android.content.Intent;
11 import android.content.SharedPreferences;
12 import android.graphics.Rect;
13 import android.os.Bundle;
14 import android.text.TextUtils;
15 import android.util.AttributeSet;
16 import android.util.Log;
17 import android.view.ViewGroup;
18 import android.webkit.ValueCallback;
19 import android.webkit.WebResourceResponse;
20 import android.widget.FrameLayout;
22 import java.io.IOException;
23 import java.io.InputStream;
25 import org.chromium.base.CalledByNative;
26 import org.chromium.base.JNINamespace;
27 import org.chromium.base.ThreadUtils;
28 import org.chromium.components.navigation_interception.InterceptNavigationDelegate;
29 import org.chromium.content.browser.ContentView;
30 import org.chromium.content.browser.ContentViewCore;
31 import org.chromium.content.browser.ContentViewRenderView;
32 import org.chromium.content.browser.ContentViewRenderView.CompositingSurfaceType;
33 import org.chromium.content.browser.ContentViewStatics;
34 import org.chromium.content.browser.LoadUrlParams;
35 import org.chromium.content.browser.NavigationHistory;
36 import org.chromium.content.common.CleanupReference;
37 import org.chromium.media.MediaPlayerBridge;
38 import org.chromium.ui.base.ActivityWindowAndroid;
40 import org.xwalk.core.JavascriptInterface;
42 @JNINamespace("xwalk")
44 * This class is the implementation class for XWalkViewInternal by calling internal
47 class XWalkContent extends FrameLayout implements XWalkPreferencesInternal.KeyValueChangeListener {
48 private static String TAG = "XWalkContent";
49 private ContentViewCore mContentViewCore;
50 private ContentView mContentView;
51 private ContentViewRenderView mContentViewRenderView;
52 private ActivityWindowAndroid mWindow;
53 private XWalkDevToolsServer mDevToolsServer;
54 private XWalkViewInternal mXWalkView;
55 private XWalkContentsClientBridge mContentsClientBridge;
56 private XWalkContentsIoThreadClient mIoThreadClient;
57 private XWalkWebContentsDelegateAdapter mXWalkContentsDelegateAdapter;
58 private XWalkSettings mSettings;
59 private XWalkGeolocationPermissions mGeolocationPermissions;
60 private XWalkLaunchScreenManager mLaunchScreenManager;
65 private static final class DestroyRunnable implements Runnable {
66 private final long mXWalkContent;
67 private DestroyRunnable(long nativeXWalkContent) {
68 mXWalkContent = nativeXWalkContent;
73 nativeDestroy(mXWalkContent);
77 // Reference to the active mXWalkContent pointer while it is active use
78 // (ie before it is destroyed).
79 private CleanupReference mCleanupReference;
81 public XWalkContent(Context context, AttributeSet attrs, XWalkViewInternal xwView) {
82 super(context, attrs);
84 // Initialize the WebContensDelegate.
86 mContentsClientBridge = new XWalkContentsClientBridge(mXWalkView);
87 mXWalkContentsDelegateAdapter = new XWalkWebContentsDelegateAdapter(
88 mContentsClientBridge);
89 mIoThreadClient = new XWalkIoThreadClientImpl();
91 // Initialize mWindow which is needed by content
92 mWindow = new ActivityWindowAndroid(xwView.getActivity());
94 // Initialize ContentViewRenderView
95 boolean animated = XWalkPreferencesInternal.getValue(XWalkPreferencesInternal.ANIMATABLE_XWALK_VIEW);
96 CompositingSurfaceType surfaceType =
97 animated ? CompositingSurfaceType.TEXTURE_VIEW : CompositingSurfaceType.SURFACE_VIEW;
98 mContentViewRenderView = new ContentViewRenderView(context, mWindow, surfaceType) {
99 protected void onReadyToRender() {
100 // Anything depending on the underlying Surface readiness should
104 mLaunchScreenManager = new XWalkLaunchScreenManager(context, mXWalkView);
105 mContentViewRenderView.registerFirstRenderedFrameListener(mLaunchScreenManager);
106 addView(mContentViewRenderView,
107 new FrameLayout.LayoutParams(
108 FrameLayout.LayoutParams.MATCH_PARENT,
109 FrameLayout.LayoutParams.MATCH_PARENT));
111 mXWalkContent = nativeInit(mXWalkContentsDelegateAdapter, mContentsClientBridge);
113 // The native side object has been bound to this java instance, so now is the time to
114 // bind all the native->java relationships.
115 mCleanupReference = new CleanupReference(this, new DestroyRunnable(mXWalkContent));
117 mWebContents = nativeGetWebContents(mXWalkContent, mIoThreadClient,
118 mContentsClientBridge.getInterceptNavigationDelegate());
120 // Initialize ContentView.
121 mContentView = ContentView.newInstance(getContext(), mWebContents, mWindow);
122 addView(mContentView,
123 new FrameLayout.LayoutParams(
124 FrameLayout.LayoutParams.MATCH_PARENT,
125 FrameLayout.LayoutParams.MATCH_PARENT));
126 mContentView.getContentViewCore().setContentViewClient(mContentsClientBridge);
128 mContentViewCore = mContentView.getContentViewCore();
129 mContentViewRenderView.setCurrentContentViewCore(mContentViewCore);
130 // For addJavascriptInterface
131 mContentsClientBridge.installWebContentsObserver(mContentViewCore);
133 mContentViewCore.setDownloadDelegate(mContentsClientBridge);
135 // Set the third argument isAccessFromFileURLsGrantedByDefault to false, so that
136 // the members mAllowUniversalAccessFromFileURLs and mAllowFileAccessFromFileURLs
137 // won't be changed from false to true at the same time in the constructor of
138 // XWalkSettings class.
139 mSettings = new XWalkSettings(getContext(), mWebContents, false);
140 // Enable AllowFileAccessFromFileURLs, so that files under file:// path could be
141 // loaded by XMLHttpRequest.
142 mSettings.setAllowFileAccessFromFileURLs(true);
144 SharedPreferences sharedPreferences = new InMemorySharedPreferences();
145 mGeolocationPermissions = new XWalkGeolocationPermissions(sharedPreferences);
147 MediaPlayerBridge.setResourceLoadingFilter(
148 new XWalkMediaPlayerResourceLoadingFilter());
150 XWalkPreferencesInternal.load(this);
153 void doLoadUrl(String url, String content) {
154 // Handle the same url loading by parameters.
155 if (url != null && !url.isEmpty() &&
156 TextUtils.equals(url, mContentViewCore.getUrl())) {
157 mContentViewCore.reload(true);
159 LoadUrlParams params = null;
160 if (content == null || content.isEmpty()) {
161 params = new LoadUrlParams(url);
163 params = LoadUrlParams.createLoadDataParamsWithBaseUrl(
164 content, "text/html", false, url, null);
166 params.setOverrideUserAgent(LoadUrlParams.UA_OVERRIDE_TRUE);
167 mContentViewCore.loadUrl(params);
170 mContentView.requestFocus();
173 public void loadUrl(String url, String data) {
174 if ((url == null || url.isEmpty()) &&
175 (data == null || data.isEmpty())) {
179 doLoadUrl(url, data);
182 public void reload(int mode) {
184 case XWalkViewInternal.RELOAD_IGNORE_CACHE:
185 mContentViewCore.reloadIgnoringCache(true);
187 case XWalkViewInternal.RELOAD_NORMAL:
189 mContentViewCore.reload(true);
193 public String getUrl() {
194 String url = mContentViewCore.getUrl();
195 if (url == null || url.trim().isEmpty()) return null;
199 public String getTitle() {
200 String title = mContentViewCore.getTitle().trim();
201 if (title == null) title = "";
205 public void addJavascriptInterface(Object object, String name) {
206 mContentViewCore.addPossiblyUnsafeJavascriptInterface(object, name,
207 JavascriptInterface.class);
210 public void evaluateJavascript(String script, ValueCallback<String> callback) {
211 final ValueCallback<String> fCallback = callback;
212 ContentViewCore.JavaScriptCallback coreCallback = null;
213 if (fCallback != null) {
214 coreCallback = new ContentViewCore.JavaScriptCallback() {
216 public void handleJavaScriptResult(String jsonResult) {
217 fCallback.onReceiveValue(jsonResult);
221 mContentViewCore.evaluateJavaScript(script, coreCallback);
224 public void setUIClient(XWalkUIClientInternal client) {
225 mContentsClientBridge.setUIClient(client);
228 public void setResourceClient(XWalkResourceClientInternal client) {
229 mContentsClientBridge.setResourceClient(client);
232 public void setXWalkWebChromeClient(XWalkWebChromeClient client) {
233 mContentsClientBridge.setXWalkWebChromeClient(client);
236 public XWalkWebChromeClient getXWalkWebChromeClient() {
237 return mContentsClientBridge.getXWalkWebChromeClient();
240 public void setXWalkClient(XWalkClient client) {
241 mContentsClientBridge.setXWalkClient(client);
244 public void setDownloadListener(DownloadListener listener) {
245 mContentsClientBridge.setDownloadListener(listener);
248 public void setNavigationHandler(XWalkNavigationHandler handler) {
249 mContentsClientBridge.setNavigationHandler(handler);
252 public void setNotificationService(XWalkNotificationService service) {
253 mContentsClientBridge.setNotificationService(service);
256 public void onPause() {
257 mContentViewCore.onHide();
260 public void onResume() {
261 mContentViewCore.onShow();
264 public void onActivityResult(int requestCode, int resultCode, Intent data) {
265 mWindow.onActivityResult(requestCode, resultCode, data);
268 public boolean onNewIntent(Intent intent) {
269 return mContentsClientBridge.onNewIntent(intent);
272 public void clearCache(boolean includeDiskFiles) {
273 if (mXWalkContent == 0) return;
274 nativeClearCache(mXWalkContent, includeDiskFiles);
277 public void clearHistory() {
278 mContentViewCore.clearHistory();
281 public boolean canGoBack() {
282 return mContentViewCore.canGoBack();
285 public void goBack() {
286 mContentViewCore.goBack();
289 public boolean canGoForward() {
290 return mContentViewCore.canGoForward();
293 public void goForward() {
294 mContentViewCore.goForward();
297 void navigateTo(int offset) {
298 mContentViewCore.goToOffset(offset);
301 public void stopLoading() {
302 mContentViewCore.stopLoading();
305 // TODO(Guangzhen): ContentViewStatics will be removed in upstream,
306 // details in content_view_statics.cc.
307 // We need follow up after upstream updates that.
308 public void pauseTimers() {
309 ContentViewStatics.setWebKitSharedTimersSuspended(true);
312 public void resumeTimers() {
313 ContentViewStatics.setWebKitSharedTimersSuspended(false);
316 public String getOriginalUrl() {
317 NavigationHistory history = mContentViewCore.getNavigationHistory();
318 int currentIndex = history.getCurrentEntryIndex();
319 if (currentIndex >= 0 && currentIndex < history.getEntryCount()) {
320 return history.getEntryAtIndex(currentIndex).getOriginalUrl();
325 public String getXWalkVersion() {
326 if (mXWalkContent == 0) return "";
327 return nativeGetVersion(mXWalkContent);
330 public void setNetworkAvailable(boolean networkUp) {
331 if (mXWalkContent == 0) return;
332 nativeSetJsOnlineProperty(mXWalkContent, networkUp);
335 // For instrumentation test.
336 public ContentViewCore getContentViewCoreForTest() {
337 return mContentViewCore;
340 // For instrumentation test.
341 public void installWebContentsObserverForTest(XWalkContentsClient contentClient) {
342 contentClient.installWebContentsObserver(mContentViewCore);
345 public String devToolsAgentId() {
346 if (mXWalkContent == 0) return "";
347 return nativeDevToolsAgentId(mXWalkContent);
350 public XWalkSettings getSettings() {
354 public void loadAppFromManifest(String url, String data) {
355 if (mXWalkContent == 0 ||
356 ((url == null || url.isEmpty()) &&
357 (data == null || data.isEmpty()))) {
361 String content = data;
362 // If the data of manifest.json is not set, try to load it.
363 if (data == null || data.isEmpty()) {
365 content = AndroidProtocolHandler.getUrlContent(mXWalkView.getActivity(), url);
366 } catch (IOException e) {
367 throw new RuntimeException("Failed to read the manifest: " + url);
371 // Calculate the base url of manifestUrl. Used by native side.
372 // TODO(yongsheng): It's from runtime side. Need to find a better way
374 String baseUrl = url;
375 int position = url.lastIndexOf("/");
376 if (position != -1) {
377 baseUrl = url.substring(0, position + 1);
379 Log.w(TAG, "The url of manifest.json is probably not set correctly.");
382 if (!nativeSetManifest(mXWalkContent, baseUrl, content)) {
383 throw new RuntimeException("Failed to parse the manifest file: " + url);
387 public XWalkNavigationHistoryInternal getNavigationHistory() {
388 return new XWalkNavigationHistoryInternal(mXWalkView, mContentViewCore.getNavigationHistory());
391 public static final String SAVE_RESTORE_STATE_KEY = "XWALKVIEW_STATE";
393 public XWalkNavigationHistoryInternal saveState(Bundle outState) {
394 if (outState == null) return null;
396 byte[] state = nativeGetState(mXWalkContent);
397 if (state == null) return null;
399 outState.putByteArray(SAVE_RESTORE_STATE_KEY, state);
400 return getNavigationHistory();
403 public XWalkNavigationHistoryInternal restoreState(Bundle inState) {
404 if (inState == null) return null;
406 byte[] state = inState.getByteArray(SAVE_RESTORE_STATE_KEY);
407 if (state == null) return null;
409 boolean result = nativeSetState(mXWalkContent, state);
411 // The onUpdateTitle callback normally happens when a page is loaded,
412 // but is optimized out in the restoreState case because the title is
413 // already restored. See WebContentsImpl::UpdateTitleForEntry. So we
414 // call the callback explicitly here.
416 mContentsClientBridge.onUpdateTitle(mContentViewCore.getTitle());
419 return result ? getNavigationHistory() : null;
422 boolean hasEnteredFullscreen() {
423 return mContentsClientBridge.hasEnteredFullscreen();
426 void exitFullscreen() {
427 if (hasEnteredFullscreen()) {
428 mContentsClientBridge.exitFullscreen(mWebContents);
433 public void onGetUrlFromManifest(String url) {
434 if (url != null && !url.isEmpty()) {
440 public void onGetUrlAndLaunchScreenFromManifest(String url, String readyWhen, String imageBorder) {
441 if (url == null || url.isEmpty()) return;
442 mLaunchScreenManager.displayLaunchScreen(readyWhen, imageBorder);
443 mContentsClientBridge.registerPageLoadListener(mLaunchScreenManager);
448 public void onGetFullscreenFlagFromManifest(boolean enterFullscreen) {
449 if (enterFullscreen) mContentsClientBridge.onToggleFullscreen(true);
452 public void destroy() {
453 if (mXWalkContent == 0) return;
455 XWalkPreferencesInternal.unload(this);
456 // Reset existing notification service in order to destruct it.
457 setNotificationService(null);
458 // Remove its children used for page rendering from view hierarchy.
459 removeView(mContentView);
460 removeView(mContentViewRenderView);
461 mContentViewRenderView.setCurrentContentViewCore(null);
463 // Destroy the native resources.
464 mContentViewRenderView.destroy();
465 mContentViewCore.destroy();
467 mCleanupReference.cleanupNow();
468 mCleanupReference = null;
472 public int getRoutingID() {
473 return nativeGetRoutingID(mXWalkContent);
476 //--------------------------------------------------------------------------------------------
477 private class XWalkIoThreadClientImpl implements XWalkContentsIoThreadClient {
478 // All methods are called on the IO thread.
481 public int getCacheMode() {
482 return mSettings.getCacheMode();
486 public InterceptedRequestData shouldInterceptRequest(final String url,
487 boolean isMainFrame) {
489 // Notify a resource load is started. This is not the best place to start the callback
490 // but it's a workable way.
491 mContentsClientBridge.getCallbackHelper().postOnResourceLoadStarted(url);
493 WebResourceResponse webResourceResponse = mContentsClientBridge.shouldInterceptRequest(url);
494 InterceptedRequestData interceptedRequestData = null;
496 if (webResourceResponse == null) {
497 mContentsClientBridge.getCallbackHelper().postOnLoadResource(url);
499 if (isMainFrame && webResourceResponse.getData() == null) {
500 mContentsClientBridge.getCallbackHelper().postOnReceivedError(
501 XWalkResourceClientInternal.ERROR_UNKNOWN, null, url);
503 interceptedRequestData = new InterceptedRequestData(webResourceResponse.getMimeType(),
504 webResourceResponse.getEncoding(),
505 webResourceResponse.getData());
507 return interceptedRequestData;
511 public boolean shouldBlockContentUrls() {
512 return !mSettings.getAllowContentAccess();
516 public boolean shouldBlockFileUrls() {
517 return !mSettings.getAllowFileAccess();
521 public boolean shouldBlockNetworkLoads() {
522 return mSettings.getBlockNetworkLoads();
526 public void onDownloadStart(String url,
528 String contentDisposition,
530 long contentLength) {
531 mContentsClientBridge.getCallbackHelper().postOnDownloadStart(url, userAgent,
532 contentDisposition, mimeType, contentLength);
536 public void newLoginRequest(String realm, String account, String args) {
537 mContentsClientBridge.getCallbackHelper().postOnReceivedLoginRequest(realm, account, args);
541 private class XWalkGeolocationCallback implements XWalkGeolocationPermissions.Callback {
543 public void invoke(final String origin, final boolean allow, final boolean retain) {
544 ThreadUtils.runOnUiThread(new Runnable() {
549 mGeolocationPermissions.allow(origin);
551 mGeolocationPermissions.deny(origin);
554 nativeInvokeGeolocationCallback(mXWalkContent, allow, origin);
561 private void onGeolocationPermissionsShowPrompt(String origin) {
562 // Reject if geolocation is disabled, or the origin has a retained deny.
563 if (!mSettings.getGeolocationEnabled()) {
564 nativeInvokeGeolocationCallback(mXWalkContent, false, origin);
567 // Allow if the origin has a retained allow.
568 if (mGeolocationPermissions.hasOrigin(origin)) {
569 nativeInvokeGeolocationCallback(mXWalkContent,
570 mGeolocationPermissions.isOriginAllowed(origin),
574 mContentsClientBridge.onGeolocationPermissionsShowPrompt(
575 origin, new XWalkGeolocationCallback());
579 public void onGeolocationPermissionsHidePrompt() {
580 mContentsClientBridge.onGeolocationPermissionsHidePrompt();
583 public String enableRemoteDebugging(int allowedUid) {
584 // Chrome looks for "devtools_remote" pattern in the name of a unix domain socket
585 // to identify a debugging page
586 final String socketName = getContext().getApplicationContext().getPackageName() + "_devtools_remote";
587 if (mDevToolsServer == null) {
588 mDevToolsServer = new XWalkDevToolsServer(socketName);
589 mDevToolsServer.allowConnectionFromUid(allowedUid);
590 mDevToolsServer.setRemoteDebuggingEnabled(true);
592 // devtools/page is hardcoded in devtools_http_handler_impl.cc (kPageUrlPrefix)
593 return "ws://" + socketName + "/devtools/page/" + devToolsAgentId();
596 // Enables remote debugging and returns the URL at which the dev tools server is listening
597 // for commands. Only the current process is allowed to connect to the server.
598 String enableRemoteDebugging() {
599 return enableRemoteDebugging(getContext().getApplicationInfo().uid);
602 void disableRemoteDebugging() {
603 if (mDevToolsServer == null) return;
605 if (mDevToolsServer.isRemoteDebuggingEnabled()) {
606 mDevToolsServer.setRemoteDebuggingEnabled(false);
608 mDevToolsServer.destroy();
609 mDevToolsServer = null;
613 public void onKeyValueChanged(String key, boolean value) {
614 if (key == XWalkPreferencesInternal.REMOTE_DEBUGGING) {
615 if (value) enableRemoteDebugging();
616 else disableRemoteDebugging();
620 public void setOverlayVideoMode(boolean enabled) {
621 if (mContentViewRenderView != null) {
622 mContentViewRenderView.setOverlayVideoMode(enabled);
626 private native long nativeInit(XWalkWebContentsDelegate webViewContentsDelegate,
627 XWalkContentsClientBridge bridge);
628 private static native void nativeDestroy(long nativeXWalkContent);
629 private native long nativeGetWebContents(long nativeXWalkContent,
630 XWalkContentsIoThreadClient ioThreadClient,
631 InterceptNavigationDelegate delegate);
632 private native void nativeClearCache(long nativeXWalkContent, boolean includeDiskFiles);
633 private native String nativeDevToolsAgentId(long nativeXWalkContent);
634 private native String nativeGetVersion(long nativeXWalkContent);
635 private native void nativeSetJsOnlineProperty(long nativeXWalkContent, boolean networkUp);
636 private native boolean nativeSetManifest(long nativeXWalkContent, String path, String manifest);
637 private native int nativeGetRoutingID(long nativeXWalkContent);
638 private native void nativeInvokeGeolocationCallback(
639 long nativeXWalkContent, boolean value, String requestingFrame);
640 private native byte[] nativeGetState(long nativeXWalkContent);
641 private native boolean nativeSetState(long nativeXWalkContent, byte[] state);