/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.webkit; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnCancelListener; import android.database.DataSetObserver; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Picture; import android.graphics.Point; import android.graphics.Rect; import android.graphics.Region; import android.net.http.SslCertificate; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.ServiceManager; import android.os.SystemClock; import android.provider.Checkin; import android.text.IClipboard; import android.text.Selection; import android.text.Spannable; import android.util.AttributeSet; import android.util.EventLog; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.SoundEffectConstants; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.ViewParent; import android.view.ViewTreeObserver; import android.view.animation.AlphaAnimation; import android.view.inputmethod.InputMethodManager; import android.webkit.WebTextView.AutoCompleteAdapter; import android.webkit.WebViewCore.EventHub; import android.widget.AbsoluteLayout; import android.widget.Adapter; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ListView; import android.widget.Scroller; import android.widget.Toast; import android.widget.ZoomButtonsController; import android.widget.ZoomControls; import android.widget.AdapterView.OnItemClickListener; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.List; /** *
A View that displays web pages. This class is the basis upon which you * can roll your own web browser or simply display some online content within your Activity. * It uses the WebKit rendering engine to display * web pages and includes methods to navigate forward and backward * through a history, zoom in and out, perform text searches and more.
*To enable the built-in zoom, set * {@link #getSettings() WebSettings}.{@link WebSettings#setBuiltInZoomControls(boolean)} * (introduced in API version 3). *
Note that, in order for your Activity to access the Internet and load web pages * in a WebView, you must add the INTERNET permissions to your * Android Manifest file:
*<uses-permission android:name="android.permission.INTERNET" />* *
This must be a child of the <manifest>
element.
By default, a WebView provides no browser-like widgets, does not * enable JavaScript and errors will be ignored. If your goal is only * to display some HTML as a part of your UI, this is probably fine; * the user won't need to interact with the web page beyond reading * it, and the web page won't need to interact with the user. If you * actually want a fully blown web browser, then you probably want to * invoke the Browser application with your URL rather than show it * with a WebView. See {@link android.content.Intent} for more information.
* ** WebView webview = new WebView(this); * setContentView(webview); * * // Simplest usage: note that an exception will NOT be thrown * // if there is an error loading this page (see below). * webview.loadUrl("http://slashdot.org/"); * * // Of course you can also load from any string: * String summary = "<html><body>You scored <b>192 points.</body></html>"; * webview.loadData(summary, "text/html", "utf-8"); * // ... although note that there are restrictions on what this HTML can do. * // See the JavaDocs for loadData and loadDataWithBaseUrl for more info. ** *
A WebView has several customization points where you can add your * own behavior. These are:
* *Here's a more complicated example, showing error handling, * settings, and progress notification:
* ** // Let's display the progress in the activity title bar, like the * // browser app does. * getWindow().requestFeature(Window.FEATURE_PROGRESS); * * webview.getSettings().setJavaScriptEnabled(true); * * final Activity activity = this; * webview.setWebChromeClient(new WebChromeClient() { * public void onProgressChanged(WebView view, int progress) { * // Activities and WebViews measure progress with different scales. * // The progress meter will automatically disappear when we reach 100% * activity.setProgress(progress * 1000); * } * }); * webview.setWebViewClient(new WebViewClient() { * public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { * Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show(); * } * }); * * webview.loadUrl("http://slashdot.org/"); ** *
For obvious security reasons, your application has its own * cache, cookie store etc - it does not share the Browser * applications data. Cookies are managed on a separate thread, so * operations like index building don't block the UI * thread. Follow the instructions in {@link android.webkit.CookieSyncManager} * if you want to use cookies in your application. *
* *By default, requests by the HTML to open new windows are * ignored. This is true whether they be opened by JavaScript or by * the target attribute on a link. You can customize your * WebChromeClient to provide your own behaviour for opening multiple windows, * and render them in whatever manner you want.
* *Standard behavior for an Activity is to be destroyed and * recreated when the devices orientation is changed. This will cause * the WebView to reload the current page. If you don't want that, you * can set your Activity to handle the orientation and keyboardHidden * changes, and then just leave the WebView alone. It'll automatically * re-orient itself as appropriate.
*/ public class WebView extends AbsoluteLayout implements ViewTreeObserver.OnGlobalFocusChangeListener, ViewGroup.OnHierarchyChangeListener { // if AUTO_REDRAW_HACK is true, then the CALL key will toggle redrawing // the screen all-the-time. Good for profiling our drawing code static private final boolean AUTO_REDRAW_HACK = false; // true means redraw the screen all-the-time. Only with AUTO_REDRAW_HACK private boolean mAutoRedraw; static final String LOGTAG = "webview"; private static class ExtendedZoomControls extends FrameLayout { public ExtendedZoomControls(Context context, AttributeSet attrs) { super(context, attrs); LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(com.android.internal.R.layout.zoom_magnify, this, true); mPlusMinusZoomControls = (ZoomControls) findViewById( com.android.internal.R.id.zoomControls); mZoomMagnify = (ImageView) findViewById(com.android.internal.R.id.zoomMagnify); } public void show(boolean showZoom, boolean canZoomOut) { mPlusMinusZoomControls.setVisibility( showZoom ? View.VISIBLE : View.GONE); mZoomMagnify.setVisibility(canZoomOut ? View.VISIBLE : View.GONE); fade(View.VISIBLE, 0.0f, 1.0f); } public void hide() { fade(View.GONE, 1.0f, 0.0f); } private void fade(int visibility, float startAlpha, float endAlpha) { AlphaAnimation anim = new AlphaAnimation(startAlpha, endAlpha); anim.setDuration(500); startAnimation(anim); setVisibility(visibility); } public void setIsZoomMagnifyEnabled(boolean isEnabled) { mZoomMagnify.setEnabled(isEnabled); } public boolean hasFocus() { return mPlusMinusZoomControls.hasFocus() || mZoomMagnify.hasFocus(); } public void setOnZoomInClickListener(OnClickListener listener) { mPlusMinusZoomControls.setOnZoomInClickListener(listener); } public void setOnZoomOutClickListener(OnClickListener listener) { mPlusMinusZoomControls.setOnZoomOutClickListener(listener); } public void setOnZoomMagnifyClickListener(OnClickListener listener) { mZoomMagnify.setOnClickListener(listener); } ZoomControls mPlusMinusZoomControls; ImageView mZoomMagnify; } /** * Transportation object for returning WebView across thread boundaries. */ public class WebViewTransport { private WebView mWebview; /** * Set the WebView to the transportation object. * @param webview The WebView to transport. */ public synchronized void setWebView(WebView webview) { mWebview = webview; } /** * Return the WebView object. * @return WebView The transported WebView object. */ public synchronized WebView getWebView() { return mWebview; } } // A final CallbackProxy shared by WebViewCore and BrowserFrame. private final CallbackProxy mCallbackProxy; private final WebViewDatabase mDatabase; // SSL certificate for the main top-level page (if secure) private SslCertificate mCertificate; // Native WebView pointer that is 0 until the native object has been // created. private int mNativeClass; // This would be final but it needs to be set to null when the WebView is // destroyed. private WebViewCore mWebViewCore; // Handler for dispatching UI messages. /* package */ final Handler mPrivateHandler = new PrivateHandler(); private WebTextView mWebTextView; // Used to ignore changes to webkit text that arrives to the UI side after // more key events. private int mTextGeneration; // Used by WebViewCore to create child views. /* package */ final ViewManager mViewManager; /** * Position of the last touch event. */ private float mLastTouchX; private float mLastTouchY; /** * Time of the last touch event. */ private long mLastTouchTime; /** * Time of the last time sending touch event to WebViewCore */ private long mLastSentTouchTime; /** * The minimum elapsed time before sending another ACTION_MOVE event to * WebViewCore. This really should be tuned for each type of the devices. * For example in Google Map api test case, it takes Dream device at least * 150ms to do a full cycle in the WebViewCore by processing a touch event, * triggering the layout and drawing the picture. While the same process * takes 60+ms on the current high speed device. If we make * TOUCH_SENT_INTERVAL too small, there will be multiple touch events sent * to WebViewCore queue and the real layout and draw events will be pushed * to further, which slows down the refresh rate. Choose 50 to favor the * current high speed devices. For Dream like devices, 100 is a better * choice. Maybe make this in the buildspec later. */ private static final int TOUCH_SENT_INTERVAL = 50; /** * Helper class to get velocity for fling */ VelocityTracker mVelocityTracker; private int mMaximumFling; // use this flag to control whether enabling the new double tap zoom static final boolean ENABLE_DOUBLETAP_ZOOM = true; /** * Touch mode */ private int mTouchMode = TOUCH_DONE_MODE; private static final int TOUCH_INIT_MODE = 1; private static final int TOUCH_DRAG_START_MODE = 2; private static final int TOUCH_DRAG_MODE = 3; private static final int TOUCH_SHORTPRESS_START_MODE = 4; private static final int TOUCH_SHORTPRESS_MODE = 5; private static final int TOUCH_DOUBLECLICK_MODE = 6; private static final int TOUCH_DONE_MODE = 7; private static final int TOUCH_SELECT_MODE = 8; // touch mode values specific to scale+scroll private static final int FIRST_SCROLL_ZOOM = 9; private static final int SCROLL_ZOOM_ANIMATION_IN = 9; private static final int SCROLL_ZOOM_ANIMATION_OUT = 10; private static final int SCROLL_ZOOM_OUT = 11; private static final int LAST_SCROLL_ZOOM = 11; // end of touch mode values specific to scale+scroll private static final int TOUCH_DOUBLE_TAP_MODE = 12; // Whether to forward the touch events to WebCore private boolean mForwardTouchEvents = false; // Whether to prevent drag during touch. The initial value depends on // mForwardTouchEvents. If WebCore wants touch events, we assume it will // take control of touch events unless it says no for touch down event. private boolean mPreventDrag; // To keep track of whether the current drag was initiated by a WebTextView, // so that we know not to hide the cursor boolean mDragFromTextInput; // Whether or not to draw the cursor ring. private boolean mDrawCursorRing = true; // true if onPause has been called (and not onResume) private boolean mIsPaused; /** * Customizable constant */ // pre-computed square of ViewConfiguration.getScaledTouchSlop() private int mTouchSlopSquare; // pre-computed square of ViewConfiguration.getScaledDoubleTapSlop() private int mDoubleTapSlopSquare; // pre-computed density adjusted navigation slop private int mNavSlop; // This should be ViewConfiguration.getTapTimeout() // But system time out is 100ms, which is too short for the browser. // In the browser, if it switches out of tap too soon, jump tap won't work. private static final int TAP_TIMEOUT = 200; // This should be ViewConfiguration.getLongPressTimeout() // But system time out is 500ms, which is too short for the browser. // With a short timeout, it's difficult to treat trigger a short press. private static final int LONG_PRESS_TIMEOUT = 1000; // needed to avoid flinging after a pause of no movement private static final int MIN_FLING_TIME = 250; // The time that the Zoom Controls are visible before fading away private static final long ZOOM_CONTROLS_TIMEOUT = ViewConfiguration.getZoomControlsTimeout(); // The amount of content to overlap between two screens when going through // pages with the space bar, in pixels. private static final int PAGE_SCROLL_OVERLAP = 24; /** * These prevent calling requestLayout if either dimension is fixed. This * depends on the layout parameters and the measure specs. */ boolean mWidthCanMeasure; boolean mHeightCanMeasure; // Remember the last dimensions we sent to the native side so we can avoid // sending the same dimensions more than once. int mLastWidthSent; int mLastHeightSent; private int mContentWidth; // cache of value from WebViewCore private int mContentHeight; // cache of value from WebViewCore // Need to have the separate control for horizontal and vertical scrollbar // style than the View's single scrollbar style private boolean mOverlayHorizontalScrollbar = true; private boolean mOverlayVerticalScrollbar = false; // our standard speed. this way small distances will be traversed in less // time than large distances, but we cap the duration, so that very large // distances won't take too long to get there. private static final int STD_SPEED = 480; // pixels per second // time for the longest scroll animation private static final int MAX_DURATION = 750; // milliseconds private Scroller mScroller; private boolean mWrapContent; /** * Private message ids */ private static final int REMEMBER_PASSWORD = 1; private static final int NEVER_REMEMBER_PASSWORD = 2; private static final int SWITCH_TO_SHORTPRESS = 3; private static final int SWITCH_TO_LONGPRESS = 4; private static final int RELEASE_SINGLE_TAP = 5; private static final int REQUEST_FORM_DATA = 6; private static final int SWITCH_TO_CLICK = 7; private static final int RESUME_WEBCORE_UPDATE = 8; //! arg1=x, arg2=y static final int SCROLL_TO_MSG_ID = 10; static final int SCROLL_BY_MSG_ID = 11; //! arg1=x, arg2=y static final int SPAWN_SCROLL_TO_MSG_ID = 12; //! arg1=x, arg2=y static final int SYNC_SCROLL_TO_MSG_ID = 13; static final int NEW_PICTURE_MSG_ID = 14; static final int UPDATE_TEXT_ENTRY_MSG_ID = 15; static final int WEBCORE_INITIALIZED_MSG_ID = 16; static final int UPDATE_TEXTFIELD_TEXT_MSG_ID = 17; static final int MOVE_OUT_OF_PLUGIN = 19; static final int CLEAR_TEXT_ENTRY = 20; static final int UPDATE_TEXT_SELECTION_MSG_ID = 21; static final int UPDATE_CLIPBOARD = 22; static final int LONG_PRESS_CENTER = 23; static final int PREVENT_TOUCH_ID = 24; static final int WEBCORE_NEED_TOUCH_EVENTS = 25; // obj=Rect in doc coordinates static final int INVAL_RECT_MSG_ID = 26; static final int REQUEST_KEYBOARD = 27; static final String[] HandlerDebugString = { "REMEMBER_PASSWORD", // = 1; "NEVER_REMEMBER_PASSWORD", // = 2; "SWITCH_TO_SHORTPRESS", // = 3; "SWITCH_TO_LONGPRESS", // = 4; "RELEASE_SINGLE_TAP", // = 5; "REQUEST_FORM_DATA", // = 6; "SWITCH_TO_CLICK", // = 7; "RESUME_WEBCORE_UPDATE", // = 8; "9", "SCROLL_TO_MSG_ID", // = 10; "SCROLL_BY_MSG_ID", // = 11; "SPAWN_SCROLL_TO_MSG_ID", // = 12; "SYNC_SCROLL_TO_MSG_ID", // = 13; "NEW_PICTURE_MSG_ID", // = 14; "UPDATE_TEXT_ENTRY_MSG_ID", // = 15; "WEBCORE_INITIALIZED_MSG_ID", // = 16; "UPDATE_TEXTFIELD_TEXT_MSG_ID", // = 17; "18", // = 18; "MOVE_OUT_OF_PLUGIN", // = 19; "CLEAR_TEXT_ENTRY", // = 20; "UPDATE_TEXT_SELECTION_MSG_ID", // = 21; "UPDATE_CLIPBOARD", // = 22; "LONG_PRESS_CENTER", // = 23; "PREVENT_TOUCH_ID", // = 24; "WEBCORE_NEED_TOUCH_EVENTS", // = 25; "INVAL_RECT_MSG_ID", // = 26; "REQUEST_KEYBOARD" // = 27; }; // default scale limit. Depending on the display density private static float DEFAULT_MAX_ZOOM_SCALE; private static float DEFAULT_MIN_ZOOM_SCALE; // scale limit, which can be set through viewport meta tag in the web page private float mMaxZoomScale; private float mMinZoomScale; private boolean mMinZoomScaleFixed = true; // initial scale in percent. 0 means using default. private int mInitialScale = 0; // while in the zoom overview mode, the page's width is fully fit to the // current window. The page is alive, in another words, you can click to // follow the links. Double tap will toggle between zoom overview mode and // the last zoom scale. boolean mInZoomOverview = false; // ideally mZoomOverviewWidth should be mContentWidth. But sites like espn, // engadget always have wider mContentWidth no matter what viewport size is. int mZoomOverviewWidth = WebViewCore.DEFAULT_VIEWPORT_WIDTH; float mLastScale; // default scale. Depending on the display density. static int DEFAULT_SCALE_PERCENT; private float mDefaultScale; // set to true temporarily while the zoom control is being dragged private boolean mPreviewZoomOnly = false; // computed scale and inverse, from mZoomWidth. private float mActualScale; private float mInvActualScale; // if this is non-zero, it is used on drawing rather than mActualScale private float mZoomScale; private float mInvInitialZoomScale; private float mInvFinalZoomScale; private int mInitialScrollX; private int mInitialScrollY; private long mZoomStart; private static final int ZOOM_ANIMATION_LENGTH = 500; private boolean mUserScroll = false; private int mSnapScrollMode = SNAP_NONE; private static final int SNAP_NONE = 1; private static final int SNAP_X = 2; private static final int SNAP_Y = 3; private static final int SNAP_X_LOCK = 4; private static final int SNAP_Y_LOCK = 5; private boolean mSnapPositive; // Used to match key downs and key ups private boolean mGotKeyDown; /* package */ static boolean mLogEvent = true; private static final int EVENT_LOG_ZOOM_LEVEL_CHANGE = 70101; private static final int EVENT_LOG_DOUBLE_TAP_DURATION = 70102; // for event log private long mLastTouchUpTime = 0; /** * URI scheme for telephone number */ public static final String SCHEME_TEL = "tel:"; /** * URI scheme for email address */ public static final String SCHEME_MAILTO = "mailto:"; /** * URI scheme for map address */ public static final String SCHEME_GEO = "geo:0,0?q="; private int mBackgroundColor = Color.WHITE; // Used to notify listeners of a new picture. private PictureListener mPictureListener; /** * Interface to listen for new pictures as they change. */ public interface PictureListener { /** * Notify the listener that the picture has changed. * @param view The WebView that owns the picture. * @param picture The new picture. */ public void onNewPicture(WebView view, Picture picture); } // FIXME: Want to make this public, but need to change the API file. public /*static*/ class HitTestResult { /** * Default HitTestResult, where the target is unknown */ public static final int UNKNOWN_TYPE = 0; /** * HitTestResult for hitting a HTML::a tag */ public static final int ANCHOR_TYPE = 1; /** * HitTestResult for hitting a phone number */ public static final int PHONE_TYPE = 2; /** * HitTestResult for hitting a map address */ public static final int GEO_TYPE = 3; /** * HitTestResult for hitting an email address */ public static final int EMAIL_TYPE = 4; /** * HitTestResult for hitting an HTML::img tag */ public static final int IMAGE_TYPE = 5; /** * HitTestResult for hitting a HTML::a tag which contains HTML::img */ public static final int IMAGE_ANCHOR_TYPE = 6; /** * HitTestResult for hitting a HTML::a tag with src=http */ public static final int SRC_ANCHOR_TYPE = 7; /** * HitTestResult for hitting a HTML::a tag with src=http + HTML::img */ public static final int SRC_IMAGE_ANCHOR_TYPE = 8; /** * HitTestResult for hitting an edit text area */ public static final int EDIT_TEXT_TYPE = 9; private int mType; private String mExtra; HitTestResult() { mType = UNKNOWN_TYPE; } private void setType(int type) { mType = type; } private void setExtra(String extra) { mExtra = extra; } public int getType() { return mType; } public String getExtra() { return mExtra; } } // The View containing the zoom controls private ExtendedZoomControls mZoomControls; private Runnable mZoomControlRunnable; private ZoomButtonsController mZoomButtonsController; // These keep track of the center point of the zoom. They are used to // determine the point around which we should zoom. private float mZoomCenterX; private float mZoomCenterY; private ZoomButtonsController.OnZoomListener mZoomListener = new ZoomButtonsController.OnZoomListener() { public void onVisibilityChanged(boolean visible) { if (visible) { switchOutDrawHistory(); updateZoomButtonsEnabled(); } } public void onZoom(boolean zoomIn) { if (zoomIn) { zoomIn(); } else { zoomOut(); } updateZoomButtonsEnabled(); } }; /** * Construct a new WebView with a Context object. * @param context A Context object used to access application assets. */ public WebView(Context context) { this(context, null); } /** * Construct a new WebView with layout parameters. * @param context A Context object used to access application assets. * @param attrs An AttributeSet passed to our parent. */ public WebView(Context context, AttributeSet attrs) { this(context, attrs, com.android.internal.R.attr.webViewStyle); } /** * Construct a new WebView with layout parameters and a default style. * @param context A Context object used to access application assets. * @param attrs An AttributeSet passed to our parent. * @param defStyle The default style resource ID. */ public WebView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); mCallbackProxy = new CallbackProxy(context, this); mWebViewCore = new WebViewCore(context, this, mCallbackProxy); mDatabase = WebViewDatabase.getInstance(context); mScroller = new Scroller(context); mViewManager = new ViewManager(this); mZoomButtonsController = new ZoomButtonsController(this); mZoomButtonsController.setOnZoomListener(mZoomListener); // ZoomButtonsController positions the buttons at the bottom, but in // the middle. Change their layout parameters so they appear on the // right. View controls = mZoomButtonsController.getZoomControls(); ViewGroup.LayoutParams params = controls.getLayoutParams(); if (params instanceof FrameLayout.LayoutParams) { FrameLayout.LayoutParams frameParams = (FrameLayout.LayoutParams) params; frameParams.gravity = Gravity.RIGHT; } } private void updateZoomButtonsEnabled() { boolean canZoomIn = mActualScale < mMaxZoomScale; boolean canZoomOut = mActualScale > mMinZoomScale && !mInZoomOverview; if (!canZoomIn && !canZoomOut) { // Hide the zoom in and out buttons, as well as the fit to page // button, if the page cannot zoom mZoomButtonsController.getZoomControls().setVisibility(View.GONE); } else { // Bring back the hidden zoom controls. mZoomButtonsController.getZoomControls() .setVisibility(View.VISIBLE); // Set each one individually, as a page may be able to zoom in // or out. mZoomButtonsController.setZoomInEnabled(canZoomIn); mZoomButtonsController.setZoomOutEnabled(canZoomOut); } } private void init() { setWillNotDraw(false); setFocusable(true); setFocusableInTouchMode(true); setClickable(true); setLongClickable(true); final ViewConfiguration configuration = ViewConfiguration.get(getContext()); int slop = configuration.getScaledTouchSlop(); mTouchSlopSquare = slop * slop; mMinLockSnapReverseDistance = slop; slop = configuration.getScaledDoubleTapSlop(); mDoubleTapSlopSquare = slop * slop; final float density = getContext().getResources().getDisplayMetrics().density; // use one line height, 16 based on our current default font, for how // far we allow a touch be away from the edge of a link mNavSlop = (int) (16 * density); // density adjusted scale factors DEFAULT_SCALE_PERCENT = (int) (100 * density); mDefaultScale = density; mActualScale = density; mInvActualScale = 1 / density; DEFAULT_MAX_ZOOM_SCALE = 4.0f * density; DEFAULT_MIN_ZOOM_SCALE = 0.25f * density; mMaxZoomScale = DEFAULT_MAX_ZOOM_SCALE; mMinZoomScale = DEFAULT_MIN_ZOOM_SCALE; mMaximumFling = configuration.getScaledMaximumFlingVelocity(); } /* package */void updateDefaultZoomDensity(int zoomDensity) { final float density = getContext().getResources().getDisplayMetrics().density * 100 / zoomDensity; if (Math.abs(density - mDefaultScale) > 0.01) { float scaleFactor = density / mDefaultScale; // adjust the limits mNavSlop = (int) (16 * density); DEFAULT_SCALE_PERCENT = (int) (100 * density); DEFAULT_MAX_ZOOM_SCALE = 4.0f * density; DEFAULT_MIN_ZOOM_SCALE = 0.25f * density; mDefaultScale = density; mMaxZoomScale *= scaleFactor; mMinZoomScale *= scaleFactor; setNewZoomScale(mActualScale * scaleFactor, false); } } /* package */ boolean onSavePassword(String schemePlusHost, String username, String password, final Message resumeMsg) { boolean rVal = false; if (resumeMsg == null) { // null resumeMsg implies saving password silently mDatabase.setUsernamePassword(schemePlusHost, username, password); } else { final Message remember = mPrivateHandler.obtainMessage( REMEMBER_PASSWORD); remember.getData().putString("host", schemePlusHost); remember.getData().putString("username", username); remember.getData().putString("password", password); remember.obj = resumeMsg; final Message neverRemember = mPrivateHandler.obtainMessage( NEVER_REMEMBER_PASSWORD); neverRemember.getData().putString("host", schemePlusHost); neverRemember.getData().putString("username", username); neverRemember.getData().putString("password", password); neverRemember.obj = resumeMsg; new AlertDialog.Builder(getContext()) .setTitle(com.android.internal.R.string.save_password_label) .setMessage(com.android.internal.R.string.save_password_message) .setPositiveButton(com.android.internal.R.string.save_password_notnow, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { resumeMsg.sendToTarget(); } }) .setNeutralButton(com.android.internal.R.string.save_password_remember, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { remember.sendToTarget(); } }) .setNegativeButton(com.android.internal.R.string.save_password_never, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { neverRemember.sendToTarget(); } }) .setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface dialog) { resumeMsg.sendToTarget(); } }).show(); // Return true so that WebViewCore will pause while the dialog is // up. rVal = true; } return rVal; } @Override public void setScrollBarStyle(int style) { if (style == View.SCROLLBARS_INSIDE_INSET || style == View.SCROLLBARS_OUTSIDE_INSET) { mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = false; } else { mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = true; } super.setScrollBarStyle(style); } /** * Specify whether the horizontal scrollbar has overlay style. * @param overlay TRUE if horizontal scrollbar should have overlay style. */ public void setHorizontalScrollbarOverlay(boolean overlay) { mOverlayHorizontalScrollbar = overlay; } /** * Specify whether the vertical scrollbar has overlay style. * @param overlay TRUE if vertical scrollbar should have overlay style. */ public void setVerticalScrollbarOverlay(boolean overlay) { mOverlayVerticalScrollbar = overlay; } /** * Return whether horizontal scrollbar has overlay style * @return TRUE if horizontal scrollbar has overlay style. */ public boolean overlayHorizontalScrollbar() { return mOverlayHorizontalScrollbar; } /** * Return whether vertical scrollbar has overlay style * @return TRUE if vertical scrollbar has overlay style. */ public boolean overlayVerticalScrollbar() { return mOverlayVerticalScrollbar; } /* * Return the width of the view where the content of WebView should render * to. */ private int getViewWidth() { if (!isVerticalScrollBarEnabled() || mOverlayVerticalScrollbar) { return getWidth(); } else { return getWidth() - getVerticalScrollbarWidth(); } } /* * Return the height of the view where the content of WebView should render * to. */ private int getViewHeight() { if (!isHorizontalScrollBarEnabled() || mOverlayHorizontalScrollbar) { return getHeight(); } else { return getHeight() - getHorizontalScrollbarHeight(); } } /** * @return The SSL certificate for the main top-level page or null if * there is no certificate (the site is not secure). */ public SslCertificate getCertificate() { return mCertificate; } /** * Sets the SSL certificate for the main top-level page. */ public void setCertificate(SslCertificate certificate) { // here, the certificate can be null (if the site is not secure) mCertificate = certificate; } //------------------------------------------------------------------------- // Methods called by activity //------------------------------------------------------------------------- /** * Save the username and password for a particular host in the WebView's * internal database. * @param host The host that required the credentials. * @param username The username for the given host. * @param password The password for the given host. */ public void savePassword(String host, String username, String password) { mDatabase.setUsernamePassword(host, username, password); } /** * Set the HTTP authentication credentials for a given host and realm. * * @param host The host for the credentials. * @param realm The realm for the credentials. * @param username The username for the password. If it is null, it means * password can't be saved. * @param password The password */ public void setHttpAuthUsernamePassword(String host, String realm, String username, String password) { mDatabase.setHttpAuthUsernamePassword(host, realm, username, password); } /** * Retrieve the HTTP authentication username and password for a given * host & realm pair * * @param host The host for which the credentials apply. * @param realm The realm for which the credentials apply. * @return String[] if found, String[0] is username, which can be null and * String[1] is password. Return null if it can't find anything. */ public String[] getHttpAuthUsernamePassword(String host, String realm) { return mDatabase.getHttpAuthUsernamePassword(host, realm); } /** * Destroy the internal state of the WebView. This method should be called * after the WebView has been removed from the view system. No other * methods may be called on a WebView after destroy. */ public void destroy() { clearTextEntry(); if (mWebViewCore != null) { // Set the handlers to null before destroying WebViewCore so no // more messages will be posted. mCallbackProxy.setWebViewClient(null); mCallbackProxy.setWebChromeClient(null); // Tell WebViewCore to destroy itself WebViewCore webViewCore = mWebViewCore; mWebViewCore = null; // prevent using partial webViewCore webViewCore.destroy(); // Remove any pending messages that might not be serviced yet. mPrivateHandler.removeCallbacksAndMessages(null); mCallbackProxy.removeCallbacksAndMessages(null); // Wake up the WebCore thread just in case it is waiting for a // javascript dialog. synchronized (mCallbackProxy) { mCallbackProxy.notify(); } } if (mNativeClass != 0) { nativeDestroy(); mNativeClass = 0; } } /** * Enables platform notifications of data state and proxy changes. */ public static void enablePlatformNotifications() { Network.enablePlatformNotifications(); } /** * If platform notifications are enabled, this should be called * from the Activity's onPause() or onStop(). */ public static void disablePlatformNotifications() { Network.disablePlatformNotifications(); } /** * Sets JavaScript engine flags. * * @param flags JS engine flags in a String * * @hide pending API solidification */ public void setJsFlags(String flags) { mWebViewCore.sendMessage(EventHub.SET_JS_FLAGS, flags); } /** * Inform WebView of the network state. This is used to set * the javascript property window.navigator.isOnline and * generates the online/offline event as specified in HTML5, sec. 5.7.7 * @param networkUp boolean indicating if network is available */ public void setNetworkAvailable(boolean networkUp) { mWebViewCore.sendMessage(EventHub.SET_NETWORK_STATE, networkUp ? 1 : 0, 0); } /** * Save the state of this WebView used in * {@link android.app.Activity#onSaveInstanceState}. Please note that this * method no longer stores the display data for this WebView. The previous * behavior could potentially leak files if {@link #restoreState} was never * called. See {@link #savePicture} and {@link #restorePicture} for saving * and restoring the display data. * @param outState The Bundle to store the WebView state. * @return The same copy of the back/forward list used to save the state. If * saveState fails, the returned list will be null. * @see #savePicture * @see #restorePicture */ public WebBackForwardList saveState(Bundle outState) { if (outState == null) { return null; } // We grab a copy of the back/forward list because a client of WebView // may have invalidated the history list by calling clearHistory. WebBackForwardList list = copyBackForwardList(); final int currentIndex = list.getCurrentIndex(); final int size = list.getSize(); // We should fail saving the state if the list is empty or the index is // not in a valid range. if (currentIndex < 0 || currentIndex >= size || size == 0) { return null; } outState.putInt("index", currentIndex); // FIXME: This should just be a byte[][] instead of ArrayList but // Parcel.java does not have the code to handle multi-dimensional // arrays. ArrayList* Note for post 1.0. Due to the change in the WebKit, the access to asset * files through "file:///android_asset/" for the sub resources is more * restricted. If you provide null or empty string as baseUrl, you won't be * able to access asset files. If the baseUrl is anything other than * http(s)/ftp(s)/about/javascript as scheme, you can access asset files for * sub resources. * * @param baseUrl Url to resolve relative paths with, if null defaults to * "about:blank" * @param data A String of data in the given encoding. * @param mimeType The MIMEType of the data. i.e. text/html. If null, * defaults to "text/html" * @param encoding The encoding of the data. i.e. utf-8, us-ascii * @param failUrl URL to use if the content fails to load or null. */ public void loadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, String failUrl) { if (baseUrl != null && baseUrl.toLowerCase().startsWith("data:")) { loadData(data, mimeType, encoding); return; } switchOutDrawHistory(); WebViewCore.BaseUrlData arg = new WebViewCore.BaseUrlData(); arg.mBaseUrl = baseUrl; arg.mData = data; arg.mMimeType = mimeType; arg.mEncoding = encoding; arg.mFailUrl = failUrl; mWebViewCore.sendMessage(EventHub.LOAD_DATA, arg); clearTextEntry(); } /** * Stop the current load. */ public void stopLoading() { // TODO: should we clear all the messages in the queue before sending // STOP_LOADING? switchOutDrawHistory(); mWebViewCore.sendMessage(EventHub.STOP_LOADING); } /** * Reload the current url. */ public void reload() { switchOutDrawHistory(); mWebViewCore.sendMessage(EventHub.RELOAD); } /** * Return true if this WebView has a back history item. * @return True iff this WebView has a back history item. */ public boolean canGoBack() { WebBackForwardList l = mCallbackProxy.getBackForwardList(); synchronized (l) { if (l.getClearPending()) { return false; } else { return l.getCurrentIndex() > 0; } } } /** * Go back in the history of this WebView. */ public void goBack() { goBackOrForward(-1); } /** * Return true if this WebView has a forward history item. * @return True iff this Webview has a forward history item. */ public boolean canGoForward() { WebBackForwardList l = mCallbackProxy.getBackForwardList(); synchronized (l) { if (l.getClearPending()) { return false; } else { return l.getCurrentIndex() < l.getSize() - 1; } } } /** * Go forward in the history of this WebView. */ public void goForward() { goBackOrForward(1); } /** * Return true if the page can go back or forward the given * number of steps. * @param steps The negative or positive number of steps to move the * history. */ public boolean canGoBackOrForward(int steps) { WebBackForwardList l = mCallbackProxy.getBackForwardList(); synchronized (l) { if (l.getClearPending()) { return false; } else { int newIndex = l.getCurrentIndex() + steps; return newIndex >= 0 && newIndex < l.getSize(); } } } /** * Go to the history item that is the number of steps away from * the current item. Steps is negative if backward and positive * if forward. * @param steps The number of steps to take back or forward in the back * forward list. */ public void goBackOrForward(int steps) { goBackOrForward(steps, false); } private void goBackOrForward(int steps, boolean ignoreSnapshot) { // every time we go back or forward, we want to reset the // WebView certificate: // if the new site is secure, we will reload it and get a // new certificate set; // if the new site is not secure, the certificate must be // null, and that will be the case mCertificate = null; if (steps != 0) { clearTextEntry(); mWebViewCore.sendMessage(EventHub.GO_BACK_FORWARD, steps, ignoreSnapshot ? 1 : 0); } } private boolean extendScroll(int y) { int finalY = mScroller.getFinalY(); int newY = pinLocY(finalY + y); if (newY == finalY) return false; mScroller.setFinalY(newY); mScroller.extendDuration(computeDuration(0, y)); return true; } /** * Scroll the contents of the view up by half the view size * @param top true to jump to the top of the page * @return true if the page was scrolled */ public boolean pageUp(boolean top) { if (mNativeClass == 0) { return false; } nativeClearCursor(); // start next trackball movement from page edge if (top) { // go to the top of the document return pinScrollTo(mScrollX, 0, true, 0); } // Page up int h = getHeight(); int y; if (h > 2 * PAGE_SCROLL_OVERLAP) { y = -h + PAGE_SCROLL_OVERLAP; } else { y = -h / 2; } mUserScroll = true; return mScroller.isFinished() ? pinScrollBy(0, y, true, 0) : extendScroll(y); } /** * Scroll the contents of the view down by half the page size * @param bottom true to jump to bottom of page * @return true if the page was scrolled */ public boolean pageDown(boolean bottom) { if (mNativeClass == 0) { return false; } nativeClearCursor(); // start next trackball movement from page edge if (bottom) { return pinScrollTo(mScrollX, mContentHeight, true, 0); } // Page down. int h = getHeight(); int y; if (h > 2 * PAGE_SCROLL_OVERLAP) { y = h - PAGE_SCROLL_OVERLAP; } else { y = h / 2; } mUserScroll = true; return mScroller.isFinished() ? pinScrollBy(0, y, true, 0) : extendScroll(y); } /** * Clear the view so that onDraw() will draw nothing but white background, * and onMeasure() will return 0 if MeasureSpec is not MeasureSpec.EXACTLY */ public void clearView() { mContentWidth = 0; mContentHeight = 0; mWebViewCore.sendMessage(EventHub.CLEAR_CONTENT); } /** * Return a new picture that captures the current display of the webview. * This is a copy of the display, and will be unaffected if the webview * later loads a different URL. * * @return a picture containing the current contents of the view. Note this * picture is of the entire document, and is not restricted to the * bounds of the view. */ public Picture capturePicture() { if (null == mWebViewCore) return null; // check for out of memory tab return mWebViewCore.copyContentPicture(); } /** * Return true if the browser is displaying a TextView for text input. */ private boolean inEditingMode() { return mWebTextView != null && mWebTextView.getParent() != null && mWebTextView.hasFocus(); } private void clearTextEntry() { if (inEditingMode()) { mWebTextView.remove(); } } /** * Return the current scale of the WebView * @return The current scale. */ public float getScale() { return mActualScale; } /** * Set the initial scale for the WebView. 0 means default. If * {@link WebSettings#getUseWideViewPort()} is true, it zooms out all the * way. Otherwise it starts with 100%. If initial scale is greater than 0, * WebView starts will this value as initial scale. * * @param scaleInPercent The initial scale in percent. */ public void setInitialScale(int scaleInPercent) { mInitialScale = scaleInPercent; } /** * Invoke the graphical zoom picker widget for this WebView. This will * result in the zoom widget appearing on the screen to control the zoom * level of this WebView. */ public void invokeZoomPicker() { if (!getSettings().supportZoom()) { Log.w(LOGTAG, "This WebView doesn't support zoom."); return; } clearTextEntry(); if (getSettings().getBuiltInZoomControls()) { mZoomButtonsController.setVisible(true); } else { mPrivateHandler.removeCallbacks(mZoomControlRunnable); mPrivateHandler.postDelayed(mZoomControlRunnable, ZOOM_CONTROLS_TIMEOUT); } } /** * Return a HitTestResult based on the current cursor node. If a HTML::a tag * is found and the anchor has a non-javascript url, the HitTestResult type * is set to SRC_ANCHOR_TYPE and the url is set in the "extra" field. If the * anchor does not have a url or if it is a javascript url, the type will * be UNKNOWN_TYPE and the url has to be retrieved through * {@link #requestFocusNodeHref} asynchronously. If a HTML::img tag is * found, the HitTestResult type is set to IMAGE_TYPE and the url is set in * the "extra" field. A type of * SRC_IMAGE_ANCHOR_TYPE indicates an anchor with a url that has an image as * a child node. If a phone number is found, the HitTestResult type is set * to PHONE_TYPE and the phone number is set in the "extra" field of * HitTestResult. If a map address is found, the HitTestResult type is set * to GEO_TYPE and the address is set in the "extra" field of HitTestResult. * If an email address is found, the HitTestResult type is set to EMAIL_TYPE * and the email is set in the "extra" field of HitTestResult. Otherwise, * HitTestResult type is set to UNKNOWN_TYPE. */ public HitTestResult getHitTestResult() { if (mNativeClass == 0) { return null; } HitTestResult result = new HitTestResult(); if (nativeHasCursorNode()) { if (nativeCursorIsTextInput()) { result.setType(HitTestResult.EDIT_TEXT_TYPE); } else { String text = nativeCursorText(); if (text != null) { if (text.startsWith(SCHEME_TEL)) { result.setType(HitTestResult.PHONE_TYPE); result.setExtra(text.substring(SCHEME_TEL.length())); } else if (text.startsWith(SCHEME_MAILTO)) { result.setType(HitTestResult.EMAIL_TYPE); result.setExtra(text.substring(SCHEME_MAILTO.length())); } else if (text.startsWith(SCHEME_GEO)) { result.setType(HitTestResult.GEO_TYPE); result.setExtra(URLDecoder.decode(text .substring(SCHEME_GEO.length()))); } else if (nativeCursorIsAnchor()) { result.setType(HitTestResult.SRC_ANCHOR_TYPE); result.setExtra(text); } } } } int type = result.getType(); if (type == HitTestResult.UNKNOWN_TYPE || type == HitTestResult.SRC_ANCHOR_TYPE) { // Now check to see if it is an image. int contentX = viewToContent((int) mLastTouchX + mScrollX); int contentY = viewToContent((int) mLastTouchY + mScrollY); String text = nativeImageURI(contentX, contentY); if (text != null) { result.setType(type == HitTestResult.UNKNOWN_TYPE ? HitTestResult.IMAGE_TYPE : HitTestResult.SRC_IMAGE_ANCHOR_TYPE); result.setExtra(text); } } return result; } /** * Request the href of an anchor element due to getFocusNodePath returning * "href." If hrefMsg is null, this method returns immediately and does not * dispatch hrefMsg to its target. * * @param hrefMsg This message will be dispatched with the result of the * request as the data member with "url" as key. The result can * be null. */ // FIXME: API change required to change the name of this function. We now // look at the cursor node, and not the focus node. Also, what is // getFocusNodePath? public void requestFocusNodeHref(Message hrefMsg) { if (hrefMsg == null || mNativeClass == 0) { return; } if (nativeCursorIsAnchor()) { mWebViewCore.sendMessage(EventHub.REQUEST_CURSOR_HREF, nativeCursorFramePointer(), nativeCursorNodePointer(), hrefMsg); } } /** * Request the url of the image last touched by the user. msg will be sent * to its target with a String representing the url as its object. * * @param msg This message will be dispatched with the result of the request * as the data member with "url" as key. The result can be null. */ public void requestImageRef(Message msg) { int contentX = viewToContent((int) mLastTouchX + mScrollX); int contentY = viewToContent((int) mLastTouchY + mScrollY); String ref = nativeImageURI(contentX, contentY); Bundle data = msg.getData(); data.putString("url", ref); msg.setData(data); msg.sendToTarget(); } private static int pinLoc(int x, int viewMax, int docMax) { // Log.d(LOGTAG, "-- pinLoc " + x + " " + viewMax + " " + docMax); if (docMax < viewMax) { // the doc has room on the sides for "blank" // pin the short document to the top/left of the screen x = 0; // Log.d(LOGTAG, "--- center " + x); } else if (x < 0) { x = 0; // Log.d(LOGTAG, "--- zero"); } else if (x + viewMax > docMax) { x = docMax - viewMax; // Log.d(LOGTAG, "--- pin " + x); } return x; } // Expects x in view coordinates private int pinLocX(int x) { return pinLoc(x, getViewWidth(), computeHorizontalScrollRange()); } // Expects y in view coordinates private int pinLocY(int y) { return pinLoc(y, getViewHeight(), computeVerticalScrollRange()); } /*package*/ int viewToContent(int x) { return Math.round(x * mInvActualScale); } /*package*/ int contentToView(int x) { return Math.round(x * mActualScale); } // Called by JNI to invalidate the View, given rectangle coordinates in // content space private void viewInvalidate(int l, int t, int r, int b) { invalidate(contentToView(l), contentToView(t), contentToView(r), contentToView(b)); } // Called by JNI to invalidate the View after a delay, given rectangle // coordinates in content space private void viewInvalidateDelayed(long delay, int l, int t, int r, int b) { postInvalidateDelayed(delay, contentToView(l), contentToView(t), contentToView(r), contentToView(b)); } private Rect contentToView(Rect x) { return new Rect(contentToView(x.left), contentToView(x.top) , contentToView(x.right), contentToView(x.bottom)); } /* call from webcoreview.draw(), so we're still executing in the UI thread */ private void recordNewContentSize(int w, int h, boolean updateLayout) { // premature data from webkit, ignore if ((w | h) == 0) { return; } // don't abort a scroll animation if we didn't change anything if (mContentWidth != w || mContentHeight != h) { // record new dimensions mContentWidth = w; mContentHeight = h; // If history Picture is drawn, don't update scroll. They will be // updated when we get out of that mode. if (!mDrawHistory) { // repin our scroll, taking into account the new content size int oldX = mScrollX; int oldY = mScrollY; mScrollX = pinLocX(mScrollX); mScrollY = pinLocY(mScrollY); // android.util.Log.d("skia", "recordNewContentSize - // abortAnimation"); mScroller.abortAnimation(); // just in case if (oldX != mScrollX || oldY != mScrollY) { sendOurVisibleRect(); } } } contentSizeChanged(updateLayout); } private void setNewZoomScale(float scale, boolean force) { if (scale < mMinZoomScale) { scale = mMinZoomScale; } else if (scale > mMaxZoomScale) { scale = mMaxZoomScale; } if (scale != mActualScale || force) { if (mDrawHistory) { // If history Picture is drawn, don't update scroll. They will // be updated when we get out of that mode. if (scale != mActualScale && !mPreviewZoomOnly) { mCallbackProxy.onScaleChanged(mActualScale, scale); } mActualScale = scale; mInvActualScale = 1 / scale; if (!mPreviewZoomOnly) { sendViewSizeZoom(); } } else { // update our scroll so we don't appear to jump // i.e. keep the center of the doc in the center of the view int oldX = mScrollX; int oldY = mScrollY; float ratio = scale * mInvActualScale; // old inverse float sx = ratio * oldX + (ratio - 1) * mZoomCenterX; float sy = ratio * oldY + (ratio - 1) * mZoomCenterY; // now update our new scale and inverse if (scale != mActualScale && !mPreviewZoomOnly) { mCallbackProxy.onScaleChanged(mActualScale, scale); } mActualScale = scale; mInvActualScale = 1 / scale; // Scale all the child views mViewManager.scaleAll(); // as we don't have animation for scaling, don't do animation // for scrolling, as it causes weird intermediate state // pinScrollTo(Math.round(sx), Math.round(sy)); mScrollX = pinLocX(Math.round(sx)); mScrollY = pinLocY(Math.round(sy)); if (!mPreviewZoomOnly) { sendViewSizeZoom(); sendOurVisibleRect(); } } } } // Used to avoid sending many visible rect messages. private Rect mLastVisibleRectSent; private Rect mLastGlobalRect; private Rect sendOurVisibleRect() { Rect rect = new Rect(); calcOurContentVisibleRect(rect); // Rect.equals() checks for null input. if (!rect.equals(mLastVisibleRectSent)) { Point pos = new Point(rect.left, rect.top); mWebViewCore.sendMessage(EventHub.SET_SCROLL_OFFSET, nativeMoveGeneration(), 0, pos); mLastVisibleRectSent = rect; } Rect globalRect = new Rect(); if (getGlobalVisibleRect(globalRect) && !globalRect.equals(mLastGlobalRect)) { if (DebugFlags.WEB_VIEW) { Log.v(LOGTAG, "sendOurVisibleRect=(" + globalRect.left + "," + globalRect.top + ",r=" + globalRect.right + ",b=" + globalRect.bottom); } // TODO: the global offset is only used by windowRect() // in ChromeClientAndroid ; other clients such as touch // and mouse events could return view + screen relative points. mWebViewCore.sendMessage(EventHub.SET_GLOBAL_BOUNDS, globalRect); mLastGlobalRect = globalRect; } return rect; } // Sets r to be the visible rectangle of our webview in view coordinates private void calcOurVisibleRect(Rect r) { Point p = new Point(); getGlobalVisibleRect(r, p); r.offset(-p.x, -p.y); if (mFindIsUp) { r.bottom -= FIND_HEIGHT; } } // Sets r to be our visible rectangle in content coordinates private void calcOurContentVisibleRect(Rect r) { calcOurVisibleRect(r); r.left = viewToContent(r.left); r.top = viewToContent(r.top); r.right = viewToContent(r.right); r.bottom = viewToContent(r.bottom); } static class ViewSizeData { int mWidth; int mHeight; int mTextWrapWidth; float mScale; } /** * Compute unzoomed width and height, and if they differ from the last * values we sent, send them to webkit (to be used has new viewport) * * @return true if new values were sent */ private boolean sendViewSizeZoom() { int viewWidth = getViewWidth(); int newWidth = Math.round(viewWidth * mInvActualScale); int newHeight = Math.round(getViewHeight() * mInvActualScale); /* * Because the native side may have already done a layout before the * View system was able to measure us, we have to send a height of 0 to * remove excess whitespace when we grow our width. This will trigger a * layout and a change in content size. This content size change will * mean that contentSizeChanged will either call this method directly or * indirectly from onSizeChanged. */ if (newWidth > mLastWidthSent && mWrapContent) { newHeight = 0; } // Avoid sending another message if the dimensions have not changed. if (newWidth != mLastWidthSent || newHeight != mLastHeightSent) { ViewSizeData data = new ViewSizeData(); data.mWidth = newWidth; data.mHeight = newHeight; // while in zoom overview mode, the text are wrapped to the screen // width matching mLastScale. So that we don't trigger re-flow while // toggling between overview mode and normal mode. data.mTextWrapWidth = mInZoomOverview ? Math.round(viewWidth / mLastScale) : newWidth; data.mScale = mActualScale; mWebViewCore.sendMessage(EventHub.VIEW_SIZE_CHANGED, data); mLastWidthSent = newWidth; mLastHeightSent = newHeight; return true; } return false; } @Override protected int computeHorizontalScrollRange() { if (mDrawHistory) { return mHistoryWidth; } else { return contentToView(mContentWidth); } } // Make sure this stays in sync with the actual height of the FindDialog. private static final int FIND_HEIGHT = 79; @Override protected int computeVerticalScrollRange() { if (mDrawHistory) { return mHistoryHeight; } else { int height = contentToView(mContentHeight); if (mFindIsUp) { height += FIND_HEIGHT; } return height; } } /** * Get the url for the current page. This is not always the same as the url * passed to WebViewClient.onPageStarted because although the load for * that url has begun, the current page may not have changed. * @return The url for the current page. */ public String getUrl() { WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); return h != null ? h.getUrl() : null; } /** * Get the original url for the current page. This is not always the same * as the url passed to WebViewClient.onPageStarted because although the * load for that url has begun, the current page may not have changed. * Also, there may have been redirects resulting in a different url to that * originally requested. * @return The url that was originally requested for the current page. */ public String getOriginalUrl() { WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); return h != null ? h.getOriginalUrl() : null; } /** * Get the title for the current page. This is the title of the current page * until WebViewClient.onReceivedTitle is called. * @return The title for the current page. */ public String getTitle() { WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); return h != null ? h.getTitle() : null; } /** * Get the favicon for the current page. This is the favicon of the current * page until WebViewClient.onReceivedIcon is called. * @return The favicon for the current page. */ public Bitmap getFavicon() { WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); return h != null ? h.getFavicon() : null; } /** * Get the touch icon url for the apple-touch-icon element. * @hide */ public String getTouchIconUrl() { WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); return h != null ? h.getTouchIconUrl() : null; } /** * Get the progress for the current page. * @return The progress for the current page between 0 and 100. */ public int getProgress() { return mCallbackProxy.getProgress(); } /** * @return the height of the HTML content. */ public int getContentHeight() { return mContentHeight; } /** * Pause all layout, parsing, and javascript timers for all webviews. This * is a global requests, not restricted to just this webview. This can be * useful if the application has been paused. */ public void pauseTimers() { mWebViewCore.sendMessage(EventHub.PAUSE_TIMERS); } /** * Resume all layout, parsing, and javascript timers for all webviews. * This will resume dispatching all timers. */ public void resumeTimers() { mWebViewCore.sendMessage(EventHub.RESUME_TIMERS); } /** * Call this to pause any extra processing associated with this view and * its associated DOM/plugins/javascript/etc. For example, if the view is * taken offscreen, this could be called to reduce unnecessary CPU and/or * network traffic. When the view is again "active", call onResume(). * * Note that this differs from pauseTimers(), which affects all views/DOMs * @hide */ public void onPause() { if (!mIsPaused) { mIsPaused = true; mWebViewCore.sendMessage(EventHub.ON_PAUSE); } } /** * Call this to balanace a previous call to onPause() * @hide */ public void onResume() { if (mIsPaused) { mIsPaused = false; mWebViewCore.sendMessage(EventHub.ON_RESUME); } } /** * Returns true if the view is paused, meaning onPause() was called. Calling * onResume() sets the paused state back to false. * @hide */ public boolean isPaused() { return mIsPaused; } /** * Call this to inform the view that memory is low so that it can * free any available memory. * @hide */ public void freeMemory() { mWebViewCore.sendMessage(EventHub.FREE_MEMORY); } /** * Clear the resource cache. Note that the cache is per-application, so * this will clear the cache for all WebViews used. * * @param includeDiskFiles If false, only the RAM cache is cleared. */ public void clearCache(boolean includeDiskFiles) { // Note: this really needs to be a static method as it clears cache for all // WebView. But we need mWebViewCore to send message to WebCore thread, so // we can't make this static. mWebViewCore.sendMessage(EventHub.CLEAR_CACHE, includeDiskFiles ? 1 : 0, 0); } /** * Make sure that clearing the form data removes the adapter from the * currently focused textfield if there is one. */ public void clearFormData() { if (inEditingMode()) { AutoCompleteAdapter adapter = null; mWebTextView.setAdapterCustom(adapter); } } /** * Tell the WebView to clear its internal back/forward list. */ public void clearHistory() { mCallbackProxy.getBackForwardList().setClearPending(); mWebViewCore.sendMessage(EventHub.CLEAR_HISTORY); } /** * Clear the SSL preferences table stored in response to proceeding with SSL * certificate errors. */ public void clearSslPreferences() { mWebViewCore.sendMessage(EventHub.CLEAR_SSL_PREF_TABLE); } /** * Return the WebBackForwardList for this WebView. This contains the * back/forward list for use in querying each item in the history stack. * This is a copy of the private WebBackForwardList so it contains only a * snapshot of the current state. Multiple calls to this method may return * different objects. The object returned from this method will not be * updated to reflect any new state. */ public WebBackForwardList copyBackForwardList() { return mCallbackProxy.getBackForwardList().clone(); } /* * Highlight and scroll to the next occurance of String in findAll. * Wraps the page infinitely, and scrolls. Must be called after * calling findAll. * * @param forward Direction to search. */ public void findNext(boolean forward) { nativeFindNext(forward); } /* * Find all instances of find on the page and highlight them. * @param find String to find. * @return int The number of occurances of the String "find" * that were found. */ public int findAll(String find) { mFindIsUp = true; int result = nativeFindAll(find.toLowerCase(), find.toUpperCase()); invalidate(); return result; } // Used to know whether the find dialog is open. Affects whether // or not we draw the highlights for matches. private boolean mFindIsUp; /** * Return the first substring consisting of the address of a physical * location. Currently, only addresses in the United States are detected, * and consist of: * - a house number * - a street name * - a street type (Road, Circle, etc), either spelled out or abbreviated * - a city name * - a state or territory, either spelled out or two-letter abbr. * - an optional 5 digit or 9 digit zip code. * * All names must be correctly capitalized, and the zip code, if present, * must be valid for the state. The street type must be a standard USPS * spelling or abbreviation. The state or territory must also be spelled * or abbreviated using USPS standards. The house number may not exceed * five digits. * @param addr The string to search for addresses. * * @return the address, or if no address is found, return null. */ public static String findAddress(String addr) { return findAddress(addr, false); } /** * @hide * Return the first substring consisting of the address of a physical * location. Currently, only addresses in the United States are detected, * and consist of: * - a house number * - a street name * - a street type (Road, Circle, etc), either spelled out or abbreviated * - a city name * - a state or territory, either spelled out or two-letter abbr. * - an optional 5 digit or 9 digit zip code. * * Names are optionally capitalized, and the zip code, if present, * must be valid for the state. The street type must be a standard USPS * spelling or abbreviation. The state or territory must also be spelled * or abbreviated using USPS standards. The house number may not exceed * five digits. * @param addr The string to search for addresses. * @param caseInsensitive addr Set to true to make search ignore case. * * @return the address, or if no address is found, return null. */ public static String findAddress(String addr, boolean caseInsensitive) { return WebViewCore.nativeFindAddress(addr, caseInsensitive); } /* * Clear the highlighting surrounding text matches created by findAll. */ public void clearMatches() { mFindIsUp = false; nativeSetFindIsDown(); // Now that the dialog has been removed, ensure that we scroll to a // location that is not beyond the end of the page. pinScrollTo(mScrollX, mScrollY, false, 0); invalidate(); } /** * Query the document to see if it contains any image references. The * message object will be dispatched with arg1 being set to 1 if images * were found and 0 if the document does not reference any images. * @param response The message that will be dispatched with the result. */ public void documentHasImages(Message response) { if (response == null) { return; } mWebViewCore.sendMessage(EventHub.DOC_HAS_IMAGES, response); } @Override public void computeScroll() { if (mScroller.computeScrollOffset()) { int oldX = mScrollX; int oldY = mScrollY; mScrollX = mScroller.getCurrX(); mScrollY = mScroller.getCurrY(); postInvalidate(); // So we draw again if (oldX != mScrollX || oldY != mScrollY) { // as onScrollChanged() is not called, sendOurVisibleRect() // needs to be call explicitly sendOurVisibleRect(); } } else { super.computeScroll(); } } private static int computeDuration(int dx, int dy) { int distance = Math.max(Math.abs(dx), Math.abs(dy)); int duration = distance * 1000 / STD_SPEED; return Math.min(duration, MAX_DURATION); } // helper to pin the scrollBy parameters (already in view coordinates) // returns true if the scroll was changed private boolean pinScrollBy(int dx, int dy, boolean animate, int animationDuration) { return pinScrollTo(mScrollX + dx, mScrollY + dy, animate, animationDuration); } // helper to pin the scrollTo parameters (already in view coordinates) // returns true if the scroll was changed private boolean pinScrollTo(int x, int y, boolean animate, int animationDuration) { x = pinLocX(x); y = pinLocY(y); int dx = x - mScrollX; int dy = y - mScrollY; if ((dx | dy) == 0) { return false; } if (true && animate) { // Log.d(LOGTAG, "startScroll: " + dx + " " + dy); mScroller.startScroll(mScrollX, mScrollY, dx, dy, animationDuration > 0 ? animationDuration : computeDuration(dx, dy)); invalidate(); } else { mScroller.abortAnimation(); // just in case scrollTo(x, y); } return true; } // Scale from content to view coordinates, and pin. // Also called by jni webview.cpp private boolean setContentScrollBy(int cx, int cy, boolean animate) { if (mDrawHistory) { // disallow WebView to change the scroll position as History Picture // is used in the view system. // TODO: as we switchOutDrawHistory when trackball or navigation // keys are hit, this should be safe. Right? return false; } cx = contentToView(cx); cy = contentToView(cy); if (mHeightCanMeasure) { // move our visible rect according to scroll request if (cy != 0) { Rect tempRect = new Rect(); calcOurVisibleRect(tempRect); tempRect.offset(cx, cy); requestRectangleOnScreen(tempRect); } // FIXME: We scroll horizontally no matter what because currently // ScrollView and ListView will not scroll horizontally. // FIXME: Why do we only scroll horizontally if there is no // vertical scroll? // Log.d(LOGTAG, "setContentScrollBy cy=" + cy); return cy == 0 && cx != 0 && pinScrollBy(cx, 0, animate, 0); } else { return pinScrollBy(cx, cy, animate, 0); } } // scale from content to view coordinates, and pin // return true if pin caused the final x/y different than the request cx/cy; // return false if the view scroll to the exact position as it is requested. private boolean setContentScrollTo(int cx, int cy) { if (mDrawHistory) { // disallow WebView to change the scroll position as History Picture // is used in the view system. // One known case where this is called is that WebCore tries to // restore the scroll position. As history Picture already uses the // saved scroll position, it is ok to skip this. return false; } int vx = contentToView(cx); int vy = contentToView(cy); // Log.d(LOGTAG, "content scrollTo [" + cx + " " + cy + "] view=[" + // vx + " " + vy + "]"); pinScrollTo(vx, vy, false, 0); if (mScrollX != vx || mScrollY != vy) { return true; } else { return false; } } // scale from content to view coordinates, and pin private void spawnContentScrollTo(int cx, int cy) { if (mDrawHistory) { // disallow WebView to change the scroll position as History Picture // is used in the view system. return; } int vx = contentToView(cx); int vy = contentToView(cy); pinScrollTo(vx, vy, true, 0); } /** * These are from webkit, and are in content coordinate system (unzoomed) */ private void contentSizeChanged(boolean updateLayout) { // suppress 0,0 since we usually see real dimensions soon after // this avoids drawing the prev content in a funny place. If we find a // way to consolidate these notifications, this check may become // obsolete if ((mContentWidth | mContentHeight) == 0) { return; } if (mHeightCanMeasure) { if (getMeasuredHeight() != contentToView(mContentHeight) && updateLayout) { requestLayout(); } } else if (mWidthCanMeasure) { if (getMeasuredWidth() != contentToView(mContentWidth) && updateLayout) { requestLayout(); } } else { // If we don't request a layout, try to send our view size to the // native side to ensure that WebCore has the correct dimensions. sendViewSizeZoom(); } } /** * Set the WebViewClient that will receive various notifications and * requests. This will replace the current handler. * @param client An implementation of WebViewClient. */ public void setWebViewClient(WebViewClient client) { mCallbackProxy.setWebViewClient(client); } /** * Register the interface to be used when content can not be handled by * the rendering engine, and should be downloaded instead. This will replace * the current handler. * @param listener An implementation of DownloadListener. */ public void setDownloadListener(DownloadListener listener) { mCallbackProxy.setDownloadListener(listener); } /** * Set the chrome handler. This is an implementation of WebChromeClient for * use in handling Javascript dialogs, favicons, titles, and the progress. * This will replace the current handler. * @param client An implementation of WebChromeClient. */ public void setWebChromeClient(WebChromeClient client) { mCallbackProxy.setWebChromeClient(client); } /** * Gets the chrome handler. * @return the current WebChromeClient instance. * * @hide API council approval. */ public WebChromeClient getWebChromeClient() { return mCallbackProxy.getWebChromeClient(); } /** * Set the Picture listener. This is an interface used to receive * notifications of a new Picture. * @param listener An implementation of WebView.PictureListener. */ public void setPictureListener(PictureListener listener) { mPictureListener = listener; } /** * {@hide} */ /* FIXME: Debug only! Remove for SDK! */ public void externalRepresentation(Message callback) { mWebViewCore.sendMessage(EventHub.REQUEST_EXT_REPRESENTATION, callback); } /** * {@hide} */ /* FIXME: Debug only! Remove for SDK! */ public void documentAsText(Message callback) { mWebViewCore.sendMessage(EventHub.REQUEST_DOC_AS_TEXT, callback); } /** * Use this function to bind an object to Javascript so that the * methods can be accessed from Javascript. *
IMPORTANT: *