Upstream version 8.36.156.0
[platform/framework/web/crosswalk.git] / src / xwalk / runtime / android / core_internal / src / org / xwalk / core / internal / XWalkContent.java
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.
5
6 package org.xwalk.core.internal;
7
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;
21
22 import java.io.IOException;
23 import java.io.InputStream;
24
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;
39
40 import org.xwalk.core.JavascriptInterface;
41
42 @JNINamespace("xwalk")
43 /**
44  * This class is the implementation class for XWalkViewInternal by calling internal
45  * various classes.
46  */
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;
61
62     long mXWalkContent;
63     long mWebContents;
64
65     private static final class DestroyRunnable implements Runnable {
66         private final long mXWalkContent;
67         private DestroyRunnable(long nativeXWalkContent) {
68             mXWalkContent = nativeXWalkContent;
69         }
70
71         @Override
72         public void run() {
73             nativeDestroy(mXWalkContent);
74         }
75     }
76
77     // Reference to the active mXWalkContent pointer while it is active use
78     // (ie before it is destroyed).
79     private CleanupReference mCleanupReference;
80
81     public XWalkContent(Context context, AttributeSet attrs, XWalkViewInternal xwView) {
82         super(context, attrs);
83
84         // Initialize the WebContensDelegate.
85         mXWalkView = xwView;
86         mContentsClientBridge = new XWalkContentsClientBridge(mXWalkView);
87         mXWalkContentsDelegateAdapter = new XWalkWebContentsDelegateAdapter(
88             mContentsClientBridge);
89         mIoThreadClient = new XWalkIoThreadClientImpl();
90
91         // Initialize mWindow which is needed by content
92         mWindow = new ActivityWindowAndroid(xwView.getActivity());
93
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
101                 // be placed here.
102             }
103         };
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));
110
111         mXWalkContent = nativeInit(mXWalkContentsDelegateAdapter, mContentsClientBridge);
112
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));
116
117         mWebContents = nativeGetWebContents(mXWalkContent, mIoThreadClient,
118                 mContentsClientBridge.getInterceptNavigationDelegate());
119
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);
127
128         mContentViewCore = mContentView.getContentViewCore();
129         mContentViewRenderView.setCurrentContentViewCore(mContentViewCore);
130         // For addJavascriptInterface
131         mContentsClientBridge.installWebContentsObserver(mContentViewCore);
132
133         mContentViewCore.setDownloadDelegate(mContentsClientBridge);
134
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);
143
144         SharedPreferences sharedPreferences = new InMemorySharedPreferences();
145         mGeolocationPermissions = new XWalkGeolocationPermissions(sharedPreferences);
146
147         MediaPlayerBridge.setResourceLoadingFilter(
148                 new XWalkMediaPlayerResourceLoadingFilter());
149
150         XWalkPreferencesInternal.load(this);
151     }
152
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);
158         } else {
159             LoadUrlParams params = null;
160             if (content == null || content.isEmpty()) {
161                 params = new LoadUrlParams(url);
162             } else {
163                 params = LoadUrlParams.createLoadDataParamsWithBaseUrl(
164                         content, "text/html", false, url, null);
165             }
166             params.setOverrideUserAgent(LoadUrlParams.UA_OVERRIDE_TRUE);
167             mContentViewCore.loadUrl(params);
168         }
169
170         mContentView.requestFocus();
171     }
172
173     public void loadUrl(String url, String data) {
174         if ((url == null || url.isEmpty()) &&
175                 (data == null || data.isEmpty())) {
176             return;
177         }
178
179         doLoadUrl(url, data);
180     }
181
182     public void reload(int mode) {
183         switch (mode) {
184             case XWalkViewInternal.RELOAD_IGNORE_CACHE:
185                 mContentViewCore.reloadIgnoringCache(true);
186                 break;
187             case XWalkViewInternal.RELOAD_NORMAL:
188             default:
189                 mContentViewCore.reload(true);
190         }
191     }
192
193     public String getUrl() {
194         String url = mContentViewCore.getUrl();
195         if (url == null || url.trim().isEmpty()) return null;
196         return url;
197     }
198
199     public String getTitle() {
200         String title = mContentViewCore.getTitle().trim();
201         if (title == null) title = "";
202         return title;
203     }
204
205     public void addJavascriptInterface(Object object, String name) {
206         mContentViewCore.addPossiblyUnsafeJavascriptInterface(object, name,
207                 JavascriptInterface.class);
208     }
209
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() {
215                 @Override
216                 public void handleJavaScriptResult(String jsonResult) {
217                     fCallback.onReceiveValue(jsonResult);
218                 }
219             };
220         }
221         mContentViewCore.evaluateJavaScript(script, coreCallback);
222     }
223
224     public void setUIClient(XWalkUIClientInternal client) {
225         mContentsClientBridge.setUIClient(client);
226     }
227
228     public void setResourceClient(XWalkResourceClientInternal client) {
229         mContentsClientBridge.setResourceClient(client);
230     }
231
232     public void setXWalkWebChromeClient(XWalkWebChromeClient client) {
233         mContentsClientBridge.setXWalkWebChromeClient(client);
234     }
235
236     public XWalkWebChromeClient getXWalkWebChromeClient() {
237         return mContentsClientBridge.getXWalkWebChromeClient();
238     }
239
240     public void setXWalkClient(XWalkClient client) {
241         mContentsClientBridge.setXWalkClient(client);
242     }
243
244     public void setDownloadListener(DownloadListener listener) {
245         mContentsClientBridge.setDownloadListener(listener);
246     }
247
248     public void setNavigationHandler(XWalkNavigationHandler handler) {
249         mContentsClientBridge.setNavigationHandler(handler);
250     }
251
252     public void setNotificationService(XWalkNotificationService service) {
253         mContentsClientBridge.setNotificationService(service);
254     }
255
256     public void onPause() {
257         mContentViewCore.onHide();
258     }
259
260     public void onResume() {
261         mContentViewCore.onShow();
262     }
263
264     public void onActivityResult(int requestCode, int resultCode, Intent data) {
265         mWindow.onActivityResult(requestCode, resultCode, data);
266     }
267
268     public boolean onNewIntent(Intent intent) {
269         return mContentsClientBridge.onNewIntent(intent);
270     }
271
272     public void clearCache(boolean includeDiskFiles) {
273         if (mXWalkContent == 0) return;
274         nativeClearCache(mXWalkContent, includeDiskFiles);
275     }
276
277     public void clearHistory() {
278         mContentViewCore.clearHistory();
279     }
280
281     public boolean canGoBack() {
282         return mContentViewCore.canGoBack();
283     }
284
285     public void goBack() {
286         mContentViewCore.goBack();
287     }
288
289     public boolean canGoForward() {
290         return mContentViewCore.canGoForward();
291     }
292
293     public void goForward() {
294         mContentViewCore.goForward();
295     }
296
297     void navigateTo(int offset)  {
298         mContentViewCore.goToOffset(offset);
299     }
300
301     public void stopLoading() {
302         mContentViewCore.stopLoading();
303     }
304
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);
310     }
311
312     public void resumeTimers() {
313         ContentViewStatics.setWebKitSharedTimersSuspended(false);
314     }
315
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();
321         }
322         return null;
323     }
324
325     public String getXWalkVersion() {
326         if (mXWalkContent == 0) return "";
327         return nativeGetVersion(mXWalkContent);
328     }
329
330     public void setNetworkAvailable(boolean networkUp) {
331         if (mXWalkContent == 0) return;
332         nativeSetJsOnlineProperty(mXWalkContent, networkUp);
333     }
334
335     // For instrumentation test.
336     public ContentViewCore getContentViewCoreForTest() {
337         return mContentViewCore;
338     }
339
340     // For instrumentation test.
341     public void installWebContentsObserverForTest(XWalkContentsClient contentClient) {
342         contentClient.installWebContentsObserver(mContentViewCore);
343     }
344
345     public String devToolsAgentId() {
346         if (mXWalkContent == 0) return "";
347         return nativeDevToolsAgentId(mXWalkContent);
348     }
349
350     public XWalkSettings getSettings() {
351         return mSettings;
352     }
353
354     public void loadAppFromManifest(String url, String data) {
355         if (mXWalkContent == 0 ||
356                 ((url == null || url.isEmpty()) &&
357                         (data == null || data.isEmpty()))) {
358             return;
359         }
360
361         String content = data;
362         // If the data of manifest.json is not set, try to load it.
363         if (data == null || data.isEmpty()) {
364             try {
365                 content = AndroidProtocolHandler.getUrlContent(mXWalkView.getActivity(), url);
366             } catch (IOException e) {
367                 throw new RuntimeException("Failed to read the manifest: " + url);
368             }
369         }
370
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
373         // to get base url.
374         String baseUrl = url;
375         int position = url.lastIndexOf("/");
376         if (position != -1) {
377             baseUrl = url.substring(0, position + 1);
378         } else {
379             Log.w(TAG, "The url of manifest.json is probably not set correctly.");
380         }
381
382         if (!nativeSetManifest(mXWalkContent, baseUrl, content)) {
383             throw new RuntimeException("Failed to parse the manifest file: " + url);
384         }
385     }
386
387     public XWalkNavigationHistoryInternal getNavigationHistory() {
388         return new XWalkNavigationHistoryInternal(mXWalkView, mContentViewCore.getNavigationHistory());
389     }
390
391     public static final String SAVE_RESTORE_STATE_KEY = "XWALKVIEW_STATE";
392
393     public XWalkNavigationHistoryInternal saveState(Bundle outState) {
394         if (outState == null) return null;
395
396         byte[] state = nativeGetState(mXWalkContent);
397         if (state == null) return null;
398
399         outState.putByteArray(SAVE_RESTORE_STATE_KEY, state);
400         return getNavigationHistory();
401     }
402
403     public XWalkNavigationHistoryInternal restoreState(Bundle inState) {
404         if (inState == null) return null;
405
406         byte[] state = inState.getByteArray(SAVE_RESTORE_STATE_KEY);
407         if (state == null) return null;
408
409         boolean result = nativeSetState(mXWalkContent, state);
410
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.
415         if (result) {
416             mContentsClientBridge.onUpdateTitle(mContentViewCore.getTitle());
417         }
418
419         return result ? getNavigationHistory() : null;
420     }
421
422     boolean hasEnteredFullscreen() {
423         return mContentsClientBridge.hasEnteredFullscreen();
424     }
425
426     void exitFullscreen() {
427         if (hasEnteredFullscreen()) {
428             mContentsClientBridge.exitFullscreen(mWebContents);
429         }
430     }
431
432     @CalledByNative
433     public void onGetUrlFromManifest(String url) {
434         if (url != null && !url.isEmpty()) {
435             loadUrl(url, null);
436         }
437     }
438
439     @CalledByNative
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);
444         loadUrl(url, null);
445     }
446
447     @CalledByNative
448     public void onGetFullscreenFlagFromManifest(boolean enterFullscreen) {
449         if (enterFullscreen) mContentsClientBridge.onToggleFullscreen(true);
450     }
451
452     public void destroy() {
453         if (mXWalkContent == 0) return;
454
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);
462
463         // Destroy the native resources.
464         mContentViewRenderView.destroy();
465         mContentViewCore.destroy();
466
467         mCleanupReference.cleanupNow();
468         mCleanupReference = null;
469         mXWalkContent = 0;
470     }
471
472     public int getRoutingID() {
473         return nativeGetRoutingID(mXWalkContent);
474     }
475
476     //--------------------------------------------------------------------------------------------
477     private class XWalkIoThreadClientImpl implements XWalkContentsIoThreadClient {
478         // All methods are called on the IO thread.
479
480         @Override
481         public int getCacheMode() {
482             return mSettings.getCacheMode();
483         }
484
485         @Override
486         public InterceptedRequestData shouldInterceptRequest(final String url,
487                 boolean isMainFrame) {
488
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);
492
493             WebResourceResponse webResourceResponse = mContentsClientBridge.shouldInterceptRequest(url);
494             InterceptedRequestData interceptedRequestData = null;
495
496             if (webResourceResponse == null) {
497                 mContentsClientBridge.getCallbackHelper().postOnLoadResource(url);
498             } else {
499                 if (isMainFrame && webResourceResponse.getData() == null) {
500                     mContentsClientBridge.getCallbackHelper().postOnReceivedError(
501                             XWalkResourceClientInternal.ERROR_UNKNOWN, null, url);
502                 }
503                 interceptedRequestData = new InterceptedRequestData(webResourceResponse.getMimeType(),
504                                                                     webResourceResponse.getEncoding(),
505                                                                     webResourceResponse.getData());
506             }
507             return interceptedRequestData;
508         }
509
510         @Override
511         public boolean shouldBlockContentUrls() {
512             return !mSettings.getAllowContentAccess();
513         }
514
515         @Override
516         public boolean shouldBlockFileUrls() {
517             return !mSettings.getAllowFileAccess();
518         }
519
520         @Override
521         public boolean shouldBlockNetworkLoads() {
522             return mSettings.getBlockNetworkLoads();
523         }
524
525         @Override
526         public void onDownloadStart(String url,
527                                     String userAgent,
528                                     String contentDisposition,
529                                     String mimeType,
530                                     long contentLength) {
531             mContentsClientBridge.getCallbackHelper().postOnDownloadStart(url, userAgent,
532                     contentDisposition, mimeType, contentLength);
533         }
534
535         @Override
536         public void newLoginRequest(String realm, String account, String args) {
537             mContentsClientBridge.getCallbackHelper().postOnReceivedLoginRequest(realm, account, args);
538         }
539     }
540
541     private class XWalkGeolocationCallback implements XWalkGeolocationPermissions.Callback {
542         @Override
543         public void invoke(final String origin, final boolean allow, final boolean retain) {
544             ThreadUtils.runOnUiThread(new Runnable() {
545                 @Override
546                 public void run() {
547                     if (retain) {
548                         if (allow) {
549                             mGeolocationPermissions.allow(origin);
550                         } else {
551                             mGeolocationPermissions.deny(origin);
552                         }
553                     }
554                     nativeInvokeGeolocationCallback(mXWalkContent, allow, origin);
555                 }
556             });
557         }
558     }
559
560     @CalledByNative
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);
565             return;
566         }
567         // Allow if the origin has a retained allow.
568         if (mGeolocationPermissions.hasOrigin(origin)) {
569             nativeInvokeGeolocationCallback(mXWalkContent,
570                     mGeolocationPermissions.isOriginAllowed(origin),
571                     origin);
572             return;
573         }
574         mContentsClientBridge.onGeolocationPermissionsShowPrompt(
575                 origin, new XWalkGeolocationCallback());
576     }
577
578     @CalledByNative
579     public void onGeolocationPermissionsHidePrompt() {
580         mContentsClientBridge.onGeolocationPermissionsHidePrompt();
581     }
582
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);
591         }
592         // devtools/page is hardcoded in devtools_http_handler_impl.cc (kPageUrlPrefix)
593         return "ws://" + socketName + "/devtools/page/" + devToolsAgentId();
594     }
595
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);
600     }
601
602     void disableRemoteDebugging() {
603         if (mDevToolsServer ==  null) return;
604
605         if (mDevToolsServer.isRemoteDebuggingEnabled()) {
606             mDevToolsServer.setRemoteDebuggingEnabled(false);
607         }
608         mDevToolsServer.destroy();
609         mDevToolsServer = null;
610     }
611
612     @Override
613     public void onKeyValueChanged(String key, boolean value) {
614         if (key == XWalkPreferencesInternal.REMOTE_DEBUGGING) {
615             if (value) enableRemoteDebugging();
616             else disableRemoteDebugging();
617         }
618     }
619
620     public void setOverlayVideoMode(boolean enabled) {
621         if (mContentViewRenderView != null) {
622             mContentViewRenderView.setOverlayVideoMode(enabled);
623         }
624     }
625
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);
642 }