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.internal;
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.Environment;
17 import android.os.Looper;
18 import android.util.AttributeSet;
19 import android.view.KeyEvent;
20 import android.view.ViewGroup;
21 import android.webkit.ValueCallback;
22 import android.widget.FrameLayout;
25 import java.io.PrintWriter;
26 import java.io.StringWriter;
28 import org.chromium.base.ActivityState;
29 import org.chromium.base.ApplicationStatus;
30 import org.chromium.base.ApplicationStatus.ActivityStateListener;
32 import org.xwalk.core.internal.extension.XWalkExtensionManager;
33 import org.xwalk.core.internal.extension.XWalkPathHelper;
36 * <p>XWalkViewInternal represents an Android view for web apps/pages. Thus most of attributes
37 * for Android view are valid for this class. Since it internally uses
38 * <a href="http://developer.android.com/reference/android/view/SurfaceView.html">
39 * android.view.SurfaceView</a> for rendering web pages by default, it can't be resized,
40 * rotated, transformed and animated due to the limitations of SurfaceView.
41 * Alternatively, if the preference key {@link XWalkPreferencesInternal#ANIMATABLE_XWALK_VIEW}
42 * is set to True, XWalkViewInternal can be transformed and animated because
43 * <a href="http://developer.android.com/reference/android/view/TextureView.html">
44 * TextureView</a> is intentionally used to render web pages for animation support.
45 * Besides, XWalkViewInternal won't be rendered if it's invisible.</p>
47 * <p>XWalkViewInternal needs hardware acceleration to render web pages. As a result, the
48 * AndroidManifest.xml of the caller's app must be appended with the attribute
49 * "android:hardwareAccelerated" and its value must be set as "true".</p>
51 * <application android:name="android.app.Application" android:label="XWalkUsers"
52 * android:hardwareAccelerated="true">
55 * <p>Crosswalk provides 2 major callback classes, namely {@link XWalkResourceClientInternal} and
56 * {@link XWalkUIClientInternal} for listening to the events related to resource loading and UI.
57 * By default, Crosswalk has a default implementation. Callers can override them if needed.</p>
59 * <p>Unlike other Android views, this class has to listen to system events like intents and activity result.
60 * The web engine inside this view need to get and handle them.
61 * With contianer activity's lifecycle change, XWalkViewInternal will pause all timers and other
62 * components like videos when activity paused, resume back them when activity resumed.
63 * When activity is about to destroy, XWalkViewInternal will destroy itself as well.
64 * Embedders can also call onHide() and pauseTimers() to explicitly pause XWalkViewInternal.
65 * Similarily with onShow(), resumeTimers() and onDestroy().
70 * import android.app.Activity;
71 * import android.os.Bundle;
73 * import org.xwalk.core.internal.XWalkResourceClientInternal;
74 * import org.xwalk.core.internal.XWalkUIClientInternal;
75 * import org.xwalk.core.internal.XWalkViewInternal;
77 * public class MyActivity extends Activity {
78 * XWalkViewInternal mXwalkView;
80 * class MyResourceClient extends XWalkResourceClientInternal {
81 * MyResourceClient(XWalkViewInternal view) {
86 * WebResourceResponse shouldInterceptLoadRequest(XWalkViewInternal view, String url) {
92 * class MyUIClient extends XWalkUIClientInternal {
93 * MyUIClient(XWalkViewInternal view) {
98 * void onFullscreenToggled(XWalkViewInternal view, String url) {
105 * protected void onCreate(Bundle savedInstanceState) {
106 * mXwalkView = new XWalkViewInternal(this, null);
107 * setContentView(mXwalkView);
108 * mXwalkView.setResourceClient(new MyResourceClient(mXwalkView));
109 * mXwalkView.setUIClient(new MyUIClient(mXwalkView));
110 * mXwalkView.load("http://www.crosswalk-project.org", null);
114 * protected void onActivityResult(int requestCode, int resultCode, Intent data) {
115 * if (mXwalkView != null) {
116 * mXwalkView.onActivityResult(requestCode, resultCode, data);
121 * protected void onNewIntent(Intent intent) {
122 * if (mXwalkView != null) {
123 * mXwalkView.onNewIntent(intent);
129 public class XWalkViewInternal extends android.widget.FrameLayout
130 implements ActivityStateListener {
132 static final String PLAYSTORE_DETAIL_URI = "market://details?id=";
134 private XWalkContent mContent;
135 private Activity mActivity;
136 private Context mContext;
137 private XWalkExtensionManager mExtensionManager;
138 private boolean mIsHidden;
141 * Normal reload mode as default.
144 public static final int RELOAD_NORMAL = 0;
146 * Reload mode with bypassing the cache.
149 public static final int RELOAD_IGNORE_CACHE = 1;
152 * Constructor for inflating via XML.
153 * @param context a Context object used to access application assets.
154 * @param attrs an AttributeSet passed to our parent.
157 public XWalkViewInternal(Context context, AttributeSet attrs) {
158 super(context, attrs);
162 init(context, attrs);
166 * Constructor for Crosswalk runtime. In shared mode, context isi
167 * different from activity. In embedded mode, they're same.
168 * @param context a Context object used to access application assets
169 * @param activity the activity for this XWalkViewInternal.
172 public XWalkViewInternal(Context context, Activity activity) {
173 super(context, null);
176 // Make sure mActivity is initialized before calling 'init' method.
177 mActivity = activity;
183 * Get the current activity passed from callers. It's never null.
184 * @return the activity instance passed from callers.
188 public Activity getActivity() {
189 if (mActivity != null) {
191 } else if (getContext() instanceof Activity) {
192 return (Activity)getContext();
195 // Never achieve here.
200 // TODO(yongsheng): we should remove this since we have getContext()?
204 public Context getViewContext() {
208 private void init(Context context, AttributeSet attrs) {
209 // Initialize chromium resources. Assign them the correct ids in
211 XWalkInternalResources.resetIds(context);
213 // Intialize library, paks and others.
215 XWalkViewDelegate.init(this);
216 ApplicationStatus.registerStateListenerForActivity(this, getActivity());
217 } catch (Throwable e) {
218 // Try to find if there is UnsatisfiedLinkError in the cause chain of the met Throwable.
219 Throwable linkError = e;
221 if (linkError == null) throw new RuntimeException(e);
222 if (linkError instanceof UnsatisfiedLinkError) break;
223 if (linkError.getCause() == null ||
224 linkError.getCause().equals(linkError)) {
225 throw new RuntimeException(e);
227 linkError = linkError.getCause();
229 final UnsatisfiedLinkError err = (UnsatisfiedLinkError) linkError;
230 final Activity activity = getActivity();
231 final String packageName = context.getPackageName();
232 String missingArch = XWalkViewDelegate.isRunningOnIA() ? "Intel" : "ARM";
233 final String message =
234 context.getString(R.string.cpu_arch_mismatch_message, missingArch);
236 AlertDialog.Builder builder = new AlertDialog.Builder(activity);
237 builder.setTitle(R.string.cpu_arch_mismatch_title)
239 .setOnCancelListener(new DialogInterface.OnCancelListener() {
241 public void onCancel(DialogInterface dialog) {
244 }).setPositiveButton(R.string.goto_store_button_label,
245 new DialogInterface.OnClickListener() {
247 public void onClick(DialogInterface dialog, int which) {
248 activity.startActivity(new Intent(Intent.ACTION_VIEW,
249 Uri.parse(PLAYSTORE_DETAIL_URI + packageName)));
252 }).setNeutralButton(R.string.report_feedback_button_label,
253 new DialogInterface.OnClickListener() {
255 public void onClick(DialogInterface dialog, int which) {
256 ApplicationErrorReport report = new ApplicationErrorReport();
257 report.type = ApplicationErrorReport.TYPE_CRASH;
258 report.packageName = report.processName = packageName;
260 ApplicationErrorReport.CrashInfo crash =
261 new ApplicationErrorReport.CrashInfo();
262 crash.exceptionClassName = err.getClass().getSimpleName();
263 crash.exceptionMessage = "CPU architecture mismatch";
264 StringWriter writer = new StringWriter();
265 PrintWriter print = new PrintWriter(writer);
266 err.printStackTrace(print);
267 crash.stackTrace = writer.toString();
268 StackTraceElement stack = err.getStackTrace()[0];
269 crash.throwClassName = stack.getClassName();
270 crash.throwFileName = stack.getFileName();
271 crash.throwLineNumber = stack.getLineNumber();
272 crash.throwMethodName = stack.getMethodName();
274 report.crashInfo = crash;
275 report.systemApp = false;
276 report.time = System.currentTimeMillis();
278 Intent intent = new Intent(Intent.ACTION_APP_ERROR);
279 intent.putExtra(Intent.EXTRA_BUG_REPORT, report);
280 activity.startActivity(intent);
284 builder.create().show();
288 initXWalkContent(context, attrs);
291 private void initXWalkContent(Context context, AttributeSet attrs) {
293 mContent = new XWalkContent(context, attrs, this);
295 new FrameLayout.LayoutParams(
296 FrameLayout.LayoutParams.MATCH_PARENT,
297 FrameLayout.LayoutParams.MATCH_PARENT));
300 // Set default XWalkClientImpl.
301 setXWalkClient(new XWalkClient(this));
302 // Set default XWalkWebChromeClient and DownloadListener. The default actions
303 // are provided via the following clients if special actions are not needed.
304 setXWalkWebChromeClient(new XWalkWebChromeClient(this));
306 // Set with internal implementation. Could be overwritten by embedders'
308 setUIClient(new XWalkUIClientInternal(this));
309 setResourceClient(new XWalkResourceClientInternal(this));
311 setDownloadListener(new XWalkDownloadListenerImpl(context));
312 setNavigationHandler(new XWalkNavigationHandlerImpl(context));
313 setNotificationService(new XWalkNotificationServiceImpl(context, this));
315 // Enable xwalk extension mechanism and start load extensions here.
316 // Note that it has to be after above initialization.
317 mExtensionManager = new XWalkExtensionManager(context, getActivity());
318 mExtensionManager.loadExtensions();
320 XWalkPathHelper.initialize();
321 XWalkPathHelper.setCacheDirectory(
322 mContext.getApplicationContext().getCacheDir().getPath());
324 String state = Environment.getExternalStorageState();
325 if (Environment.MEDIA_MOUNTED.equals(state) ||
326 Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
327 File extCacheDir = mContext.getApplicationContext().getExternalCacheDir();
328 if (null != extCacheDir) {
329 XWalkPathHelper.setExternalCacheDirectory(extCacheDir.getPath());
335 * Load a web page/app from a given base URL or a content.
336 * If url is null or empty and content is null or empty, then this function
338 * If content is not null, load the web page/app from the content.
339 * If content is not null and the url is not set, return "about:blank" ifi
340 * calling {@link XWalkViewInternal#getUrl()}.
341 * If content is null, try to load the content from the url.
343 * It supports URL schemes like 'http:', 'https:' and 'file:'.
344 * It can also load files from Android assets, e.g. 'file:///android_asset/'.
345 * @param url the url for web page/app.
346 * @param content the content for the web page/app. Could be empty.
349 public void load(String url, String content) {
350 if (mContent == null) return;
352 mContent.loadUrl(url, content);
356 * Load a web app from a given manifest.json file. If content is not null,
357 * load the manifest.json from the content. If content is null, try to load
358 * the manifest.json from the url. Note that url should not be null if the
359 * launched path defined in manifest.json is relative.
361 * It supports URL schemes like 'http:', 'https:' and 'file:'.
362 * It can also load files from Android assets, e.g. 'file:///android_asset/'.
363 * @param url the url for manifest.json.
364 * @param content the content for manifest.json.
367 public void loadAppFromManifest(String url, String content) {
368 if (mContent == null) return;
370 mContent.loadAppFromManifest(url, content);
374 * Reload a web app with a given mode.
375 * @param mode the reload mode.
378 public void reload(int mode) {
379 if (mContent == null) return;
381 mContent.reload(mode);
385 * Stop current loading progress.
388 public void stopLoading() {
389 if (mContent == null) return;
391 mContent.stopLoading();
395 * Get the url of current web page/app. This may be different from what's passed
397 * @return the url for current web page/app.
400 public String getUrl() {
401 if (mContent == null) return null;
403 return mContent.getUrl();
407 * Get the title of current web page/app. This may be different from what's passed
409 * @return the title for current web page/app.
412 public String getTitle() {
413 if (mContent == null) return null;
415 return mContent.getTitle();
419 * Get the original url specified by caller.
420 * @return the original url.
423 public String getOriginalUrl() {
424 if (mContent == null) return null;
426 return mContent.getOriginalUrl();
430 * Get the navigation history for current XWalkViewInternal. It's synchronized with
431 * this XWalkViewInternal if any backward/forward and navigation operations.
432 * @return the navigation history.
435 public XWalkNavigationHistoryInternal getNavigationHistory() {
436 if (mContent == null) return null;
438 return mContent.getNavigationHistory();
442 * Injects the supplied Java object into this XWalkViewInternal.
443 * Each method defined in the class of the object should be
444 * marked with {@link JavascriptInterface} if it's called by JavaScript.
445 * @param object the supplied Java object, called by JavaScript.
446 * @param name the name injected in JavaScript.
449 public void addJavascriptInterface(Object object, String name) {
450 if (mContent == null) return;
452 mContent.addJavascriptInterface(object, name);
456 * Evaluate a fragment of JavaScript code and get the result via callback.
457 * @param script the JavaScript string.
458 * @param callback the callback to handle the evaluated result.
461 public void evaluateJavascript(String script, ValueCallback<String> callback) {
462 if (mContent == null) return;
464 mContent.evaluateJavascript(script, callback);
468 * Clear the resource cache. Note that the cache is per-application, so this
469 * will clear the cache for all XWalkViews used.
470 * @param includeDiskFiles indicate whether to clear disk files for cache.
473 public void clearCache(boolean includeDiskFiles) {
474 if (mContent == null) return;
476 mContent.clearCache(includeDiskFiles);
480 * Indicate that a HTML element is occupying the whole screen.
481 * @return true if any HTML element is occupying the whole screen.
484 public boolean hasEnteredFullscreen() {
485 if (mContent == null) return false;
487 return mContent.hasEnteredFullscreen();
491 * Leave fullscreen mode if it's. Do nothing if it's not
495 public void leaveFullscreen() {
496 if (mContent == null) return;
498 mContent.exitFullscreen();
502 * Pause all layout, parsing and JavaScript timers for all XWalkViewInternal instances.
503 * It will be called when the container Activity get paused. It can also be explicitly
504 * called to pause timers.
506 * Note that it will globally impact all XWalkViewInternal instances, not limited to
507 * just this XWalkViewInternal.
511 public void pauseTimers() {
512 if (mContent == null) return;
514 mContent.pauseTimers();
518 * Resume all layout, parsing and JavaScript timers for all XWalkViewInternal instances.
519 * It will be called when the container Activity get resumed. It can also be explicitly
520 * called to resume timers.
522 * Note that it will globally impact all XWalkViewInternal instances, not limited to
523 * just this XWalkViewInternal.
527 public void resumeTimers() {
528 if (mContent == null) return;
530 mContent.resumeTimers();
534 * Pause many other things except JavaScript timers inside rendering engine,
535 * like video player, modal dialogs, etc. See {@link #pauseTimers} about pausing
537 * It will be called when the container Activity get paused. It can also be explicitly
538 * called to pause above things.
541 public void onHide() {
542 if (mContent == null || mIsHidden) return;
543 mExtensionManager.onPause();
549 * Resume video player, modal dialogs. Embedders are in charge of calling
550 * this during resuming this activity if they call onHide.
551 * Typically it should be called when the activity for this view is resumed.
552 * It will be called when the container Activity get resumed. It can also be explicitly
553 * called to resume above things.
556 public void onShow() {
557 if (mContent == null || !mIsHidden ) return;
558 mExtensionManager.onResume();
564 * Release internal resources occupied by this XWalkViewInternal.
565 * It will be called when the container Activity get destroyed. It can also be explicitly
566 * called to release resources.
569 public void onDestroy() {
574 * Pass through activity result to XWalkViewInternal. Many internal facilities need this
575 * to handle activity result like JavaScript dialog, Crosswalk extensions, etc.
576 * See <a href="http://developer.android.com/reference/android/app/Activity.html">
577 * android.app.Activity.onActivityResult()</a>.
578 * @param requestCode passed from android.app.Activity.onActivityResult().
579 * @param resultCode passed from android.app.Activity.onActivityResult().
580 * @param data passed from android.app.Activity.onActivityResult().
583 public void onActivityResult(int requestCode, int resultCode, Intent data) {
584 if (mContent == null) return;
585 mExtensionManager.onActivityResult(requestCode, resultCode, data);
586 mContent.onActivityResult(requestCode, resultCode, data);
590 * Pass through intents to XWalkViewInternal. Many internal facilities need this
591 * to receive the intents like web notification. See
592 * <a href="http://developer.android.com/reference/android/app/Activity.html">
593 * android.app.Activity.onNewIntent()</a>.
594 * @param intent passed from android.app.Activity.onNewIntent().
597 public boolean onNewIntent(Intent intent) {
598 if (mContent == null) return false;
599 return mContent.onNewIntent(intent);
603 * Save current internal state of this XWalkViewInternal. This can help restore this state
604 * afterwards restoring.
605 * @param outState the saved state for restoring.
608 public boolean saveState(Bundle outState) {
609 if (mContent == null) return false;
610 mContent.saveState(outState);
615 * Restore the state from the saved bundle data.
616 * @param inState the state saved from saveState().
617 * @return true if it can restore the state.
620 public boolean restoreState(Bundle inState) {
621 if (mContent == null) return false;
622 if (mContent.restoreState(inState) != null) return true;
627 * Get the API version of Crosswalk embedding API.
628 * @return the string of API level.
631 // TODO(yongsheng): make it static?
632 public String getAPIVersion() {
637 * Get the Crosswalk version.
638 * @return the string of Crosswalk.
641 // TODO(yongsheng): make it static?
642 public String getXWalkVersion() {
643 if (mContent == null) return null;
644 return mContent.getXWalkVersion();
648 * Embedders use this to customize their handlers to events/callbacks related
650 * @param client the XWalkUIClientInternal defined by callers.
653 public void setUIClient(XWalkUIClientInternal client) {
654 if (mContent == null) return;
656 mContent.setUIClient(client);
660 * Embedders use this to customize their handlers to events/callbacks related
661 * to resource loading.
662 * @param client the XWalkResourceClientInternal defined by callers.
665 public void setResourceClient(XWalkResourceClientInternal client) {
666 if (mContent == null) return;
668 mContent.setResourceClient(client);
671 // TODO(yongsheng): this is not public.
675 public XWalkSettings getSettings() {
676 if (mContent == null) return null;
678 return mContent.getSettings();
682 * This method is used by Cordova for hacking.
683 * TODO(yongsheng): remove this and related test cases?
687 public void setNetworkAvailable(boolean networkUp) {
688 if (mContent == null) return;
690 mContent.setNetworkAvailable(networkUp);
694 * Enables remote debugging and returns the URL at which the dev tools server is listening
695 * for commands. The allowedUid argument can be used to specify the uid of the process that is
696 * permitted to connect.
697 * TODO(yongsheng): how to enable this in XWalkPreferencesInternal?
701 public String enableRemoteDebugging(int allowedUid) {
702 if (mContent == null) return null;
704 return mContent.enableRemoteDebugging(allowedUid);
708 * It's used for Presentation API.
711 public int getContentID() {
712 if (mContent == null) return -1;
713 return mContent.getRoutingID();
716 boolean canGoBack() {
717 if (mContent == null) return false;
719 return mContent.canGoBack();
723 if (mContent == null) return;
728 boolean canGoForward() {
729 if (mContent == null) return false;
731 return mContent.canGoForward();
735 if (mContent == null) return;
737 mContent.goForward();
740 void clearHistory() {
741 if (mContent == null) return;
743 mContent.clearHistory();
747 if (mContent == null) return;
748 mExtensionManager.onDestroy();
750 disableRemoteDebugging();
753 // Enables remote debugging and returns the URL at which the dev tools server is listening
754 // for commands. Only the current process is allowed to connect to the server.
755 String enableRemoteDebugging() {
756 return enableRemoteDebugging(mContext.getApplicationInfo().uid);
759 void disableRemoteDebugging() {
760 if (mContent == null) return;
762 mContent.disableRemoteDebugging();
765 private static void checkThreadSafety() {
766 if (Looper.myLooper() != Looper.getMainLooper()) {
767 Throwable throwable = new Throwable(
768 "Warning: A XWalkViewInternal method was called on thread '" +
769 Thread.currentThread().getName() + "'. " +
770 "All XWalkViewInternal methods must be called on the UI thread. ");
771 throw new RuntimeException(throwable);
775 boolean isOwnerActivityRunning() {
776 int status = ApplicationStatus.getStateForActivity(getActivity());
777 if (status == ActivityState.DESTROYED) return false;
781 void navigateTo(int offset) {
782 if (mContent == null) return;
783 mContent.navigateTo(offset);
786 void setOverlayVideoMode(boolean enabled) {
787 mContent.setOverlayVideoMode(enabled);
790 // Below methods are for test shell and instrumentation tests.
794 public void setXWalkClient(XWalkClient client) {
795 if (mContent == null) return;
797 mContent.setXWalkClient(client);
803 public void setXWalkWebChromeClient(XWalkWebChromeClient client) {
804 if (mContent == null) return;
806 mContent.setXWalkWebChromeClient(client);
812 public void setDownloadListener(DownloadListener listener) {
813 if (mContent == null) return;
815 mContent.setDownloadListener(listener);
821 public void setNavigationHandler(XWalkNavigationHandler handler) {
822 if (mContent == null) return;
824 mContent.setNavigationHandler(handler);
830 public void setNotificationService(XWalkNotificationService service) {
831 if (mContent == null) return;
833 mContent.setNotificationService(service);
840 public boolean dispatchKeyEvent(KeyEvent event) {
841 if (event.getAction() == KeyEvent.ACTION_UP &&
842 event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
843 // If there's navigation happens when app is fullscreen,
844 // the content will still be fullscreen after navigation.
845 // In such case, the back key will exit fullscreen first.
846 if (hasEnteredFullscreen()) {
849 } else if (canGoBack()) {
854 return super.dispatchKeyEvent(event);
861 public void onActivityStateChange(Activity activity, int newState) {
862 assert(getActivity() == activity);
864 case ActivityState.PAUSED:
868 case ActivityState.RESUMED:
872 case ActivityState.DESTROYED: