1 // Copyright (c) 2013-2014 Intel Corporation. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 package org.xwalk.core;
7 import android.app.Activity;
8 import android.app.AlertDialog;
9 import android.app.ApplicationErrorReport;
10 import android.content.Context;
11 import android.content.DialogInterface;
12 import android.content.Intent;
13 import android.graphics.Rect;
14 import android.net.Uri;
15 import android.os.Bundle;
16 import android.os.Looper;
17 import android.util.AttributeSet;
18 import android.view.KeyEvent;
19 import android.view.ViewGroup;
20 import android.webkit.ValueCallback;
21 import android.widget.FrameLayout;
23 import java.io.PrintWriter;
24 import java.io.StringWriter;
26 import org.chromium.base.ActivityState;
27 import org.chromium.base.ApplicationStatus;
29 import org.xwalk.core.extension.XWalkExtensionManager;
32 * <p>XWalkView represents an Android view for web apps/pages. Thus most of attributes
33 * for Android view are valid for this class. Since it internally uses
34 * <a href="http://developer.android.com/reference/android/view/SurfaceView.html">
35 * android.view.SurfaceView</a> for rendering web pages by default, it can't be resized,
36 * rotated, transformed and animated due to the limitations of SurfaceView.
37 * Alternatively, if the preference key {@link XWalkPreferences#ANIMATABLE_XWALK_VIEW}
38 * is set to True, XWalkView can be transformed and animated because
39 * <a href="http://developer.android.com/reference/android/view/TextureView.html">
40 * TextureView</a> is intentionally used to render web pages for animation support.
41 * Besides, XWalkView won't be rendered if it's invisible.</p>
43 * <p>XWalkView needs hardware acceleration to render web pages. As a result, the
44 * AndroidManifest.xml of the caller's app must be appended with the attribute
45 * "android:hardwareAccelerated" and its value must be set as "true".</p>
47 * <application android:name="android.app.Application" android:label="XWalkUsers"
48 * android:hardwareAccelerated="true">
51 * <p>Crosswalk provides 2 major callback classes, namely {@link XWalkResourceClient} and
52 * {@link XWalkUIClient} for listening to the events related to resource loading and UI.
53 * By default, Crosswalk has a default implementation. Callers can override them if needed.</p>
55 * <p>Unlike other Android views, this class has to listen to system events like application life
56 * cycle, intents, and activity result. The web engine inside this view need to get and handle
57 * them. For example:</p>
60 * import android.app.Activity;
61 * import android.os.Bundle;
63 * import org.xwalk.core.XWalkResourceClient;
64 * import org.xwalk.core.XWalkUIClient;
65 * import org.xwalk.core.XWalkView;
67 * public class MyActivity extends Activity {
68 * XWalkView mXwalkView;
70 * class MyResourceClient extends XWalkResourceClient {
71 * MyResourceClient(XWalkView view) {
76 * WebResourceResponse shouldInterceptLoadRequest(XWalkView view, String url) {
82 * class MyUIClient extends XWalkUIClient {
83 * MyUIClient(XWalkView view) {
88 * void onFullscreenToggled(XWalkView view, String url) {
95 * protected void onCreate(Bundle savedInstanceState) {
96 * mXwalkView = new XWalkView(this, null);
97 * setContentView(mXwalkView);
98 * mXwalkView.setResourceClient(new MyResourceClient(mXwalkView));
99 * mXwalkView.setUIClient(new MyUIClient(mXwalkView));
100 * mXwalkView.load("http://www.crosswalk-project.org", null);
104 * protected void onPause() {
106 * if (mXwalkView != null) {
107 * mXwalkView.pauseTimers();
108 * mXwalkView.onHide();
113 * protected void onResume() {
115 * if (mXwalkView != null) {
116 * mXwalkView.resumeTimers();
117 * mXwalkView.onShow();
122 * protected void onDestroy() {
124 * if (mXwalkView != null) {
125 * mXwalkView.onDestroy();
130 * protected void onActivityResult(int requestCode, int resultCode, Intent data) {
131 * if (mXwalkView != null) {
132 * mXwalkView.onActivityResult(requestCode, resultCode, data);
137 * protected void onNewIntent(Intent intent) {
138 * if (mXwalkView != null) {
139 * mXwalkView.onNewIntent(intent);
145 public class XWalkView extends android.widget.FrameLayout {
147 static final String PLAYSTORE_DETAIL_URI = "market://details?id=";
149 private XWalkContent mContent;
150 private Activity mActivity;
151 private Context mContext;
152 private XWalkExtensionManager mExtensionManager;
153 private boolean mIsHidden;
155 /** Normal reload mode as default. */
156 public static final int RELOAD_NORMAL = 0;
157 /** Reload mode with bypassing the cache. */
158 public static final int RELOAD_IGNORE_CACHE = 1;
161 * Constructor for inflating via XML.
162 * @param context a Context object used to access application assets.
163 * @param attrs an AttributeSet passed to our parent.
165 public XWalkView(Context context, AttributeSet attrs) {
166 super(context, attrs);
170 init(context, attrs);
174 * Constructor for Crosswalk runtime. In shared mode, context isi
175 * different from activity. In embedded mode, they're same.
176 * @param context a Context object used to access application assets
177 * @param activity the activity for this XWalkView.
179 public XWalkView(Context context, Activity activity) {
180 super(context, null);
183 // Make sure mActivity is initialized before calling 'init' method.
184 mActivity = activity;
190 * Get the current activity passed from callers. It's never null.
191 * @return the activity instance passed from callers.
195 public Activity getActivity() {
196 if (mActivity != null) {
198 } else if (getContext() instanceof Activity) {
199 return (Activity)getContext();
202 // Never achieve here.
207 // TODO(yongsheng): we should remove this since we have getContext()?
211 public Context getViewContext() {
215 private void init(Context context, AttributeSet attrs) {
216 // Initialize chromium resources. Assign them the correct ids in
218 XWalkInternalResources.resetIds(context);
220 // Intialize library, paks and others.
222 XWalkViewDelegate.init(this);
223 } catch (UnsatisfiedLinkError e) {
224 final UnsatisfiedLinkError err = e;
225 final Activity activity = getActivity();
226 final String packageName = context.getPackageName();
227 String missingArch = XWalkViewDelegate.isRunningOnIA() ? "Intel" : "ARM";
228 final String message =
229 context.getString(R.string.cpu_arch_mismatch_message, missingArch);
231 AlertDialog.Builder builder = new AlertDialog.Builder(activity);
232 builder.setTitle(R.string.cpu_arch_mismatch_title)
234 .setOnCancelListener(new DialogInterface.OnCancelListener() {
236 public void onCancel(DialogInterface dialog) {
239 }).setPositiveButton(R.string.goto_store_button_label,
240 new DialogInterface.OnClickListener() {
242 public void onClick(DialogInterface dialog, int which) {
243 activity.startActivity(new Intent(Intent.ACTION_VIEW,
244 Uri.parse(PLAYSTORE_DETAIL_URI + packageName)));
247 }).setNeutralButton(R.string.report_feedback_button_label,
248 new DialogInterface.OnClickListener() {
250 public void onClick(DialogInterface dialog, int which) {
251 ApplicationErrorReport report = new ApplicationErrorReport();
252 report.type = ApplicationErrorReport.TYPE_CRASH;
253 report.packageName = report.processName = packageName;
255 ApplicationErrorReport.CrashInfo crash =
256 new ApplicationErrorReport.CrashInfo();
257 crash.exceptionClassName = err.getClass().getSimpleName();
258 crash.exceptionMessage = "CPU architecture mismatch";
259 StringWriter writer = new StringWriter();
260 PrintWriter print = new PrintWriter(writer);
261 err.printStackTrace(print);
262 crash.stackTrace = writer.toString();
263 StackTraceElement stack = err.getStackTrace()[0];
264 crash.throwClassName = stack.getClassName();
265 crash.throwFileName = stack.getFileName();
266 crash.throwLineNumber = stack.getLineNumber();
267 crash.throwMethodName = stack.getMethodName();
269 report.crashInfo = crash;
270 report.systemApp = false;
271 report.time = System.currentTimeMillis();
273 Intent intent = new Intent(Intent.ACTION_APP_ERROR);
274 intent.putExtra(Intent.EXTRA_BUG_REPORT, report);
275 activity.startActivity(intent);
279 builder.create().show();
283 initXWalkContent(context, attrs);
286 private void initXWalkContent(Context context, AttributeSet attrs) {
288 mContent = new XWalkContent(context, attrs, this);
290 new FrameLayout.LayoutParams(
291 FrameLayout.LayoutParams.MATCH_PARENT,
292 FrameLayout.LayoutParams.MATCH_PARENT));
295 // Set default XWalkClientImpl.
296 setXWalkClient(new XWalkClient(this));
297 // Set default XWalkWebChromeClient and DownloadListener. The default actions
298 // are provided via the following clients if special actions are not needed.
299 setXWalkWebChromeClient(new XWalkWebChromeClient(this));
301 // Set with internal implementation. Could be overwritten by embedders'
303 setUIClient(new XWalkUIClient(this));
304 setResourceClient(new XWalkResourceClient(this));
306 setDownloadListener(new XWalkDownloadListenerImpl(context));
307 setNavigationHandler(new XWalkNavigationHandlerImpl(context));
308 setNotificationService(new XWalkNotificationServiceImpl(context, this));
310 // Enable xwalk extension mechanism and start load extensions here.
311 // Note that it has to be after above initialization.
312 mExtensionManager = new XWalkExtensionManager(context, getActivity());
313 mExtensionManager.loadExtensions();
317 * Load a web page/app from a given base URL or a content.
318 * If url is null or empty and content is null or empty, then this function
320 * If content is not null, load the web page/app from the content.
321 * If content is not null and the url is not set, return "about:blank" ifi
322 * calling {@link XWalkView#getUrl()}.
323 * If content is null, try to load the content from the url.
325 * It supports URL schemes like 'http:', 'https:' and 'file:'.
326 * It can also load files from Android assets, e.g. 'file:///android_asset/'.
327 * @param url the url for web page/app.
328 * @param content the content for the web page/app. Could be empty.
330 public void load(String url, String content) {
331 if (mContent == null) return;
333 mContent.loadUrl(url, content);
337 * Load a web app from a given manifest.json file. If content is not null,
338 * load the manifest.json from the content. If content is null, try to load
339 * the manifest.json from the url. Note that url should not be null if the
340 * launched path defined in manifest.json is relative.
342 * It supports URL schemes like 'http:', 'https:' and 'file:'.
343 * It can also load files from Android assets, e.g. 'file:///android_asset/'.
344 * @param url the url for manifest.json.
345 * @param content the content for manifest.json.
347 public void loadAppFromManifest(String url, String content) {
348 if (mContent == null) return;
350 mContent.loadAppFromManifest(url, content);
354 * Reload a web app with a given mode.
355 * @param mode the reload mode.
357 public void reload(int mode) {
358 if (mContent == null) return;
360 mContent.reload(mode);
364 * Stop current loading progress.
366 public void stopLoading() {
367 if (mContent == null) return;
369 mContent.stopLoading();
373 * Get the url of current web page/app. This may be different from what's passed
375 * @return the url for current web page/app.
377 public String getUrl() {
378 if (mContent == null) return null;
380 return mContent.getUrl();
384 * Get the title of current web page/app. This may be different from what's passed
386 * @return the title for current web page/app.
388 public String getTitle() {
389 if (mContent == null) return null;
391 return mContent.getTitle();
395 * Get the original url specified by caller.
396 * @return the original url.
398 public String getOriginalUrl() {
399 if (mContent == null) return null;
401 return mContent.getOriginalUrl();
405 * Get the navigation history for current XWalkView. It's synchronized with
406 * this XWalkView if any backward/forward and navigation operations.
407 * @return the navigation history.
409 public XWalkNavigationHistory getNavigationHistory() {
410 if (mContent == null) return null;
412 return mContent.getNavigationHistory();
416 * Injects the supplied Java object into this XWalkView.
417 * Each method defined in the class of the object should be
418 * marked with {@link JavascriptInterface} if it's called by JavaScript.
419 * @param object the supplied Java object, called by JavaScript.
420 * @param name the name injected in JavaScript.
422 public void addJavascriptInterface(Object object, String name) {
423 if (mContent == null) return;
425 mContent.addJavascriptInterface(object, name);
429 * Evaluate a fragment of JavaScript code and get the result via callback.
430 * @param script the JavaScript string.
431 * @param callback the callback to handle the evaluated result.
433 public void evaluateJavascript(String script, ValueCallback<String> callback) {
434 if (mContent == null) return;
436 mContent.evaluateJavascript(script, callback);
440 * Clear the resource cache. Note that the cache is per-application, so this
441 * will clear the cache for all XWalkViews used.
442 * @param includeDiskFiles indicate whether to clear disk files for cache.
444 public void clearCache(boolean includeDiskFiles) {
445 if (mContent == null) return;
447 mContent.clearCache(includeDiskFiles);
451 * Indicate that a HTML element is occupying the whole screen.
452 * @return true if any HTML element is occupying the whole screen.
454 public boolean hasEnteredFullscreen() {
455 if (mContent == null) return false;
457 return mContent.hasEnteredFullscreen();
461 * Leave fullscreen mode if it's. Do nothing if it's not
464 public void leaveFullscreen() {
465 if (mContent == null) return;
467 mContent.exitFullscreen();
471 * Pause all layout, parsing and JavaScript timers for all XWalkView instances.
472 * Typically it should be called when the activity for this view is paused,
473 * and accordingly {@link #resumeTimers} should be called when the activity
476 * Note that it will globally impact all XWalkView instances, not limited to
477 * just this XWalkView.
479 public void pauseTimers() {
480 if (mContent == null) return;
482 mContent.pauseTimers();
486 * Resume all layout, parsing and JavaScript timers for all XWalkView instances.
487 * Typically it should be called when the activity for this view is resumed.
489 * Note that it will globally impact all XWalkView instances, not limited to
490 * just this XWalkView.
492 public void resumeTimers() {
493 if (mContent == null) return;
495 mContent.resumeTimers();
499 * Pause many other things except JavaScript timers inside rendering engine,
500 * like video player, modal dialogs, etc. See {@link #pauseTimers} about pausing
502 * Typically it should be called when the activity for this view is paused.
504 public void onHide() {
505 if (mContent == null || mIsHidden) return;
506 mExtensionManager.onPause();
512 * Resume video player, modal dialogs. Embedders are in charge of calling
513 * this during resuming this activity if they call onHide.
514 * Typically it should be called when the activity for this view is resumed.
516 public void onShow() {
517 if (mContent == null || !mIsHidden ) return;
518 mExtensionManager.onResume();
524 * Release internal resources occupied by this XWalkView.
526 public void onDestroy() {
531 * Pass through activity result to XWalkView. Many internal facilities need this
532 * to handle activity result like JavaScript dialog, Crosswalk extensions, etc.
533 * See <a href="http://developer.android.com/reference/android/app/Activity.html">
534 * android.app.Activity.onActivityResult()</a>.
535 * @param requestCode passed from android.app.Activity.onActivityResult().
536 * @param resultCode passed from android.app.Activity.onActivityResult().
537 * @param data passed from android.app.Activity.onActivityResult().
539 public void onActivityResult(int requestCode, int resultCode, Intent data) {
540 if (mContent == null) return;
541 mExtensionManager.onActivityResult(requestCode, resultCode, data);
542 mContent.onActivityResult(requestCode, resultCode, data);
546 * Pass through intents to XWalkView. Many internal facilities need this
547 * to receive the intents like web notification. See
548 * <a href="http://developer.android.com/reference/android/app/Activity.html">
549 * android.app.Activity.onNewIntent()</a>.
550 * @param intent passed from android.app.Activity.onNewIntent().
552 public boolean onNewIntent(Intent intent) {
553 if (mContent == null) return false;
554 return mContent.onNewIntent(intent);
558 * Save current internal state of this XWalkView. This can help restore this state
559 * afterwards restoring.
560 * @param outState the saved state for restoring.
562 public boolean saveState(Bundle outState) {
563 if (mContent == null) return false;
564 mContent.saveState(outState);
569 * Restore the state from the saved bundle data.
570 * @param inState the state saved from saveState().
571 * @return true if it can restore the state.
573 public boolean restoreState(Bundle inState) {
574 if (mContent == null) return false;
575 if (mContent.restoreState(inState) != null) return true;
580 * Get the API version of Crosswalk embedding API.
581 * @return the string of API level.
583 // TODO(yongsheng): make it static?
584 public String getAPIVersion() {
589 * Get the Crosswalk version.
590 * @return the string of Crosswalk.
592 // TODO(yongsheng): make it static?
593 public String getXWalkVersion() {
594 if (mContent == null) return null;
595 return mContent.getXWalkVersion();
599 * Embedders use this to customize their handlers to events/callbacks related
601 * @param client the XWalkUIClient defined by callers.
603 public void setUIClient(XWalkUIClient client) {
604 if (mContent == null) return;
606 mContent.setUIClient(client);
610 * Embedders use this to customize their handlers to events/callbacks related
611 * to resource loading.
612 * @param client the XWalkResourceClient defined by callers.
614 public void setResourceClient(XWalkResourceClient client) {
615 if (mContent == null) return;
617 mContent.setResourceClient(client);
621 * Inherit from <a href="http://developer.android.com/reference/android/view/View.html">
622 * android.view.View</a>. This class needs to handle some keys like
624 * @param keyCode passed from android.view.View.onKeyUp().
625 * @param event passed from android.view.View.onKeyUp().
628 public boolean onKeyUp(int keyCode, KeyEvent event) {
629 if (keyCode == KeyEvent.KEYCODE_BACK) {
630 // If there's navigation happens when app is fullscreen,
631 // the content will still be fullscreen after navigation.
632 // In such case, the back key will exit fullscreen first.
633 if (hasEnteredFullscreen()) {
636 } else if (canGoBack()) {
644 // TODO(yongsheng): this is not public.
648 public XWalkSettings getSettings() {
649 if (mContent == null) return null;
651 return mContent.getSettings();
655 * This method is used by Cordova for hacking.
656 * TODO(yongsheng): remove this and related test cases?
660 public void setNetworkAvailable(boolean networkUp) {
661 if (mContent == null) return;
663 mContent.setNetworkAvailable(networkUp);
667 * Enables remote debugging and returns the URL at which the dev tools server is listening
668 * for commands. The allowedUid argument can be used to specify the uid of the process that is
669 * permitted to connect.
670 * TODO(yongsheng): how to enable this in XWalkPreferences?
674 public String enableRemoteDebugging(int allowedUid) {
675 if (mContent == null) return null;
677 return mContent.enableRemoteDebugging(allowedUid);
681 * It's used for Presentation API.
684 public int getContentID() {
685 if (mContent == null) return -1;
686 return mContent.getRoutingID();
689 boolean canGoBack() {
690 if (mContent == null) return false;
692 return mContent.canGoBack();
696 if (mContent == null) return;
701 boolean canGoForward() {
702 if (mContent == null) return false;
704 return mContent.canGoForward();
708 if (mContent == null) return;
710 mContent.goForward();
713 void clearHistory() {
714 if (mContent == null) return;
716 mContent.clearHistory();
720 if (mContent == null) return;
721 mExtensionManager.onDestroy();
723 disableRemoteDebugging();
726 // Enables remote debugging and returns the URL at which the dev tools server is listening
727 // for commands. Only the current process is allowed to connect to the server.
728 String enableRemoteDebugging() {
729 return enableRemoteDebugging(mContext.getApplicationInfo().uid);
732 void disableRemoteDebugging() {
733 if (mContent == null) return;
735 mContent.disableRemoteDebugging();
738 private static void checkThreadSafety() {
739 if (Looper.myLooper() != Looper.getMainLooper()) {
740 Throwable throwable = new Throwable(
741 "Warning: A XWalkView method was called on thread '" +
742 Thread.currentThread().getName() + "'. " +
743 "All XWalkView methods must be called on the UI thread. ");
744 throw new RuntimeException(throwable);
748 boolean isOwnerActivityRunning() {
749 int status = ApplicationStatus.getStateForActivity(getActivity());
750 if (status == ActivityState.DESTROYED) return false;
754 void navigateTo(int offset) {
755 if (mContent == null) return;
756 mContent.navigateTo(offset);
759 void setOverlayVideoMode(boolean enabled) {
760 mContent.setOverlayVideoMode(enabled);
763 // Below methods are for test shell and instrumentation tests.
767 public void setXWalkClient(XWalkClient client) {
768 if (mContent == null) return;
770 mContent.setXWalkClient(client);
776 public void setXWalkWebChromeClient(XWalkWebChromeClient client) {
777 if (mContent == null) return;
779 mContent.setXWalkWebChromeClient(client);
785 public void setDownloadListener(DownloadListener listener) {
786 if (mContent == null) return;
788 mContent.setDownloadListener(listener);
794 public void setNavigationHandler(XWalkNavigationHandler handler) {
795 if (mContent == null) return;
797 mContent.setNavigationHandler(handler);
803 public void setNotificationService(XWalkNotificationService service) {
804 if (mContent == null) return;
806 mContent.setNotificationService(service);