blob: 0346712203cac445cba334737997bbc2fddd30d8 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.webkit;
18
19import android.app.AlertDialog;
20import android.content.Context;
21import android.content.DialogInterface;
22import android.content.Intent;
23import android.content.DialogInterface.OnCancelListener;
Leon Scroggins3667ce42009-05-13 15:58:03 -040024import android.database.DataSetObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.graphics.Bitmap;
26import android.graphics.Canvas;
27import android.graphics.Color;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.graphics.Picture;
29import android.graphics.Point;
30import android.graphics.Rect;
31import android.graphics.Region;
Mike Reede8853fc2009-09-04 14:01:48 -040032import android.graphics.drawable.Drawable;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.net.http.SslCertificate;
34import android.net.Uri;
35import android.os.Bundle;
36import android.os.Handler;
37import android.os.Message;
38import android.os.ServiceManager;
39import android.os.SystemClock;
40import android.provider.Checkin;
41import android.text.IClipboard;
42import android.text.Selection;
43import android.text.Spannable;
44import android.util.AttributeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.util.EventLog;
46import android.util.Log;
Leon Scroggins3a6c88c2009-09-09 14:50:23 -040047import android.util.TypedValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.view.Gravity;
49import android.view.KeyEvent;
50import android.view.LayoutInflater;
51import android.view.MotionEvent;
52import android.view.SoundEffectConstants;
53import android.view.VelocityTracker;
54import android.view.View;
55import android.view.ViewConfiguration;
56import android.view.ViewGroup;
57import android.view.ViewParent;
58import android.view.ViewTreeObserver;
The Android Open Source Project10592532009-03-18 17:39:46 -070059import android.view.animation.AlphaAnimation;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.view.inputmethod.InputMethodManager;
Leon Scrogginsd3465f62009-06-02 10:57:54 -040061import android.webkit.WebTextView.AutoCompleteAdapter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.webkit.WebViewCore.EventHub;
63import android.widget.AbsoluteLayout;
Leon Scroggins3667ce42009-05-13 15:58:03 -040064import android.widget.Adapter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.widget.AdapterView;
66import android.widget.ArrayAdapter;
The Android Open Source Project10592532009-03-18 17:39:46 -070067import android.widget.FrameLayout;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.widget.ListView;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.widget.Scroller;
70import android.widget.Toast;
71import android.widget.ZoomButtonsController;
The Android Open Source Project10592532009-03-18 17:39:46 -070072import android.widget.ZoomControls;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.widget.AdapterView.OnItemClickListener;
74
75import java.io.File;
76import java.io.FileInputStream;
77import java.io.FileNotFoundException;
78import java.io.FileOutputStream;
79import java.io.IOException;
80import java.net.URLDecoder;
81import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import java.util.List;
Andrei Popescu4950b2b2009-09-03 13:56:07 +010083import java.util.Map;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084
85/**
Cary Clarkd6982c92009-05-29 11:02:22 -040086 * <p>A View that displays web pages. This class is the basis upon which you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087 * can roll your own web browser or simply display some online content within your Activity.
88 * It uses the WebKit rendering engine to display
89 * web pages and includes methods to navigate forward and backward
90 * through a history, zoom in and out, perform text searches and more.</p>
The Android Open Source Project10592532009-03-18 17:39:46 -070091 * <p>To enable the built-in zoom, set
92 * {@link #getSettings() WebSettings}.{@link WebSettings#setBuiltInZoomControls(boolean)}
93 * (introduced in API version 3).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094 * <p>Note that, in order for your Activity to access the Internet and load web pages
Cary Clarkd6982c92009-05-29 11:02:22 -040095 * in a WebView, you must add the <var>INTERNET</var> permissions to your
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096 * Android Manifest file:</p>
97 * <pre>&lt;uses-permission android:name="android.permission.INTERNET" /></pre>
Mike Hearnadcd2ed2009-01-21 16:44:36 +010098 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099 * <p>This must be a child of the <code>&lt;manifest></code> element.</p>
Mike Hearnadcd2ed2009-01-21 16:44:36 +0100100 *
101 * <h3>Basic usage</h3>
102 *
103 * <p>By default, a WebView provides no browser-like widgets, does not
104 * enable JavaScript and errors will be ignored. If your goal is only
105 * to display some HTML as a part of your UI, this is probably fine;
106 * the user won't need to interact with the web page beyond reading
107 * it, and the web page won't need to interact with the user. If you
108 * actually want a fully blown web browser, then you probably want to
109 * invoke the Browser application with your URL rather than show it
110 * with a WebView. See {@link android.content.Intent} for more information.</p>
111 *
112 * <pre class="prettyprint">
113 * WebView webview = new WebView(this);
114 * setContentView(webview);
115 *
116 * // Simplest usage: note that an exception will NOT be thrown
117 * // if there is an error loading this page (see below).
118 * webview.loadUrl("http://slashdot.org/");
119 *
120 * // Of course you can also load from any string:
121 * String summary = "&lt;html>&lt;body>You scored &lt;b>192</b> points.&lt;/body>&lt;/html>";
122 * webview.loadData(summary, "text/html", "utf-8");
123 * // ... although note that there are restrictions on what this HTML can do.
124 * // See the JavaDocs for loadData and loadDataWithBaseUrl for more info.
125 * </pre>
126 *
127 * <p>A WebView has several customization points where you can add your
128 * own behavior. These are:</p>
129 *
130 * <ul>
131 * <li>Creating and setting a {@link android.webkit.WebChromeClient} subclass.
132 * This class is called when something that might impact a
133 * browser UI happens, for instance, progress updates and
134 * JavaScript alerts are sent here.
135 * </li>
136 * <li>Creating and setting a {@link android.webkit.WebViewClient} subclass.
137 * It will be called when things happen that impact the
138 * rendering of the content, eg, errors or form submissions. You
139 * can also intercept URL loading here.</li>
140 * <li>Via the {@link android.webkit.WebSettings} class, which contains
141 * miscellaneous configuration. </li>
142 * <li>With the {@link android.webkit.WebView#addJavascriptInterface} method.
143 * This lets you bind Java objects into the WebView so they can be
144 * controlled from the web pages JavaScript.</li>
145 * </ul>
146 *
147 * <p>Here's a more complicated example, showing error handling,
148 * settings, and progress notification:</p>
149 *
150 * <pre class="prettyprint">
151 * // Let's display the progress in the activity title bar, like the
152 * // browser app does.
153 * getWindow().requestFeature(Window.FEATURE_PROGRESS);
154 *
155 * webview.getSettings().setJavaScriptEnabled(true);
156 *
157 * final Activity activity = this;
158 * webview.setWebChromeClient(new WebChromeClient() {
159 * public void onProgressChanged(WebView view, int progress) {
160 * // Activities and WebViews measure progress with different scales.
161 * // The progress meter will automatically disappear when we reach 100%
162 * activity.setProgress(progress * 1000);
163 * }
164 * });
165 * webview.setWebViewClient(new WebViewClient() {
166 * public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
167 * Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
168 * }
169 * });
170 *
171 * webview.loadUrl("http://slashdot.org/");
172 * </pre>
173 *
174 * <h3>Cookie and window management</h3>
175 *
176 * <p>For obvious security reasons, your application has its own
177 * cache, cookie store etc - it does not share the Browser
178 * applications data. Cookies are managed on a separate thread, so
179 * operations like index building don't block the UI
180 * thread. Follow the instructions in {@link android.webkit.CookieSyncManager}
181 * if you want to use cookies in your application.
182 * </p>
183 *
184 * <p>By default, requests by the HTML to open new windows are
185 * ignored. This is true whether they be opened by JavaScript or by
186 * the target attribute on a link. You can customize your
187 * WebChromeClient to provide your own behaviour for opening multiple windows,
188 * and render them in whatever manner you want.</p>
189 *
190 * <p>Standard behavior for an Activity is to be destroyed and
191 * recreated when the devices orientation is changed. This will cause
192 * the WebView to reload the current page. If you don't want that, you
193 * can set your Activity to handle the orientation and keyboardHidden
194 * changes, and then just leave the WebView alone. It'll automatically
195 * re-orient itself as appropriate.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 */
Cary Clarkd6982c92009-05-29 11:02:22 -0400197public class WebView extends AbsoluteLayout
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 implements ViewTreeObserver.OnGlobalFocusChangeListener,
199 ViewGroup.OnHierarchyChangeListener {
200
201 // if AUTO_REDRAW_HACK is true, then the CALL key will toggle redrawing
202 // the screen all-the-time. Good for profiling our drawing code
203 static private final boolean AUTO_REDRAW_HACK = false;
204 // true means redraw the screen all-the-time. Only with AUTO_REDRAW_HACK
205 private boolean mAutoRedraw;
206
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207 static final String LOGTAG = "webview";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208
Leon Scroggins213a31c2009-05-21 16:49:32 -0700209 private static class ExtendedZoomControls extends FrameLayout {
The Android Open Source Project10592532009-03-18 17:39:46 -0700210 public ExtendedZoomControls(Context context, AttributeSet attrs) {
211 super(context, attrs);
212 LayoutInflater inflater = (LayoutInflater)
213 context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
214 inflater.inflate(com.android.internal.R.layout.zoom_magnify, this, true);
Leon Scrogginsa5645b22009-06-09 15:31:19 -0400215 mPlusMinusZoomControls = (ZoomControls) findViewById(
216 com.android.internal.R.id.zoomControls);
Grace Kloba04b28682009-09-14 14:38:37 -0700217 findViewById(com.android.internal.R.id.zoomMagnify).setVisibility(
218 View.GONE);
The Android Open Source Project10592532009-03-18 17:39:46 -0700219 }
Cary Clarkd6982c92009-05-29 11:02:22 -0400220
The Android Open Source Project10592532009-03-18 17:39:46 -0700221 public void show(boolean showZoom, boolean canZoomOut) {
Leon Scrogginsa5645b22009-06-09 15:31:19 -0400222 mPlusMinusZoomControls.setVisibility(
223 showZoom ? View.VISIBLE : View.GONE);
The Android Open Source Project10592532009-03-18 17:39:46 -0700224 fade(View.VISIBLE, 0.0f, 1.0f);
225 }
Cary Clarkd6982c92009-05-29 11:02:22 -0400226
The Android Open Source Project10592532009-03-18 17:39:46 -0700227 public void hide() {
228 fade(View.GONE, 1.0f, 0.0f);
229 }
Cary Clarkd6982c92009-05-29 11:02:22 -0400230
The Android Open Source Project10592532009-03-18 17:39:46 -0700231 private void fade(int visibility, float startAlpha, float endAlpha) {
232 AlphaAnimation anim = new AlphaAnimation(startAlpha, endAlpha);
233 anim.setDuration(500);
234 startAnimation(anim);
235 setVisibility(visibility);
236 }
Cary Clarkd6982c92009-05-29 11:02:22 -0400237
The Android Open Source Project10592532009-03-18 17:39:46 -0700238 public boolean hasFocus() {
Grace Kloba04b28682009-09-14 14:38:37 -0700239 return mPlusMinusZoomControls.hasFocus();
The Android Open Source Project10592532009-03-18 17:39:46 -0700240 }
Cary Clarkd6982c92009-05-29 11:02:22 -0400241
The Android Open Source Project10592532009-03-18 17:39:46 -0700242 public void setOnZoomInClickListener(OnClickListener listener) {
Leon Scrogginsa5645b22009-06-09 15:31:19 -0400243 mPlusMinusZoomControls.setOnZoomInClickListener(listener);
The Android Open Source Project10592532009-03-18 17:39:46 -0700244 }
Cary Clarkd6982c92009-05-29 11:02:22 -0400245
The Android Open Source Project10592532009-03-18 17:39:46 -0700246 public void setOnZoomOutClickListener(OnClickListener listener) {
Leon Scrogginsa5645b22009-06-09 15:31:19 -0400247 mPlusMinusZoomControls.setOnZoomOutClickListener(listener);
The Android Open Source Project10592532009-03-18 17:39:46 -0700248 }
Cary Clarkd6982c92009-05-29 11:02:22 -0400249
Leon Scrogginsa5645b22009-06-09 15:31:19 -0400250 ZoomControls mPlusMinusZoomControls;
The Android Open Source Project10592532009-03-18 17:39:46 -0700251 }
Cary Clarkd6982c92009-05-29 11:02:22 -0400252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 /**
254 * Transportation object for returning WebView across thread boundaries.
255 */
256 public class WebViewTransport {
257 private WebView mWebview;
258
259 /**
260 * Set the WebView to the transportation object.
261 * @param webview The WebView to transport.
262 */
263 public synchronized void setWebView(WebView webview) {
264 mWebview = webview;
265 }
266
267 /**
268 * Return the WebView object.
269 * @return WebView The transported WebView object.
270 */
271 public synchronized WebView getWebView() {
272 return mWebview;
273 }
274 }
275
276 // A final CallbackProxy shared by WebViewCore and BrowserFrame.
277 private final CallbackProxy mCallbackProxy;
278
279 private final WebViewDatabase mDatabase;
280
281 // SSL certificate for the main top-level page (if secure)
282 private SslCertificate mCertificate;
283
284 // Native WebView pointer that is 0 until the native object has been
285 // created.
286 private int mNativeClass;
287 // This would be final but it needs to be set to null when the WebView is
288 // destroyed.
289 private WebViewCore mWebViewCore;
290 // Handler for dispatching UI messages.
291 /* package */ final Handler mPrivateHandler = new PrivateHandler();
Leon Scrogginsd3465f62009-06-02 10:57:54 -0400292 private WebTextView mWebTextView;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800293 // Used to ignore changes to webkit text that arrives to the UI side after
294 // more key events.
295 private int mTextGeneration;
296
Patrick Scott0a5ce012009-07-02 08:56:10 -0400297 // Used by WebViewCore to create child views.
298 /* package */ final ViewManager mViewManager;
299
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800300 /**
301 * Position of the last touch event.
302 */
303 private float mLastTouchX;
304 private float mLastTouchY;
305
306 /**
307 * Time of the last touch event.
308 */
309 private long mLastTouchTime;
310
311 /**
312 * Time of the last time sending touch event to WebViewCore
313 */
314 private long mLastSentTouchTime;
315
316 /**
317 * The minimum elapsed time before sending another ACTION_MOVE event to
Grace Kloba53d3c1e2009-06-26 11:36:03 -0700318 * WebViewCore. This really should be tuned for each type of the devices.
319 * For example in Google Map api test case, it takes Dream device at least
320 * 150ms to do a full cycle in the WebViewCore by processing a touch event,
321 * triggering the layout and drawing the picture. While the same process
322 * takes 60+ms on the current high speed device. If we make
323 * TOUCH_SENT_INTERVAL too small, there will be multiple touch events sent
324 * to WebViewCore queue and the real layout and draw events will be pushed
325 * to further, which slows down the refresh rate. Choose 50 to favor the
326 * current high speed devices. For Dream like devices, 100 is a better
327 * choice. Maybe make this in the buildspec later.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800328 */
Grace Kloba53d3c1e2009-06-26 11:36:03 -0700329 private static final int TOUCH_SENT_INTERVAL = 50;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330
331 /**
332 * Helper class to get velocity for fling
333 */
334 VelocityTracker mVelocityTracker;
Romain Guy4296fc42009-07-06 11:48:52 -0700335 private int mMaximumFling;
Cary Clark278ce052009-08-31 16:08:42 -0400336 private float mLastVelocity;
337 private float mLastVelX;
338 private float mLastVelY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800339
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800340 /**
341 * Touch mode
342 */
343 private int mTouchMode = TOUCH_DONE_MODE;
344 private static final int TOUCH_INIT_MODE = 1;
345 private static final int TOUCH_DRAG_START_MODE = 2;
346 private static final int TOUCH_DRAG_MODE = 3;
347 private static final int TOUCH_SHORTPRESS_START_MODE = 4;
348 private static final int TOUCH_SHORTPRESS_MODE = 5;
Grace Kloba04b28682009-09-14 14:38:37 -0700349 private static final int TOUCH_DOUBLE_TAP_MODE = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800350 private static final int TOUCH_DONE_MODE = 7;
351 private static final int TOUCH_SELECT_MODE = 8;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800352
353 // Whether to forward the touch events to WebCore
354 private boolean mForwardTouchEvents = false;
355
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356 // Whether to prevent drag during touch. The initial value depends on
357 // mForwardTouchEvents. If WebCore wants touch events, we assume it will
358 // take control of touch events unless it says no for touch down event.
Grace Klobaf58af622009-09-24 17:41:23 -0700359 private static final int PREVENT_DRAG_NO = 0;
360 private static final int PREVENT_DRAG_MAYBE_YES = 1;
361 private static final int PREVENT_DRAG_YES = 2;
362 private int mPreventDrag = PREVENT_DRAG_NO;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800363
Leon Scroggins72543e12009-07-23 15:29:45 -0400364 // To keep track of whether the current drag was initiated by a WebTextView,
365 // so that we know not to hide the cursor
366 boolean mDragFromTextInput;
367
Cary Clarkd6982c92009-05-29 11:02:22 -0400368 // Whether or not to draw the cursor ring.
369 private boolean mDrawCursorRing = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370
Mike Reedd205d5b2009-05-27 11:02:29 -0400371 // true if onPause has been called (and not onResume)
372 private boolean mIsPaused;
373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800374 /**
375 * Customizable constant
376 */
377 // pre-computed square of ViewConfiguration.getScaledTouchSlop()
378 private int mTouchSlopSquare;
Grace Kloba8b97e4b2009-07-28 13:11:38 -0700379 // pre-computed square of ViewConfiguration.getScaledDoubleTapSlop()
380 private int mDoubleTapSlopSquare;
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700381 // pre-computed density adjusted navigation slop
382 private int mNavSlop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383 // This should be ViewConfiguration.getTapTimeout()
384 // But system time out is 100ms, which is too short for the browser.
385 // In the browser, if it switches out of tap too soon, jump tap won't work.
386 private static final int TAP_TIMEOUT = 200;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387 // This should be ViewConfiguration.getLongPressTimeout()
388 // But system time out is 500ms, which is too short for the browser.
389 // With a short timeout, it's difficult to treat trigger a short press.
390 private static final int LONG_PRESS_TIMEOUT = 1000;
391 // needed to avoid flinging after a pause of no movement
392 private static final int MIN_FLING_TIME = 250;
Cary Clark25415e22009-10-12 13:41:28 -0400393 // draw unfiltered after drag is held without movement
394 private static final int MOTIONLESS_TIME = 100;
The Android Open Source Project10592532009-03-18 17:39:46 -0700395 // The time that the Zoom Controls are visible before fading away
Cary Clarkd6982c92009-05-29 11:02:22 -0400396 private static final long ZOOM_CONTROLS_TIMEOUT =
The Android Open Source Project10592532009-03-18 17:39:46 -0700397 ViewConfiguration.getZoomControlsTimeout();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800398 // The amount of content to overlap between two screens when going through
399 // pages with the space bar, in pixels.
400 private static final int PAGE_SCROLL_OVERLAP = 24;
401
402 /**
403 * These prevent calling requestLayout if either dimension is fixed. This
404 * depends on the layout parameters and the measure specs.
405 */
406 boolean mWidthCanMeasure;
407 boolean mHeightCanMeasure;
408
409 // Remember the last dimensions we sent to the native side so we can avoid
410 // sending the same dimensions more than once.
411 int mLastWidthSent;
412 int mLastHeightSent;
413
414 private int mContentWidth; // cache of value from WebViewCore
415 private int mContentHeight; // cache of value from WebViewCore
416
Cary Clarkd6982c92009-05-29 11:02:22 -0400417 // Need to have the separate control for horizontal and vertical scrollbar
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 // style than the View's single scrollbar style
419 private boolean mOverlayHorizontalScrollbar = true;
420 private boolean mOverlayVerticalScrollbar = false;
421
422 // our standard speed. this way small distances will be traversed in less
423 // time than large distances, but we cap the duration, so that very large
424 // distances won't take too long to get there.
425 private static final int STD_SPEED = 480; // pixels per second
426 // time for the longest scroll animation
427 private static final int MAX_DURATION = 750; // milliseconds
Leon Scroggins03c87bf2009-09-18 15:05:59 -0400428 private static final int SLIDE_TITLE_DURATION = 500; // milliseconds
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429 private Scroller mScroller;
430
431 private boolean mWrapContent;
Cary Clark25415e22009-10-12 13:41:28 -0400432 private static final int MOTIONLESS_FALSE = 0;
433 private static final int MOTIONLESS_PENDING = 1;
434 private static final int MOTIONLESS_TRUE = 2;
435 private int mHeldMotionless;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437 /**
438 * Private message ids
439 */
Leon Scrogginsd3465f62009-06-02 10:57:54 -0400440 private static final int REMEMBER_PASSWORD = 1;
441 private static final int NEVER_REMEMBER_PASSWORD = 2;
442 private static final int SWITCH_TO_SHORTPRESS = 3;
443 private static final int SWITCH_TO_LONGPRESS = 4;
Grace Kloba8b97e4b2009-07-28 13:11:38 -0700444 private static final int RELEASE_SINGLE_TAP = 5;
Leon Scrogginsd3465f62009-06-02 10:57:54 -0400445 private static final int REQUEST_FORM_DATA = 6;
Grace Klobadd817492009-09-14 10:17:06 -0700446 private static final int RESUME_WEBCORE_UPDATE = 7;
Cary Clark25415e22009-10-12 13:41:28 -0400447 private static final int DRAG_HELD_MOTIONLESS = 8;
448 private static final int AWAKEN_SCROLL_BARS = 9;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800449
450 //! arg1=x, arg2=y
Leon Scrogginsd3465f62009-06-02 10:57:54 -0400451 static final int SCROLL_TO_MSG_ID = 10;
452 static final int SCROLL_BY_MSG_ID = 11;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453 //! arg1=x, arg2=y
Leon Scrogginsd3465f62009-06-02 10:57:54 -0400454 static final int SPAWN_SCROLL_TO_MSG_ID = 12;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455 //! arg1=x, arg2=y
Leon Scrogginsd3465f62009-06-02 10:57:54 -0400456 static final int SYNC_SCROLL_TO_MSG_ID = 13;
457 static final int NEW_PICTURE_MSG_ID = 14;
458 static final int UPDATE_TEXT_ENTRY_MSG_ID = 15;
459 static final int WEBCORE_INITIALIZED_MSG_ID = 16;
460 static final int UPDATE_TEXTFIELD_TEXT_MSG_ID = 17;
Cary Clark215b72c2009-06-26 14:38:43 -0400461 static final int MOVE_OUT_OF_PLUGIN = 19;
Cary Clark243ea062009-06-25 10:49:32 -0400462 static final int CLEAR_TEXT_ENTRY = 20;
Leon Scroggins6679f2f2009-08-12 18:48:10 -0400463 static final int UPDATE_TEXT_SELECTION_MSG_ID = 21;
Leon Scrogginsd3465f62009-06-02 10:57:54 -0400464 static final int UPDATE_CLIPBOARD = 22;
Leon Scrogginse3225672009-06-03 15:53:13 -0400465 static final int LONG_PRESS_CENTER = 23;
Leon Scrogginsd3465f62009-06-02 10:57:54 -0400466 static final int PREVENT_TOUCH_ID = 24;
467 static final int WEBCORE_NEED_TOUCH_EVENTS = 25;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800468 // obj=Rect in doc coordinates
Leon Scrogginsd3465f62009-06-02 10:57:54 -0400469 static final int INVAL_RECT_MSG_ID = 26;
Derek Sollenberger4c41e8d2009-06-29 13:49:27 -0400470 static final int REQUEST_KEYBOARD = 27;
Cary Clarkd6982c92009-05-29 11:02:22 -0400471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800472 static final String[] HandlerDebugString = {
Leon Scrogginsd3465f62009-06-02 10:57:54 -0400473 "REMEMBER_PASSWORD", // = 1;
474 "NEVER_REMEMBER_PASSWORD", // = 2;
475 "SWITCH_TO_SHORTPRESS", // = 3;
476 "SWITCH_TO_LONGPRESS", // = 4;
Grace Kloba8b97e4b2009-07-28 13:11:38 -0700477 "RELEASE_SINGLE_TAP", // = 5;
Leon Scrogginsd3465f62009-06-02 10:57:54 -0400478 "REQUEST_FORM_DATA", // = 6;
Cary Clark25415e22009-10-12 13:41:28 -0400479 "RESUME_WEBCORE_UPDATE", // = 7;
480 "DRAG_HELD_MOTIONLESS", // = 8;
481 "AWAKEN_SCROLL_BARS", // = 9;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482 "SCROLL_TO_MSG_ID", // = 10;
483 "SCROLL_BY_MSG_ID", // = 11;
484 "SPAWN_SCROLL_TO_MSG_ID", // = 12;
485 "SYNC_SCROLL_TO_MSG_ID", // = 13;
486 "NEW_PICTURE_MSG_ID", // = 14;
487 "UPDATE_TEXT_ENTRY_MSG_ID", // = 15;
488 "WEBCORE_INITIALIZED_MSG_ID", // = 16;
489 "UPDATE_TEXTFIELD_TEXT_MSG_ID", // = 17;
Grace Klobaef347ef2009-07-30 11:20:32 -0700490 "18", // = 18;
Cary Clark215b72c2009-06-26 14:38:43 -0400491 "MOVE_OUT_OF_PLUGIN", // = 19;
Cary Clark243ea062009-06-25 10:49:32 -0400492 "CLEAR_TEXT_ENTRY", // = 20;
Leon Scroggins6679f2f2009-08-12 18:48:10 -0400493 "UPDATE_TEXT_SELECTION_MSG_ID", // = 21;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494 "UPDATE_CLIPBOARD", // = 22;
Leon Scrogginse3225672009-06-03 15:53:13 -0400495 "LONG_PRESS_CENTER", // = 23;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800496 "PREVENT_TOUCH_ID", // = 24;
497 "WEBCORE_NEED_TOUCH_EVENTS", // = 25;
Derek Sollenberger4c41e8d2009-06-29 13:49:27 -0400498 "INVAL_RECT_MSG_ID", // = 26;
499 "REQUEST_KEYBOARD" // = 27;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800500 };
501
Grace Kloba25737912009-06-19 12:42:47 -0700502 // default scale limit. Depending on the display density
503 private static float DEFAULT_MAX_ZOOM_SCALE;
504 private static float DEFAULT_MIN_ZOOM_SCALE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505 // scale limit, which can be set through viewport meta tag in the web page
Grace Kloba25737912009-06-19 12:42:47 -0700506 private float mMaxZoomScale;
507 private float mMinZoomScale;
Grace Klobae397a882009-08-06 12:04:14 -0700508 private boolean mMinZoomScaleFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800509
510 // initial scale in percent. 0 means using default.
511 private int mInitialScale = 0;
512
Grace Kloba8b97e4b2009-07-28 13:11:38 -0700513 // while in the zoom overview mode, the page's width is fully fit to the
514 // current window. The page is alive, in another words, you can click to
515 // follow the links. Double tap will toggle between zoom overview mode and
516 // the last zoom scale.
517 boolean mInZoomOverview = false;
Leon Scrogginsf58ffac2009-08-13 15:34:06 -0400518
Grace Kloba8b97e4b2009-07-28 13:11:38 -0700519 // ideally mZoomOverviewWidth should be mContentWidth. But sites like espn,
520 // engadget always have wider mContentWidth no matter what viewport size is.
Grace Klobae397a882009-08-06 12:04:14 -0700521 int mZoomOverviewWidth = WebViewCore.DEFAULT_VIEWPORT_WIDTH;
Grace Kloba8b97e4b2009-07-28 13:11:38 -0700522 float mLastScale;
523
Grace Kloba25737912009-06-19 12:42:47 -0700524 // default scale. Depending on the display density.
525 static int DEFAULT_SCALE_PERCENT;
Grace Kloba0d8b77c2009-06-25 11:20:51 -0700526 private float mDefaultScale;
Grace Kloba25737912009-06-19 12:42:47 -0700527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800528 // set to true temporarily while the zoom control is being dragged
529 private boolean mPreviewZoomOnly = false;
530
531 // computed scale and inverse, from mZoomWidth.
Grace Kloba25737912009-06-19 12:42:47 -0700532 private float mActualScale;
533 private float mInvActualScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800534 // if this is non-zero, it is used on drawing rather than mActualScale
535 private float mZoomScale;
536 private float mInvInitialZoomScale;
537 private float mInvFinalZoomScale;
Grace Kloba675c7d22009-07-23 09:21:21 -0700538 private int mInitialScrollX;
539 private int mInitialScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540 private long mZoomStart;
541 private static final int ZOOM_ANIMATION_LENGTH = 500;
542
543 private boolean mUserScroll = false;
544
545 private int mSnapScrollMode = SNAP_NONE;
Cary Clarkac492e12009-10-14 14:53:37 -0400546 private static final int SNAP_NONE = 0;
547 private static final int SNAP_LOCK = 1; // not a separate state
548 private static final int SNAP_X = 2; // may be combined with SNAP_LOCK
549 private static final int SNAP_Y = 4; // may be combined with SNAP_LOCK
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800550 private boolean mSnapPositive;
Cary Clarkd6982c92009-05-29 11:02:22 -0400551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 // Used to match key downs and key ups
553 private boolean mGotKeyDown;
554
555 /* package */ static boolean mLogEvent = true;
556 private static final int EVENT_LOG_ZOOM_LEVEL_CHANGE = 70101;
557 private static final int EVENT_LOG_DOUBLE_TAP_DURATION = 70102;
558
559 // for event log
560 private long mLastTouchUpTime = 0;
561
562 /**
563 * URI scheme for telephone number
564 */
565 public static final String SCHEME_TEL = "tel:";
566 /**
567 * URI scheme for email address
568 */
569 public static final String SCHEME_MAILTO = "mailto:";
570 /**
571 * URI scheme for map address
572 */
573 public static final String SCHEME_GEO = "geo:0,0?q=";
Cary Clarkd6982c92009-05-29 11:02:22 -0400574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 private int mBackgroundColor = Color.WHITE;
576
577 // Used to notify listeners of a new picture.
578 private PictureListener mPictureListener;
579 /**
580 * Interface to listen for new pictures as they change.
581 */
582 public interface PictureListener {
583 /**
584 * Notify the listener that the picture has changed.
585 * @param view The WebView that owns the picture.
586 * @param picture The new picture.
587 */
588 public void onNewPicture(WebView view, Picture picture);
589 }
590
Leon Scroggins3246c222009-05-26 09:51:23 -0400591 // FIXME: Want to make this public, but need to change the API file.
592 public /*static*/ class HitTestResult {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800593 /**
594 * Default HitTestResult, where the target is unknown
595 */
596 public static final int UNKNOWN_TYPE = 0;
597 /**
598 * HitTestResult for hitting a HTML::a tag
599 */
600 public static final int ANCHOR_TYPE = 1;
601 /**
602 * HitTestResult for hitting a phone number
603 */
604 public static final int PHONE_TYPE = 2;
605 /**
606 * HitTestResult for hitting a map address
607 */
608 public static final int GEO_TYPE = 3;
609 /**
610 * HitTestResult for hitting an email address
611 */
612 public static final int EMAIL_TYPE = 4;
613 /**
614 * HitTestResult for hitting an HTML::img tag
615 */
616 public static final int IMAGE_TYPE = 5;
617 /**
618 * HitTestResult for hitting a HTML::a tag which contains HTML::img
619 */
620 public static final int IMAGE_ANCHOR_TYPE = 6;
621 /**
622 * HitTestResult for hitting a HTML::a tag with src=http
623 */
624 public static final int SRC_ANCHOR_TYPE = 7;
625 /**
626 * HitTestResult for hitting a HTML::a tag with src=http + HTML::img
627 */
628 public static final int SRC_IMAGE_ANCHOR_TYPE = 8;
629 /**
630 * HitTestResult for hitting an edit text area
631 */
632 public static final int EDIT_TEXT_TYPE = 9;
633
634 private int mType;
635 private String mExtra;
636
637 HitTestResult() {
638 mType = UNKNOWN_TYPE;
639 }
640
641 private void setType(int type) {
642 mType = type;
643 }
644
645 private void setExtra(String extra) {
646 mExtra = extra;
647 }
648
649 public int getType() {
650 return mType;
651 }
652
653 public String getExtra() {
654 return mExtra;
655 }
656 }
657
The Android Open Source Project10592532009-03-18 17:39:46 -0700658 // The View containing the zoom controls
659 private ExtendedZoomControls mZoomControls;
660 private Runnable mZoomControlRunnable;
661
Cary Clarkd6982c92009-05-29 11:02:22 -0400662 private ZoomButtonsController mZoomButtonsController;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700664 // These keep track of the center point of the zoom. They are used to
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 // determine the point around which we should zoom.
666 private float mZoomCenterX;
667 private float mZoomCenterY;
668
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700669 private ZoomButtonsController.OnZoomListener mZoomListener =
670 new ZoomButtonsController.OnZoomListener() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672 public void onVisibilityChanged(boolean visible) {
673 if (visible) {
674 switchOutDrawHistory();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700675 updateZoomButtonsEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800676 }
677 }
678
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700679 public void onZoom(boolean zoomIn) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680 if (zoomIn) {
681 zoomIn();
682 } else {
683 zoomOut();
684 }
Cary Clarkd6982c92009-05-29 11:02:22 -0400685
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700686 updateZoomButtonsEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688 };
Cary Clarkd6982c92009-05-29 11:02:22 -0400689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 /**
691 * Construct a new WebView with a Context object.
692 * @param context A Context object used to access application assets.
693 */
694 public WebView(Context context) {
695 this(context, null);
696 }
697
698 /**
699 * Construct a new WebView with layout parameters.
700 * @param context A Context object used to access application assets.
701 * @param attrs An AttributeSet passed to our parent.
702 */
703 public WebView(Context context, AttributeSet attrs) {
704 this(context, attrs, com.android.internal.R.attr.webViewStyle);
705 }
706
707 /**
708 * Construct a new WebView with layout parameters and a default style.
709 * @param context A Context object used to access application assets.
710 * @param attrs An AttributeSet passed to our parent.
711 * @param defStyle The default style resource ID.
712 */
713 public WebView(Context context, AttributeSet attrs, int defStyle) {
Andrei Popescu4950b2b2009-09-03 13:56:07 +0100714 this(context, attrs, defStyle, null);
715 }
716
717 /**
718 * Construct a new WebView with layout parameters, a default style and a set
719 * of custom Javscript interfaces to be added to the WebView at initialization
720 * time. This guraratees that these interfaces will be available when the JS
721 * context is initialized.
722 * @param context A Context object used to access application assets.
723 * @param attrs An AttributeSet passed to our parent.
724 * @param defStyle The default style resource ID.
725 * @param javascriptInterfaces is a Map of intareface names, as keys, and
726 * object implementing those interfaces, as values.
727 * @hide pending API council approval.
728 */
729 protected WebView(Context context, AttributeSet attrs, int defStyle,
730 Map<String, Object> javascriptInterfaces) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731 super(context, attrs, defStyle);
732 init();
733
734 mCallbackProxy = new CallbackProxy(context, this);
Andrei Popescu4950b2b2009-09-03 13:56:07 +0100735 mWebViewCore = new WebViewCore(context, this, mCallbackProxy, javascriptInterfaces);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 mDatabase = WebViewDatabase.getInstance(context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 mScroller = new Scroller(context);
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700738
Patrick Scott0a5ce012009-07-02 08:56:10 -0400739 mViewManager = new ViewManager(this);
740
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -0700741 mZoomButtonsController = new ZoomButtonsController(this);
742 mZoomButtonsController.setOnZoomListener(mZoomListener);
Leon Scrogginsaa3f96a2009-06-11 14:46:35 -0400743 // ZoomButtonsController positions the buttons at the bottom, but in
744 // the middle. Change their layout parameters so they appear on the
745 // right.
746 View controls = mZoomButtonsController.getZoomControls();
747 ViewGroup.LayoutParams params = controls.getLayoutParams();
748 if (params instanceof FrameLayout.LayoutParams) {
749 FrameLayout.LayoutParams frameParams = (FrameLayout.LayoutParams)
750 params;
751 frameParams.gravity = Gravity.RIGHT;
752 }
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700753 }
754
755 private void updateZoomButtonsEnabled() {
The Android Open Source Project10592532009-03-18 17:39:46 -0700756 boolean canZoomIn = mActualScale < mMaxZoomScale;
Grace Kloba455e3af2009-08-13 11:01:21 -0700757 boolean canZoomOut = mActualScale > mMinZoomScale && !mInZoomOverview;
The Android Open Source Project10592532009-03-18 17:39:46 -0700758 if (!canZoomIn && !canZoomOut) {
759 // Hide the zoom in and out buttons, as well as the fit to page
760 // button, if the page cannot zoom
761 mZoomButtonsController.getZoomControls().setVisibility(View.GONE);
The Android Open Source Project10592532009-03-18 17:39:46 -0700762 } else {
763 // Bring back the hidden zoom controls.
764 mZoomButtonsController.getZoomControls()
765 .setVisibility(View.VISIBLE);
The Android Open Source Project10592532009-03-18 17:39:46 -0700766 // Set each one individually, as a page may be able to zoom in
767 // or out.
768 mZoomButtonsController.setZoomInEnabled(canZoomIn);
769 mZoomButtonsController.setZoomOutEnabled(canZoomOut);
The Android Open Source Project10592532009-03-18 17:39:46 -0700770 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 }
772
773 private void init() {
774 setWillNotDraw(false);
775 setFocusable(true);
776 setFocusableInTouchMode(true);
777 setClickable(true);
778 setLongClickable(true);
779
Romain Guy4296fc42009-07-06 11:48:52 -0700780 final ViewConfiguration configuration = ViewConfiguration.get(getContext());
Grace Kloba8b97e4b2009-07-28 13:11:38 -0700781 int slop = configuration.getScaledTouchSlop();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 mTouchSlopSquare = slop * slop;
783 mMinLockSnapReverseDistance = slop;
Grace Kloba8b97e4b2009-07-28 13:11:38 -0700784 slop = configuration.getScaledDoubleTapSlop();
785 mDoubleTapSlopSquare = slop * slop;
Grace Kloba25737912009-06-19 12:42:47 -0700786 final float density = getContext().getResources().getDisplayMetrics().density;
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700787 // use one line height, 16 based on our current default font, for how
788 // far we allow a touch be away from the edge of a link
Grace Kloba25737912009-06-19 12:42:47 -0700789 mNavSlop = (int) (16 * density);
790 // density adjusted scale factors
791 DEFAULT_SCALE_PERCENT = (int) (100 * density);
Grace Kloba0d8b77c2009-06-25 11:20:51 -0700792 mDefaultScale = density;
Grace Kloba25737912009-06-19 12:42:47 -0700793 mActualScale = density;
794 mInvActualScale = 1 / density;
795 DEFAULT_MAX_ZOOM_SCALE = 4.0f * density;
796 DEFAULT_MIN_ZOOM_SCALE = 0.25f * density;
797 mMaxZoomScale = DEFAULT_MAX_ZOOM_SCALE;
798 mMinZoomScale = DEFAULT_MIN_ZOOM_SCALE;
Romain Guy4296fc42009-07-06 11:48:52 -0700799 mMaximumFling = configuration.getScaledMaximumFlingVelocity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800 }
801
Grace Kloba0d8b77c2009-06-25 11:20:51 -0700802 /* package */void updateDefaultZoomDensity(int zoomDensity) {
803 final float density = getContext().getResources().getDisplayMetrics().density
804 * 100 / zoomDensity;
805 if (Math.abs(density - mDefaultScale) > 0.01) {
806 float scaleFactor = density / mDefaultScale;
807 // adjust the limits
808 mNavSlop = (int) (16 * density);
809 DEFAULT_SCALE_PERCENT = (int) (100 * density);
810 DEFAULT_MAX_ZOOM_SCALE = 4.0f * density;
811 DEFAULT_MIN_ZOOM_SCALE = 0.25f * density;
812 mDefaultScale = density;
813 mMaxZoomScale *= scaleFactor;
814 mMinZoomScale *= scaleFactor;
815 setNewZoomScale(mActualScale * scaleFactor, false);
816 }
817 }
818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 /* package */ boolean onSavePassword(String schemePlusHost, String username,
820 String password, final Message resumeMsg) {
821 boolean rVal = false;
822 if (resumeMsg == null) {
823 // null resumeMsg implies saving password silently
824 mDatabase.setUsernamePassword(schemePlusHost, username, password);
825 } else {
826 final Message remember = mPrivateHandler.obtainMessage(
827 REMEMBER_PASSWORD);
828 remember.getData().putString("host", schemePlusHost);
829 remember.getData().putString("username", username);
830 remember.getData().putString("password", password);
831 remember.obj = resumeMsg;
832
833 final Message neverRemember = mPrivateHandler.obtainMessage(
834 NEVER_REMEMBER_PASSWORD);
835 neverRemember.getData().putString("host", schemePlusHost);
836 neverRemember.getData().putString("username", username);
837 neverRemember.getData().putString("password", password);
838 neverRemember.obj = resumeMsg;
839
840 new AlertDialog.Builder(getContext())
841 .setTitle(com.android.internal.R.string.save_password_label)
842 .setMessage(com.android.internal.R.string.save_password_message)
843 .setPositiveButton(com.android.internal.R.string.save_password_notnow,
844 new DialogInterface.OnClickListener() {
845 public void onClick(DialogInterface dialog, int which) {
846 resumeMsg.sendToTarget();
847 }
848 })
849 .setNeutralButton(com.android.internal.R.string.save_password_remember,
850 new DialogInterface.OnClickListener() {
851 public void onClick(DialogInterface dialog, int which) {
852 remember.sendToTarget();
853 }
854 })
855 .setNegativeButton(com.android.internal.R.string.save_password_never,
856 new DialogInterface.OnClickListener() {
857 public void onClick(DialogInterface dialog, int which) {
858 neverRemember.sendToTarget();
859 }
860 })
861 .setOnCancelListener(new OnCancelListener() {
862 public void onCancel(DialogInterface dialog) {
863 resumeMsg.sendToTarget();
864 }
865 }).show();
866 // Return true so that WebViewCore will pause while the dialog is
867 // up.
868 rVal = true;
869 }
870 return rVal;
871 }
872
873 @Override
874 public void setScrollBarStyle(int style) {
875 if (style == View.SCROLLBARS_INSIDE_INSET
876 || style == View.SCROLLBARS_OUTSIDE_INSET) {
877 mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = false;
878 } else {
879 mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = true;
880 }
881 super.setScrollBarStyle(style);
882 }
883
884 /**
885 * Specify whether the horizontal scrollbar has overlay style.
886 * @param overlay TRUE if horizontal scrollbar should have overlay style.
887 */
888 public void setHorizontalScrollbarOverlay(boolean overlay) {
889 mOverlayHorizontalScrollbar = overlay;
890 }
891
892 /**
893 * Specify whether the vertical scrollbar has overlay style.
894 * @param overlay TRUE if vertical scrollbar should have overlay style.
895 */
896 public void setVerticalScrollbarOverlay(boolean overlay) {
897 mOverlayVerticalScrollbar = overlay;
898 }
899
900 /**
901 * Return whether horizontal scrollbar has overlay style
902 * @return TRUE if horizontal scrollbar has overlay style.
903 */
904 public boolean overlayHorizontalScrollbar() {
905 return mOverlayHorizontalScrollbar;
906 }
907
908 /**
909 * Return whether vertical scrollbar has overlay style
910 * @return TRUE if vertical scrollbar has overlay style.
911 */
912 public boolean overlayVerticalScrollbar() {
913 return mOverlayVerticalScrollbar;
914 }
915
916 /*
917 * Return the width of the view where the content of WebView should render
918 * to.
Grace Kloba6ed525e2009-09-17 15:31:12 -0700919 * Note: this can be called from WebCoreThread.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920 */
Grace Kloba6ed525e2009-09-17 15:31:12 -0700921 /* package */ int getViewWidth() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 if (!isVerticalScrollBarEnabled() || mOverlayVerticalScrollbar) {
923 return getWidth();
924 } else {
925 return getWidth() - getVerticalScrollbarWidth();
926 }
927 }
928
929 /*
Mike Reede8853fc2009-09-04 14:01:48 -0400930 * returns the height of the titlebarview (if any). Does not care about
931 * scrolling
932 */
933 private int getTitleHeight() {
934 return mTitleBar != null ? mTitleBar.getHeight() : 0;
935 }
936
937 /*
938 * Return the amount of the titlebarview (if any) that is visible
939 */
940 private int getVisibleTitleHeight() {
941 return Math.max(getTitleHeight() - mScrollY, 0);
942 }
943
944 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 * Return the height of the view where the content of WebView should render
Leon Scroggins0236e672009-09-02 21:12:08 -0400946 * to. Note that this excludes mTitleBar, if there is one.
Grace Kloba6ed525e2009-09-17 15:31:12 -0700947 * Note: this can be called from WebCoreThread.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 */
Grace Kloba6ed525e2009-09-17 15:31:12 -0700949 /* package */ int getViewHeight() {
Grace Kloba8eff73f2009-09-24 09:34:32 -0700950 return getViewHeightWithTitle() - getVisibleTitleHeight();
951 }
952
953 private int getViewHeightWithTitle() {
Leon Scroggins0236e672009-09-02 21:12:08 -0400954 int height = getHeight();
Mike Reede8853fc2009-09-04 14:01:48 -0400955 if (isHorizontalScrollBarEnabled() && !mOverlayHorizontalScrollbar) {
Leon Scroggins0236e672009-09-02 21:12:08 -0400956 height -= getHorizontalScrollbarHeight();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 }
Grace Kloba8eff73f2009-09-24 09:34:32 -0700958 return height;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 }
960
961 /**
962 * @return The SSL certificate for the main top-level page or null if
963 * there is no certificate (the site is not secure).
964 */
965 public SslCertificate getCertificate() {
966 return mCertificate;
967 }
968
969 /**
970 * Sets the SSL certificate for the main top-level page.
971 */
972 public void setCertificate(SslCertificate certificate) {
973 // here, the certificate can be null (if the site is not secure)
974 mCertificate = certificate;
975 }
976
977 //-------------------------------------------------------------------------
978 // Methods called by activity
979 //-------------------------------------------------------------------------
980
981 /**
982 * Save the username and password for a particular host in the WebView's
983 * internal database.
984 * @param host The host that required the credentials.
985 * @param username The username for the given host.
986 * @param password The password for the given host.
987 */
988 public void savePassword(String host, String username, String password) {
989 mDatabase.setUsernamePassword(host, username, password);
990 }
991
992 /**
993 * Set the HTTP authentication credentials for a given host and realm.
994 *
995 * @param host The host for the credentials.
996 * @param realm The realm for the credentials.
997 * @param username The username for the password. If it is null, it means
998 * password can't be saved.
999 * @param password The password
1000 */
1001 public void setHttpAuthUsernamePassword(String host, String realm,
1002 String username, String password) {
1003 mDatabase.setHttpAuthUsernamePassword(host, realm, username, password);
1004 }
1005
1006 /**
1007 * Retrieve the HTTP authentication username and password for a given
1008 * host & realm pair
1009 *
1010 * @param host The host for which the credentials apply.
1011 * @param realm The realm for which the credentials apply.
1012 * @return String[] if found, String[0] is username, which can be null and
1013 * String[1] is password. Return null if it can't find anything.
1014 */
1015 public String[] getHttpAuthUsernamePassword(String host, String realm) {
1016 return mDatabase.getHttpAuthUsernamePassword(host, realm);
1017 }
1018
1019 /**
1020 * Destroy the internal state of the WebView. This method should be called
1021 * after the WebView has been removed from the view system. No other
1022 * methods may be called on a WebView after destroy.
1023 */
1024 public void destroy() {
1025 clearTextEntry();
1026 if (mWebViewCore != null) {
1027 // Set the handlers to null before destroying WebViewCore so no
Cary Clarkd6982c92009-05-29 11:02:22 -04001028 // more messages will be posted.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 mCallbackProxy.setWebViewClient(null);
1030 mCallbackProxy.setWebChromeClient(null);
1031 // Tell WebViewCore to destroy itself
1032 WebViewCore webViewCore = mWebViewCore;
1033 mWebViewCore = null; // prevent using partial webViewCore
1034 webViewCore.destroy();
1035 // Remove any pending messages that might not be serviced yet.
1036 mPrivateHandler.removeCallbacksAndMessages(null);
1037 mCallbackProxy.removeCallbacksAndMessages(null);
1038 // Wake up the WebCore thread just in case it is waiting for a
1039 // javascript dialog.
1040 synchronized (mCallbackProxy) {
1041 mCallbackProxy.notify();
1042 }
1043 }
1044 if (mNativeClass != 0) {
1045 nativeDestroy();
1046 mNativeClass = 0;
1047 }
1048 }
1049
1050 /**
1051 * Enables platform notifications of data state and proxy changes.
1052 */
1053 public static void enablePlatformNotifications() {
1054 Network.enablePlatformNotifications();
1055 }
1056
1057 /**
1058 * If platform notifications are enabled, this should be called
Mike Reedd205d5b2009-05-27 11:02:29 -04001059 * from the Activity's onPause() or onStop().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 */
1061 public static void disablePlatformNotifications() {
1062 Network.disablePlatformNotifications();
1063 }
Cary Clarkd6982c92009-05-29 11:02:22 -04001064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 /**
Feng Qianb3081372009-06-29 15:55:18 -07001066 * Sets JavaScript engine flags.
1067 *
1068 * @param flags JS engine flags in a String
1069 *
1070 * @hide pending API solidification
1071 */
1072 public void setJsFlags(String flags) {
1073 mWebViewCore.sendMessage(EventHub.SET_JS_FLAGS, flags);
1074 }
1075
1076 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 * Inform WebView of the network state. This is used to set
1078 * the javascript property window.navigator.isOnline and
1079 * generates the online/offline event as specified in HTML5, sec. 5.7.7
1080 * @param networkUp boolean indicating if network is available
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 */
1082 public void setNetworkAvailable(boolean networkUp) {
Grace Klobaa72cc092009-04-02 08:50:17 -07001083 mWebViewCore.sendMessage(EventHub.SET_NETWORK_STATE,
1084 networkUp ? 1 : 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 }
1086
1087 /**
Cary Clarkd6982c92009-05-29 11:02:22 -04001088 * Save the state of this WebView used in
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 * {@link android.app.Activity#onSaveInstanceState}. Please note that this
1090 * method no longer stores the display data for this WebView. The previous
1091 * behavior could potentially leak files if {@link #restoreState} was never
1092 * called. See {@link #savePicture} and {@link #restorePicture} for saving
1093 * and restoring the display data.
1094 * @param outState The Bundle to store the WebView state.
1095 * @return The same copy of the back/forward list used to save the state. If
1096 * saveState fails, the returned list will be null.
1097 * @see #savePicture
1098 * @see #restorePicture
1099 */
1100 public WebBackForwardList saveState(Bundle outState) {
1101 if (outState == null) {
1102 return null;
1103 }
1104 // We grab a copy of the back/forward list because a client of WebView
1105 // may have invalidated the history list by calling clearHistory.
1106 WebBackForwardList list = copyBackForwardList();
1107 final int currentIndex = list.getCurrentIndex();
1108 final int size = list.getSize();
1109 // We should fail saving the state if the list is empty or the index is
1110 // not in a valid range.
1111 if (currentIndex < 0 || currentIndex >= size || size == 0) {
1112 return null;
1113 }
1114 outState.putInt("index", currentIndex);
1115 // FIXME: This should just be a byte[][] instead of ArrayList but
1116 // Parcel.java does not have the code to handle multi-dimensional
1117 // arrays.
1118 ArrayList<byte[]> history = new ArrayList<byte[]>(size);
1119 for (int i = 0; i < size; i++) {
1120 WebHistoryItem item = list.getItemAtIndex(i);
Cary Clark4fbf81b2009-09-29 16:07:56 -04001121 if (null == item) {
1122 // FIXME: this shouldn't happen
1123 // need to determine how item got set to null
1124 Log.w(LOGTAG, "saveState: Unexpected null history item.");
1125 return null;
1126 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001127 byte[] data = item.getFlattenedData();
1128 if (data == null) {
1129 // It would be very odd to not have any data for a given history
1130 // item. And we will fail to rebuild the history list without
1131 // flattened data.
1132 return null;
1133 }
1134 history.add(data);
1135 }
1136 outState.putSerializable("history", history);
1137 if (mCertificate != null) {
1138 outState.putBundle("certificate",
1139 SslCertificate.saveState(mCertificate));
1140 }
1141 return list;
1142 }
1143
1144 /**
1145 * Save the current display data to the Bundle given. Used in conjunction
1146 * with {@link #saveState}.
1147 * @param b A Bundle to store the display data.
1148 * @param dest The file to store the serialized picture data. Will be
1149 * overwritten with this WebView's picture data.
1150 * @return True if the picture was successfully saved.
1151 */
1152 public boolean savePicture(Bundle b, File dest) {
1153 if (dest == null || b == null) {
1154 return false;
1155 }
1156 final Picture p = capturePicture();
1157 try {
1158 final FileOutputStream out = new FileOutputStream(dest);
1159 p.writeToStream(out);
1160 out.close();
1161 } catch (FileNotFoundException e){
1162 e.printStackTrace();
1163 } catch (IOException e) {
1164 e.printStackTrace();
1165 } catch (RuntimeException e) {
1166 e.printStackTrace();
1167 }
1168 if (dest.length() > 0) {
1169 b.putInt("scrollX", mScrollX);
1170 b.putInt("scrollY", mScrollY);
1171 b.putFloat("scale", mActualScale);
Grace Kloba8b97e4b2009-07-28 13:11:38 -07001172 if (mInZoomOverview) {
1173 b.putFloat("lastScale", mLastScale);
1174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 return true;
1176 }
1177 return false;
1178 }
1179
1180 /**
1181 * Restore the display data that was save in {@link #savePicture}. Used in
1182 * conjunction with {@link #restoreState}.
1183 * @param b A Bundle containing the saved display data.
1184 * @param src The file where the picture data was stored.
1185 * @return True if the picture was successfully restored.
1186 */
1187 public boolean restorePicture(Bundle b, File src) {
1188 if (src == null || b == null) {
1189 return false;
1190 }
1191 if (src.exists()) {
1192 Picture p = null;
1193 try {
1194 final FileInputStream in = new FileInputStream(src);
1195 p = Picture.createFromStream(in);
1196 in.close();
1197 } catch (FileNotFoundException e){
1198 e.printStackTrace();
1199 } catch (RuntimeException e) {
1200 e.printStackTrace();
1201 } catch (IOException e) {
1202 e.printStackTrace();
1203 }
1204 if (p != null) {
1205 int sx = b.getInt("scrollX", 0);
1206 int sy = b.getInt("scrollY", 0);
1207 float scale = b.getFloat("scale", 1.0f);
1208 mDrawHistory = true;
1209 mHistoryPicture = p;
1210 mScrollX = sx;
1211 mScrollY = sy;
1212 mHistoryWidth = Math.round(p.getWidth() * scale);
1213 mHistoryHeight = Math.round(p.getHeight() * scale);
1214 // as getWidth() / getHeight() of the view are not
1215 // available yet, set up mActualScale, so that when
1216 // onSizeChanged() is called, the rest will be set
1217 // correctly
1218 mActualScale = scale;
Grace Kloba8b97e4b2009-07-28 13:11:38 -07001219 float lastScale = b.getFloat("lastScale", -1.0f);
1220 if (lastScale > 0) {
1221 mInZoomOverview = true;
1222 mLastScale = lastScale;
1223 } else {
1224 mInZoomOverview = false;
1225 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 invalidate();
1227 return true;
1228 }
1229 }
1230 return false;
1231 }
1232
1233 /**
1234 * Restore the state of this WebView from the given map used in
Cary Clarkd6982c92009-05-29 11:02:22 -04001235 * {@link android.app.Activity#onRestoreInstanceState}. This method should
1236 * be called to restore the state of the WebView before using the object. If
1237 * it is called after the WebView has had a chance to build state (load
1238 * pages, create a back/forward list, etc.) there may be undesirable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239 * side-effects. Please note that this method no longer restores the
1240 * display data for this WebView. See {@link #savePicture} and {@link
1241 * #restorePicture} for saving and restoring the display data.
1242 * @param inState The incoming Bundle of state.
1243 * @return The restored back/forward list or null if restoreState failed.
1244 * @see #savePicture
1245 * @see #restorePicture
1246 */
1247 public WebBackForwardList restoreState(Bundle inState) {
1248 WebBackForwardList returnList = null;
1249 if (inState == null) {
1250 return returnList;
1251 }
1252 if (inState.containsKey("index") && inState.containsKey("history")) {
1253 mCertificate = SslCertificate.restoreState(
1254 inState.getBundle("certificate"));
1255
1256 final WebBackForwardList list = mCallbackProxy.getBackForwardList();
1257 final int index = inState.getInt("index");
1258 // We can't use a clone of the list because we need to modify the
1259 // shared copy, so synchronize instead to prevent concurrent
1260 // modifications.
1261 synchronized (list) {
1262 final List<byte[]> history =
1263 (List<byte[]>) inState.getSerializable("history");
1264 final int size = history.size();
1265 // Check the index bounds so we don't crash in native code while
1266 // restoring the history index.
1267 if (index < 0 || index >= size) {
1268 return null;
1269 }
1270 for (int i = 0; i < size; i++) {
1271 byte[] data = history.remove(0);
1272 if (data == null) {
1273 // If we somehow have null data, we cannot reconstruct
1274 // the item and thus our history list cannot be rebuilt.
1275 return null;
1276 }
1277 WebHistoryItem item = new WebHistoryItem(data);
1278 list.addHistoryItem(item);
1279 }
1280 // Grab the most recent copy to return to the caller.
1281 returnList = copyBackForwardList();
1282 // Update the copy to have the correct index.
1283 returnList.setCurrentIndex(index);
1284 }
1285 // Remove all pending messages because we are restoring previous
1286 // state.
1287 mWebViewCore.removeMessages();
1288 // Send a restore state message.
1289 mWebViewCore.sendMessage(EventHub.RESTORE_STATE, index);
1290 }
1291 return returnList;
1292 }
1293
1294 /**
1295 * Load the given url.
1296 * @param url The url of the resource to load.
1297 */
1298 public void loadUrl(String url) {
Patrick Scott4c3ca702009-07-15 15:41:05 -04001299 if (url == null) {
1300 return;
1301 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 switchOutDrawHistory();
1303 mWebViewCore.sendMessage(EventHub.LOAD_URL, url);
1304 clearTextEntry();
1305 }
1306
1307 /**
Grace Kloba57534302009-05-22 18:55:02 -07001308 * Load the url with postData using "POST" method into the WebView. If url
1309 * is not a network url, it will be loaded with {link
1310 * {@link #loadUrl(String)} instead.
Cary Clarkd6982c92009-05-29 11:02:22 -04001311 *
Grace Kloba57534302009-05-22 18:55:02 -07001312 * @param url The url of the resource to load.
1313 * @param postData The data will be passed to "POST" request.
Grace Kloba57534302009-05-22 18:55:02 -07001314 */
1315 public void postUrl(String url, byte[] postData) {
1316 if (URLUtil.isNetworkUrl(url)) {
1317 switchOutDrawHistory();
Cary Clarkded054c2009-06-15 10:26:08 -04001318 WebViewCore.PostUrlData arg = new WebViewCore.PostUrlData();
1319 arg.mUrl = url;
1320 arg.mPostData = postData;
Grace Kloba57534302009-05-22 18:55:02 -07001321 mWebViewCore.sendMessage(EventHub.POST_URL, arg);
1322 clearTextEntry();
1323 } else {
1324 loadUrl(url);
1325 }
1326 }
1327
1328 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 * Load the given data into the WebView. This will load the data into
1330 * WebView using the data: scheme. Content loaded through this mechanism
1331 * does not have the ability to load content from the network.
1332 * @param data A String of data in the given encoding.
1333 * @param mimeType The MIMEType of the data. i.e. text/html, image/jpeg
1334 * @param encoding The encoding of the data. i.e. utf-8, base64
1335 */
1336 public void loadData(String data, String mimeType, String encoding) {
1337 loadUrl("data:" + mimeType + ";" + encoding + "," + data);
1338 }
1339
1340 /**
1341 * Load the given data into the WebView, use the provided URL as the base
1342 * URL for the content. The base URL is the URL that represents the page
1343 * that is loaded through this interface. As such, it is used for the
1344 * history entry and to resolve any relative URLs. The failUrl is used if
1345 * browser fails to load the data provided. If it is empty or null, and the
1346 * load fails, then no history entry is created.
1347 * <p>
1348 * Note for post 1.0. Due to the change in the WebKit, the access to asset
1349 * files through "file:///android_asset/" for the sub resources is more
1350 * restricted. If you provide null or empty string as baseUrl, you won't be
1351 * able to access asset files. If the baseUrl is anything other than
1352 * http(s)/ftp(s)/about/javascript as scheme, you can access asset files for
1353 * sub resources.
Cary Clarkd6982c92009-05-29 11:02:22 -04001354 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 * @param baseUrl Url to resolve relative paths with, if null defaults to
1356 * "about:blank"
1357 * @param data A String of data in the given encoding.
1358 * @param mimeType The MIMEType of the data. i.e. text/html. If null,
1359 * defaults to "text/html"
1360 * @param encoding The encoding of the data. i.e. utf-8, us-ascii
1361 * @param failUrl URL to use if the content fails to load or null.
1362 */
1363 public void loadDataWithBaseURL(String baseUrl, String data,
1364 String mimeType, String encoding, String failUrl) {
Cary Clarkd6982c92009-05-29 11:02:22 -04001365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366 if (baseUrl != null && baseUrl.toLowerCase().startsWith("data:")) {
1367 loadData(data, mimeType, encoding);
1368 return;
1369 }
1370 switchOutDrawHistory();
Cary Clarkded054c2009-06-15 10:26:08 -04001371 WebViewCore.BaseUrlData arg = new WebViewCore.BaseUrlData();
1372 arg.mBaseUrl = baseUrl;
1373 arg.mData = data;
1374 arg.mMimeType = mimeType;
1375 arg.mEncoding = encoding;
1376 arg.mFailUrl = failUrl;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 mWebViewCore.sendMessage(EventHub.LOAD_DATA, arg);
1378 clearTextEntry();
1379 }
1380
1381 /**
1382 * Stop the current load.
1383 */
1384 public void stopLoading() {
1385 // TODO: should we clear all the messages in the queue before sending
1386 // STOP_LOADING?
1387 switchOutDrawHistory();
1388 mWebViewCore.sendMessage(EventHub.STOP_LOADING);
1389 }
1390
1391 /**
1392 * Reload the current url.
1393 */
1394 public void reload() {
Leon Scroggins74077c82009-09-14 18:56:48 -04001395 clearTextEntry();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 switchOutDrawHistory();
1397 mWebViewCore.sendMessage(EventHub.RELOAD);
1398 }
1399
1400 /**
1401 * Return true if this WebView has a back history item.
1402 * @return True iff this WebView has a back history item.
1403 */
1404 public boolean canGoBack() {
1405 WebBackForwardList l = mCallbackProxy.getBackForwardList();
1406 synchronized (l) {
1407 if (l.getClearPending()) {
1408 return false;
1409 } else {
1410 return l.getCurrentIndex() > 0;
1411 }
1412 }
1413 }
1414
1415 /**
1416 * Go back in the history of this WebView.
1417 */
1418 public void goBack() {
1419 goBackOrForward(-1);
1420 }
1421
1422 /**
1423 * Return true if this WebView has a forward history item.
1424 * @return True iff this Webview has a forward history item.
1425 */
1426 public boolean canGoForward() {
1427 WebBackForwardList l = mCallbackProxy.getBackForwardList();
1428 synchronized (l) {
1429 if (l.getClearPending()) {
1430 return false;
1431 } else {
1432 return l.getCurrentIndex() < l.getSize() - 1;
1433 }
1434 }
1435 }
1436
1437 /**
1438 * Go forward in the history of this WebView.
1439 */
1440 public void goForward() {
1441 goBackOrForward(1);
1442 }
1443
1444 /**
1445 * Return true if the page can go back or forward the given
1446 * number of steps.
1447 * @param steps The negative or positive number of steps to move the
1448 * history.
1449 */
1450 public boolean canGoBackOrForward(int steps) {
1451 WebBackForwardList l = mCallbackProxy.getBackForwardList();
1452 synchronized (l) {
1453 if (l.getClearPending()) {
1454 return false;
1455 } else {
1456 int newIndex = l.getCurrentIndex() + steps;
1457 return newIndex >= 0 && newIndex < l.getSize();
1458 }
1459 }
1460 }
1461
1462 /**
1463 * Go to the history item that is the number of steps away from
1464 * the current item. Steps is negative if backward and positive
1465 * if forward.
1466 * @param steps The number of steps to take back or forward in the back
1467 * forward list.
1468 */
1469 public void goBackOrForward(int steps) {
1470 goBackOrForward(steps, false);
1471 }
1472
1473 private void goBackOrForward(int steps, boolean ignoreSnapshot) {
1474 // every time we go back or forward, we want to reset the
1475 // WebView certificate:
1476 // if the new site is secure, we will reload it and get a
1477 // new certificate set;
1478 // if the new site is not secure, the certificate must be
1479 // null, and that will be the case
1480 mCertificate = null;
1481 if (steps != 0) {
1482 clearTextEntry();
1483 mWebViewCore.sendMessage(EventHub.GO_BACK_FORWARD, steps,
1484 ignoreSnapshot ? 1 : 0);
1485 }
1486 }
Cary Clarkd6982c92009-05-29 11:02:22 -04001487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 private boolean extendScroll(int y) {
1489 int finalY = mScroller.getFinalY();
1490 int newY = pinLocY(finalY + y);
1491 if (newY == finalY) return false;
1492 mScroller.setFinalY(newY);
1493 mScroller.extendDuration(computeDuration(0, y));
1494 return true;
1495 }
Cary Clarkd6982c92009-05-29 11:02:22 -04001496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 /**
1498 * Scroll the contents of the view up by half the view size
1499 * @param top true to jump to the top of the page
1500 * @return true if the page was scrolled
1501 */
1502 public boolean pageUp(boolean top) {
1503 if (mNativeClass == 0) {
1504 return false;
1505 }
Cary Clarke872f3a2009-06-11 09:51:11 -04001506 nativeClearCursor(); // start next trackball movement from page edge
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 if (top) {
1508 // go to the top of the document
1509 return pinScrollTo(mScrollX, 0, true, 0);
1510 }
1511 // Page up
1512 int h = getHeight();
1513 int y;
1514 if (h > 2 * PAGE_SCROLL_OVERLAP) {
1515 y = -h + PAGE_SCROLL_OVERLAP;
1516 } else {
1517 y = -h / 2;
1518 }
1519 mUserScroll = true;
Cary Clarkd6982c92009-05-29 11:02:22 -04001520 return mScroller.isFinished() ? pinScrollBy(0, y, true, 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 : extendScroll(y);
1522 }
Cary Clarkd6982c92009-05-29 11:02:22 -04001523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 /**
1525 * Scroll the contents of the view down by half the page size
1526 * @param bottom true to jump to bottom of page
1527 * @return true if the page was scrolled
1528 */
1529 public boolean pageDown(boolean bottom) {
1530 if (mNativeClass == 0) {
1531 return false;
1532 }
Cary Clarke872f3a2009-06-11 09:51:11 -04001533 nativeClearCursor(); // start next trackball movement from page edge
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 if (bottom) {
1535 return pinScrollTo(mScrollX, mContentHeight, true, 0);
1536 }
1537 // Page down.
1538 int h = getHeight();
1539 int y;
1540 if (h > 2 * PAGE_SCROLL_OVERLAP) {
1541 y = h - PAGE_SCROLL_OVERLAP;
1542 } else {
1543 y = h / 2;
1544 }
1545 mUserScroll = true;
Cary Clarkd6982c92009-05-29 11:02:22 -04001546 return mScroller.isFinished() ? pinScrollBy(0, y, true, 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 : extendScroll(y);
1548 }
1549
1550 /**
1551 * Clear the view so that onDraw() will draw nothing but white background,
1552 * and onMeasure() will return 0 if MeasureSpec is not MeasureSpec.EXACTLY
1553 */
1554 public void clearView() {
1555 mContentWidth = 0;
1556 mContentHeight = 0;
1557 mWebViewCore.sendMessage(EventHub.CLEAR_CONTENT);
1558 }
Cary Clarkd6982c92009-05-29 11:02:22 -04001559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 /**
1561 * Return a new picture that captures the current display of the webview.
1562 * This is a copy of the display, and will be unaffected if the webview
1563 * later loads a different URL.
1564 *
1565 * @return a picture containing the current contents of the view. Note this
1566 * picture is of the entire document, and is not restricted to the
1567 * bounds of the view.
1568 */
1569 public Picture capturePicture() {
Cary Clarkd6982c92009-05-29 11:02:22 -04001570 if (null == mWebViewCore) return null; // check for out of memory tab
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 return mWebViewCore.copyContentPicture();
1572 }
1573
1574 /**
1575 * Return true if the browser is displaying a TextView for text input.
1576 */
1577 private boolean inEditingMode() {
Leon Scrogginsd3465f62009-06-02 10:57:54 -04001578 return mWebTextView != null && mWebTextView.getParent() != null
1579 && mWebTextView.hasFocus();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 }
1581
1582 private void clearTextEntry() {
1583 if (inEditingMode()) {
Leon Scrogginsd3465f62009-06-02 10:57:54 -04001584 mWebTextView.remove();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 }
1586 }
1587
Cary Clarkd6982c92009-05-29 11:02:22 -04001588 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 * Return the current scale of the WebView
1590 * @return The current scale.
1591 */
1592 public float getScale() {
1593 return mActualScale;
1594 }
1595
1596 /**
1597 * Set the initial scale for the WebView. 0 means default. If
1598 * {@link WebSettings#getUseWideViewPort()} is true, it zooms out all the
1599 * way. Otherwise it starts with 100%. If initial scale is greater than 0,
1600 * WebView starts will this value as initial scale.
1601 *
1602 * @param scaleInPercent The initial scale in percent.
1603 */
1604 public void setInitialScale(int scaleInPercent) {
1605 mInitialScale = scaleInPercent;
1606 }
1607
1608 /**
1609 * Invoke the graphical zoom picker widget for this WebView. This will
1610 * result in the zoom widget appearing on the screen to control the zoom
1611 * level of this WebView.
1612 */
1613 public void invokeZoomPicker() {
1614 if (!getSettings().supportZoom()) {
1615 Log.w(LOGTAG, "This WebView doesn't support zoom.");
1616 return;
1617 }
1618 clearTextEntry();
The Android Open Source Project10592532009-03-18 17:39:46 -07001619 if (getSettings().getBuiltInZoomControls()) {
1620 mZoomButtonsController.setVisible(true);
1621 } else {
1622 mPrivateHandler.removeCallbacks(mZoomControlRunnable);
1623 mPrivateHandler.postDelayed(mZoomControlRunnable,
1624 ZOOM_CONTROLS_TIMEOUT);
1625 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 }
1627
1628 /**
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04001629 * Return a HitTestResult based on the current cursor node. If a HTML::a tag
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 * is found and the anchor has a non-javascript url, the HitTestResult type
1631 * is set to SRC_ANCHOR_TYPE and the url is set in the "extra" field. If the
1632 * anchor does not have a url or if it is a javascript url, the type will
1633 * be UNKNOWN_TYPE and the url has to be retrieved through
1634 * {@link #requestFocusNodeHref} asynchronously. If a HTML::img tag is
1635 * found, the HitTestResult type is set to IMAGE_TYPE and the url is set in
1636 * the "extra" field. A type of
1637 * SRC_IMAGE_ANCHOR_TYPE indicates an anchor with a url that has an image as
1638 * a child node. If a phone number is found, the HitTestResult type is set
1639 * to PHONE_TYPE and the phone number is set in the "extra" field of
1640 * HitTestResult. If a map address is found, the HitTestResult type is set
1641 * to GEO_TYPE and the address is set in the "extra" field of HitTestResult.
1642 * If an email address is found, the HitTestResult type is set to EMAIL_TYPE
1643 * and the email is set in the "extra" field of HitTestResult. Otherwise,
1644 * HitTestResult type is set to UNKNOWN_TYPE.
1645 */
1646 public HitTestResult getHitTestResult() {
1647 if (mNativeClass == 0) {
1648 return null;
1649 }
1650
1651 HitTestResult result = new HitTestResult();
Cary Clarkd6982c92009-05-29 11:02:22 -04001652 if (nativeHasCursorNode()) {
1653 if (nativeCursorIsTextInput()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 result.setType(HitTestResult.EDIT_TEXT_TYPE);
Cary Clarkd6982c92009-05-29 11:02:22 -04001655 } else {
1656 String text = nativeCursorText();
1657 if (text != null) {
1658 if (text.startsWith(SCHEME_TEL)) {
1659 result.setType(HitTestResult.PHONE_TYPE);
1660 result.setExtra(text.substring(SCHEME_TEL.length()));
1661 } else if (text.startsWith(SCHEME_MAILTO)) {
1662 result.setType(HitTestResult.EMAIL_TYPE);
1663 result.setExtra(text.substring(SCHEME_MAILTO.length()));
1664 } else if (text.startsWith(SCHEME_GEO)) {
1665 result.setType(HitTestResult.GEO_TYPE);
1666 result.setExtra(URLDecoder.decode(text
1667 .substring(SCHEME_GEO.length())));
1668 } else if (nativeCursorIsAnchor()) {
1669 result.setType(HitTestResult.SRC_ANCHOR_TYPE);
1670 result.setExtra(text);
1671 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 }
1673 }
1674 }
1675 int type = result.getType();
1676 if (type == HitTestResult.UNKNOWN_TYPE
1677 || type == HitTestResult.SRC_ANCHOR_TYPE) {
1678 // Now check to see if it is an image.
Leon Scroggins0236e672009-09-02 21:12:08 -04001679 int contentX = viewToContentX((int) mLastTouchX + mScrollX);
1680 int contentY = viewToContentY((int) mLastTouchY + mScrollY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 String text = nativeImageURI(contentX, contentY);
1682 if (text != null) {
Cary Clarkd6982c92009-05-29 11:02:22 -04001683 result.setType(type == HitTestResult.UNKNOWN_TYPE ?
1684 HitTestResult.IMAGE_TYPE :
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1686 result.setExtra(text);
1687 }
1688 }
1689 return result;
1690 }
1691
1692 /**
1693 * Request the href of an anchor element due to getFocusNodePath returning
1694 * "href." If hrefMsg is null, this method returns immediately and does not
1695 * dispatch hrefMsg to its target.
Cary Clarkd6982c92009-05-29 11:02:22 -04001696 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 * @param hrefMsg This message will be dispatched with the result of the
1698 * request as the data member with "url" as key. The result can
1699 * be null.
1700 */
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04001701 // FIXME: API change required to change the name of this function. We now
1702 // look at the cursor node, and not the focus node. Also, what is
1703 // getFocusNodePath?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 public void requestFocusNodeHref(Message hrefMsg) {
1705 if (hrefMsg == null || mNativeClass == 0) {
1706 return;
1707 }
Cary Clarkd6982c92009-05-29 11:02:22 -04001708 if (nativeCursorIsAnchor()) {
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04001709 mWebViewCore.sendMessage(EventHub.REQUEST_CURSOR_HREF,
Cary Clarkd6982c92009-05-29 11:02:22 -04001710 nativeCursorFramePointer(), nativeCursorNodePointer(),
1711 hrefMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 }
1713 }
Cary Clarkd6982c92009-05-29 11:02:22 -04001714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001715 /**
1716 * Request the url of the image last touched by the user. msg will be sent
1717 * to its target with a String representing the url as its object.
Cary Clarkd6982c92009-05-29 11:02:22 -04001718 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001719 * @param msg This message will be dispatched with the result of the request
1720 * as the data member with "url" as key. The result can be null.
1721 */
1722 public void requestImageRef(Message msg) {
Cary Clark7f970112009-10-15 15:29:08 -04001723 if (0 == mNativeClass) return; // client isn't initialized
Leon Scroggins0236e672009-09-02 21:12:08 -04001724 int contentX = viewToContentX((int) mLastTouchX + mScrollX);
1725 int contentY = viewToContentY((int) mLastTouchY + mScrollY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 String ref = nativeImageURI(contentX, contentY);
1727 Bundle data = msg.getData();
1728 data.putString("url", ref);
1729 msg.setData(data);
1730 msg.sendToTarget();
1731 }
1732
1733 private static int pinLoc(int x, int viewMax, int docMax) {
1734// Log.d(LOGTAG, "-- pinLoc " + x + " " + viewMax + " " + docMax);
1735 if (docMax < viewMax) { // the doc has room on the sides for "blank"
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001736 // pin the short document to the top/left of the screen
1737 x = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738// Log.d(LOGTAG, "--- center " + x);
1739 } else if (x < 0) {
1740 x = 0;
1741// Log.d(LOGTAG, "--- zero");
1742 } else if (x + viewMax > docMax) {
1743 x = docMax - viewMax;
1744// Log.d(LOGTAG, "--- pin " + x);
1745 }
1746 return x;
1747 }
1748
1749 // Expects x in view coordinates
1750 private int pinLocX(int x) {
1751 return pinLoc(x, getViewWidth(), computeHorizontalScrollRange());
1752 }
1753
1754 // Expects y in view coordinates
1755 private int pinLocY(int y) {
Mike Reede8853fc2009-09-04 14:01:48 -04001756 int titleH = getTitleHeight();
1757 // if the titlebar is still visible, just pin against 0
1758 if (y <= titleH) {
1759 return Math.max(y, 0);
1760 }
1761 // convert to 0-based coordinate (subtract the title height)
1762 // pin(), and then add the title height back in
1763 return pinLoc(y - titleH, getViewHeight(),
1764 computeVerticalScrollRange()) + titleH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 }
1766
Leon Scroggins0236e672009-09-02 21:12:08 -04001767 /**
1768 * A title bar which is embedded in this WebView, and scrolls along with it
1769 * vertically, but not horizontally.
1770 */
1771 private View mTitleBar;
1772
1773 /**
Leon Scroggins58992ea2009-09-17 15:55:31 -04001774 * Since we draw the title bar ourselves, we removed the shadow from the
1775 * browser's activity. We do want a shadow at the bottom of the title bar,
1776 * or at the top of the screen if the title bar is not visible. This
1777 * drawable serves that purpose.
1778 */
1779 private Drawable mTitleShadow;
1780
1781 /**
Leon Scroggins0236e672009-09-02 21:12:08 -04001782 * Add or remove a title bar to be embedded into the WebView, and scroll
1783 * along with it vertically, while remaining in view horizontally. Pass
1784 * null to remove the title bar from the WebView, and return to drawing
1785 * the WebView normally without translating to account for the title bar.
1786 * @hide
1787 */
Leon Scroggins078c52c2009-09-04 16:58:09 -04001788 public void setEmbeddedTitleBar(View v) {
1789 if (mTitleBar == v) return;
1790 if (mTitleBar != null) {
Leon Scroggins0236e672009-09-02 21:12:08 -04001791 removeView(mTitleBar);
Leon Scroggins078c52c2009-09-04 16:58:09 -04001792 }
1793 if (null != v) {
Leon Scroggins0236e672009-09-02 21:12:08 -04001794 addView(v, new AbsoluteLayout.LayoutParams(
1795 ViewGroup.LayoutParams.FILL_PARENT,
Leon Scroggins078c52c2009-09-04 16:58:09 -04001796 ViewGroup.LayoutParams.WRAP_CONTENT, 0, 0));
Leon Scroggins58992ea2009-09-17 15:55:31 -04001797 if (mTitleShadow == null) {
1798 mTitleShadow = (Drawable) mContext.getResources().getDrawable(
1799 com.android.internal.R.drawable.title_bar_shadow);
1800 }
Leon Scroggins0236e672009-09-02 21:12:08 -04001801 }
1802 mTitleBar = v;
1803 }
1804
1805 /**
Leon Scrogginsd3997e52009-09-21 14:15:18 -04001806 * Given a distance in view space, convert it to content space. Note: this
1807 * does not reflect translation, just scaling, so this should not be called
1808 * with coordinates, but should be called for dimensions like width or
1809 * height.
1810 */
1811 private int viewToContentDimension(int d) {
1812 return Math.round(d * mInvActualScale);
1813 }
1814
1815 /**
Leon Scroggins0236e672009-09-02 21:12:08 -04001816 * Given an x coordinate in view space, convert it to content space. Also
1817 * may be used for absolute heights (such as for the WebTextView's
1818 * textSize, which is unaffected by the height of the title bar).
1819 */
1820 /*package*/ int viewToContentX(int x) {
Leon Scrogginsd3997e52009-09-21 14:15:18 -04001821 return viewToContentDimension(x);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 }
1823
Leon Scroggins0236e672009-09-02 21:12:08 -04001824 /**
1825 * Given a y coordinate in view space, convert it to content space.
1826 * Takes into account the height of the title bar if there is one
1827 * embedded into the WebView.
1828 */
1829 /*package*/ int viewToContentY(int y) {
Leon Scrogginsd3997e52009-09-21 14:15:18 -04001830 return viewToContentDimension(y - getTitleHeight());
Mike Reede8853fc2009-09-04 14:01:48 -04001831 }
1832
1833 /**
1834 * Given a distance in content space, convert it to view space. Note: this
1835 * does not reflect translation, just scaling, so this should not be called
1836 * with coordinates, but should be called for dimensions like width or
1837 * height.
1838 */
1839 /*package*/ int contentToViewDimension(int d) {
1840 return Math.round(d * mActualScale);
Leon Scroggins0236e672009-09-02 21:12:08 -04001841 }
1842
1843 /**
1844 * Given an x coordinate in content space, convert it to view
Leon Scrogginsd3997e52009-09-21 14:15:18 -04001845 * space.
Leon Scroggins0236e672009-09-02 21:12:08 -04001846 */
1847 /*package*/ int contentToViewX(int x) {
Mike Reede8853fc2009-09-04 14:01:48 -04001848 return contentToViewDimension(x);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001849 }
1850
Leon Scroggins0236e672009-09-02 21:12:08 -04001851 /**
1852 * Given a y coordinate in content space, convert it to view
1853 * space. Takes into account the height of the title bar.
1854 */
1855 /*package*/ int contentToViewY(int y) {
Mike Reede8853fc2009-09-04 14:01:48 -04001856 return contentToViewDimension(y) + getTitleHeight();
Leon Scroggins0236e672009-09-02 21:12:08 -04001857 }
1858
Mike Reede9e86b82009-09-15 11:26:53 -04001859 private Rect contentToViewRect(Rect x) {
1860 return new Rect(contentToViewX(x.left), contentToViewY(x.top),
1861 contentToViewX(x.right), contentToViewY(x.bottom));
1862 }
1863
1864 /* To invalidate a rectangle in content coordinates, we need to transform
1865 the rect into view coordinates, so we can then call invalidate(...).
1866
1867 Normally, we would just call contentToView[XY](...), which eventually
1868 calls Math.round(coordinate * mActualScale). However, for invalidates,
1869 we need to account for the slop that occurs with antialiasing. To
1870 address that, we are a little more liberal in the size of the rect that
1871 we invalidate.
1872
1873 This liberal calculation calls floor() for the top/left, and ceil() for
1874 the bottom/right coordinates. This catches the possible extra pixels of
1875 antialiasing that we might have missed with just round().
1876 */
1877
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878 // Called by JNI to invalidate the View, given rectangle coordinates in
1879 // content space
1880 private void viewInvalidate(int l, int t, int r, int b) {
Mike Reede9e86b82009-09-15 11:26:53 -04001881 final float scale = mActualScale;
1882 final int dy = getTitleHeight();
1883 invalidate((int)Math.floor(l * scale),
1884 (int)Math.floor(t * scale) + dy,
1885 (int)Math.ceil(r * scale),
1886 (int)Math.ceil(b * scale) + dy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 }
1888
1889 // Called by JNI to invalidate the View after a delay, given rectangle
1890 // coordinates in content space
1891 private void viewInvalidateDelayed(long delay, int l, int t, int r, int b) {
Mike Reede9e86b82009-09-15 11:26:53 -04001892 final float scale = mActualScale;
1893 final int dy = getTitleHeight();
1894 postInvalidateDelayed(delay,
1895 (int)Math.floor(l * scale),
1896 (int)Math.floor(t * scale) + dy,
1897 (int)Math.ceil(r * scale),
1898 (int)Math.ceil(b * scale) + dy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 }
1900
Mike Reede9e86b82009-09-15 11:26:53 -04001901 private void invalidateContentRect(Rect r) {
1902 viewInvalidate(r.left, r.top, r.right, r.bottom);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001903 }
1904
Cary Clark278ce052009-08-31 16:08:42 -04001905 // stop the scroll animation, and don't let a subsequent fling add
1906 // to the existing velocity
1907 private void abortAnimation() {
1908 mScroller.abortAnimation();
1909 mLastVelocity = 0;
1910 }
1911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001912 /* call from webcoreview.draw(), so we're still executing in the UI thread
1913 */
1914 private void recordNewContentSize(int w, int h, boolean updateLayout) {
1915
1916 // premature data from webkit, ignore
1917 if ((w | h) == 0) {
1918 return;
1919 }
Cary Clarkd6982c92009-05-29 11:02:22 -04001920
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921 // don't abort a scroll animation if we didn't change anything
1922 if (mContentWidth != w || mContentHeight != h) {
1923 // record new dimensions
1924 mContentWidth = w;
1925 mContentHeight = h;
1926 // If history Picture is drawn, don't update scroll. They will be
1927 // updated when we get out of that mode.
1928 if (!mDrawHistory) {
1929 // repin our scroll, taking into account the new content size
1930 int oldX = mScrollX;
1931 int oldY = mScrollY;
1932 mScrollX = pinLocX(mScrollX);
1933 mScrollY = pinLocY(mScrollY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 if (oldX != mScrollX || oldY != mScrollY) {
1935 sendOurVisibleRect();
1936 }
Leon Scrogginsd84e7d52009-09-29 11:11:45 -04001937 if (!mScroller.isFinished()) {
1938 // We are in the middle of a scroll. Repin the final scroll
1939 // position.
1940 mScroller.setFinalX(pinLocX(mScroller.getFinalX()));
1941 mScroller.setFinalY(pinLocY(mScroller.getFinalY()));
1942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 }
1944 }
1945 contentSizeChanged(updateLayout);
1946 }
1947
1948 private void setNewZoomScale(float scale, boolean force) {
1949 if (scale < mMinZoomScale) {
1950 scale = mMinZoomScale;
1951 } else if (scale > mMaxZoomScale) {
1952 scale = mMaxZoomScale;
1953 }
1954 if (scale != mActualScale || force) {
1955 if (mDrawHistory) {
1956 // If history Picture is drawn, don't update scroll. They will
1957 // be updated when we get out of that mode.
1958 if (scale != mActualScale && !mPreviewZoomOnly) {
1959 mCallbackProxy.onScaleChanged(mActualScale, scale);
1960 }
1961 mActualScale = scale;
1962 mInvActualScale = 1 / scale;
1963 if (!mPreviewZoomOnly) {
1964 sendViewSizeZoom();
1965 }
1966 } else {
1967 // update our scroll so we don't appear to jump
1968 // i.e. keep the center of the doc in the center of the view
1969
1970 int oldX = mScrollX;
1971 int oldY = mScrollY;
1972 float ratio = scale * mInvActualScale; // old inverse
1973 float sx = ratio * oldX + (ratio - 1) * mZoomCenterX;
Grace Klobac0c03af2009-09-17 11:01:44 -07001974 float sy = ratio * oldY + (ratio - 1)
1975 * (mZoomCenterY - getTitleHeight());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976
1977 // now update our new scale and inverse
1978 if (scale != mActualScale && !mPreviewZoomOnly) {
1979 mCallbackProxy.onScaleChanged(mActualScale, scale);
1980 }
1981 mActualScale = scale;
1982 mInvActualScale = 1 / scale;
1983
Patrick Scott0a5ce012009-07-02 08:56:10 -04001984 // Scale all the child views
1985 mViewManager.scaleAll();
1986
Cary Clarkd6982c92009-05-29 11:02:22 -04001987 // as we don't have animation for scaling, don't do animation
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001988 // for scrolling, as it causes weird intermediate state
1989 // pinScrollTo(Math.round(sx), Math.round(sy));
1990 mScrollX = pinLocX(Math.round(sx));
1991 mScrollY = pinLocY(Math.round(sy));
1992
1993 if (!mPreviewZoomOnly) {
1994 sendViewSizeZoom();
1995 sendOurVisibleRect();
1996 }
1997 }
1998 }
1999 }
2000
2001 // Used to avoid sending many visible rect messages.
2002 private Rect mLastVisibleRectSent;
2003 private Rect mLastGlobalRect;
2004
2005 private Rect sendOurVisibleRect() {
2006 Rect rect = new Rect();
2007 calcOurContentVisibleRect(rect);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 // Rect.equals() checks for null input.
2009 if (!rect.equals(mLastVisibleRectSent)) {
Cary Clarked56eda2009-06-18 09:48:47 -04002010 Point pos = new Point(rect.left, rect.top);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002011 mWebViewCore.sendMessage(EventHub.SET_SCROLL_OFFSET,
Cary Clarked56eda2009-06-18 09:48:47 -04002012 nativeMoveGeneration(), 0, pos);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002013 mLastVisibleRectSent = rect;
2014 }
2015 Rect globalRect = new Rect();
2016 if (getGlobalVisibleRect(globalRect)
2017 && !globalRect.equals(mLastGlobalRect)) {
Cary Clark3524be92009-06-22 13:09:11 -04002018 if (DebugFlags.WEB_VIEW) {
2019 Log.v(LOGTAG, "sendOurVisibleRect=(" + globalRect.left + ","
2020 + globalRect.top + ",r=" + globalRect.right + ",b="
2021 + globalRect.bottom);
2022 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023 // TODO: the global offset is only used by windowRect()
2024 // in ChromeClientAndroid ; other clients such as touch
2025 // and mouse events could return view + screen relative points.
2026 mWebViewCore.sendMessage(EventHub.SET_GLOBAL_BOUNDS, globalRect);
2027 mLastGlobalRect = globalRect;
2028 }
2029 return rect;
2030 }
2031
2032 // Sets r to be the visible rectangle of our webview in view coordinates
2033 private void calcOurVisibleRect(Rect r) {
2034 Point p = new Point();
2035 getGlobalVisibleRect(r, p);
2036 r.offset(-p.x, -p.y);
Cary Clark3524be92009-06-22 13:09:11 -04002037 if (mFindIsUp) {
Cary Clark5bb6b522009-09-21 11:58:31 -04002038 r.bottom -= mFindHeight;
Cary Clark3524be92009-06-22 13:09:11 -04002039 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002040 }
2041
2042 // Sets r to be our visible rectangle in content coordinates
2043 private void calcOurContentVisibleRect(Rect r) {
2044 calcOurVisibleRect(r);
Leon Scroggins0236e672009-09-02 21:12:08 -04002045 r.left = viewToContentX(r.left);
Leon Scroggins37df6a82009-09-23 10:31:23 -04002046 // viewToContentY will remove the total height of the title bar. Add
2047 // the visible height back in to account for the fact that if the title
2048 // bar is partially visible, the part of the visible rect which is
2049 // displaying our content is displaced by that amount.
Grace Kloba8eff73f2009-09-24 09:34:32 -07002050 r.top = viewToContentY(r.top + getVisibleTitleHeight());
Leon Scroggins0236e672009-09-02 21:12:08 -04002051 r.right = viewToContentX(r.right);
Grace Kloba8eff73f2009-09-24 09:34:32 -07002052 r.bottom = viewToContentY(r.bottom);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 }
2054
Grace Klobaef347ef2009-07-30 11:20:32 -07002055 static class ViewSizeData {
2056 int mWidth;
2057 int mHeight;
2058 int mTextWrapWidth;
2059 float mScale;
Cary Clark6d45acc2009-08-27 15:42:57 -04002060 boolean mIgnoreHeight;
Grace Klobaef347ef2009-07-30 11:20:32 -07002061 }
2062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002063 /**
2064 * Compute unzoomed width and height, and if they differ from the last
2065 * values we sent, send them to webkit (to be used has new viewport)
2066 *
2067 * @return true if new values were sent
2068 */
2069 private boolean sendViewSizeZoom() {
Grace Klobaef347ef2009-07-30 11:20:32 -07002070 int viewWidth = getViewWidth();
2071 int newWidth = Math.round(viewWidth * mInvActualScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002072 int newHeight = Math.round(getViewHeight() * mInvActualScale);
2073 /*
2074 * Because the native side may have already done a layout before the
2075 * View system was able to measure us, we have to send a height of 0 to
2076 * remove excess whitespace when we grow our width. This will trigger a
2077 * layout and a change in content size. This content size change will
2078 * mean that contentSizeChanged will either call this method directly or
2079 * indirectly from onSizeChanged.
2080 */
2081 if (newWidth > mLastWidthSent && mWrapContent) {
2082 newHeight = 0;
2083 }
2084 // Avoid sending another message if the dimensions have not changed.
2085 if (newWidth != mLastWidthSent || newHeight != mLastHeightSent) {
Grace Klobaef347ef2009-07-30 11:20:32 -07002086 ViewSizeData data = new ViewSizeData();
2087 data.mWidth = newWidth;
2088 data.mHeight = newHeight;
2089 // while in zoom overview mode, the text are wrapped to the screen
2090 // width matching mLastScale. So that we don't trigger re-flow while
2091 // toggling between overview mode and normal mode.
2092 data.mTextWrapWidth = mInZoomOverview ? Math.round(viewWidth
2093 / mLastScale) : newWidth;
2094 data.mScale = mActualScale;
Cary Clark6d45acc2009-08-27 15:42:57 -04002095 data.mIgnoreHeight = mZoomScale != 0 && !mHeightCanMeasure;
Grace Klobaef347ef2009-07-30 11:20:32 -07002096 mWebViewCore.sendMessage(EventHub.VIEW_SIZE_CHANGED, data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002097 mLastWidthSent = newWidth;
2098 mLastHeightSent = newHeight;
2099 return true;
2100 }
2101 return false;
2102 }
2103
2104 @Override
2105 protected int computeHorizontalScrollRange() {
2106 if (mDrawHistory) {
2107 return mHistoryWidth;
2108 } else {
Grace Klobae621d6f2009-09-11 13:20:39 -07002109 // to avoid rounding error caused unnecessary scrollbar, use floor
2110 return (int) Math.floor(mContentWidth * mActualScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111 }
2112 }
2113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002114 @Override
2115 protected int computeVerticalScrollRange() {
2116 if (mDrawHistory) {
2117 return mHistoryHeight;
2118 } else {
Grace Klobae621d6f2009-09-11 13:20:39 -07002119 // to avoid rounding error caused unnecessary scrollbar, use floor
2120 return (int) Math.floor(mContentHeight * mActualScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002121 }
2122 }
2123
Leon Scroggins0236e672009-09-02 21:12:08 -04002124 @Override
2125 protected int computeVerticalScrollOffset() {
Mike Reede8853fc2009-09-04 14:01:48 -04002126 return Math.max(mScrollY - getTitleHeight(), 0);
Leon Scroggins0236e672009-09-02 21:12:08 -04002127 }
2128
2129 @Override
2130 protected int computeVerticalScrollExtent() {
2131 return getViewHeight();
2132 }
2133
Mike Reede8853fc2009-09-04 14:01:48 -04002134 /** @hide */
2135 @Override
2136 protected void onDrawVerticalScrollBar(Canvas canvas,
2137 Drawable scrollBar,
2138 int l, int t, int r, int b) {
2139 scrollBar.setBounds(l, t + getVisibleTitleHeight(), r, b);
2140 scrollBar.draw(canvas);
2141 }
2142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002143 /**
2144 * Get the url for the current page. This is not always the same as the url
2145 * passed to WebViewClient.onPageStarted because although the load for
2146 * that url has begun, the current page may not have changed.
2147 * @return The url for the current page.
2148 */
2149 public String getUrl() {
2150 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2151 return h != null ? h.getUrl() : null;
2152 }
Cary Clarkd6982c92009-05-29 11:02:22 -04002153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002154 /**
Cary Clarkd6982c92009-05-29 11:02:22 -04002155 * Get the original url for the current page. This is not always the same
2156 * as the url passed to WebViewClient.onPageStarted because although the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002157 * load for that url has begun, the current page may not have changed.
2158 * Also, there may have been redirects resulting in a different url to that
2159 * originally requested.
2160 * @return The url that was originally requested for the current page.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002161 */
2162 public String getOriginalUrl() {
2163 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2164 return h != null ? h.getOriginalUrl() : null;
2165 }
2166
2167 /**
2168 * Get the title for the current page. This is the title of the current page
2169 * until WebViewClient.onReceivedTitle is called.
2170 * @return The title for the current page.
2171 */
2172 public String getTitle() {
2173 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2174 return h != null ? h.getTitle() : null;
2175 }
2176
2177 /**
2178 * Get the favicon for the current page. This is the favicon of the current
2179 * page until WebViewClient.onReceivedIcon is called.
2180 * @return The favicon for the current page.
2181 */
2182 public Bitmap getFavicon() {
2183 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2184 return h != null ? h.getFavicon() : null;
2185 }
2186
2187 /**
Patrick Scott2ba12622009-08-04 13:20:05 -04002188 * Get the touch icon url for the apple-touch-icon <link> element.
2189 * @hide
2190 */
2191 public String getTouchIconUrl() {
2192 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2193 return h != null ? h.getTouchIconUrl() : null;
2194 }
2195
2196 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002197 * Get the progress for the current page.
2198 * @return The progress for the current page between 0 and 100.
2199 */
2200 public int getProgress() {
2201 return mCallbackProxy.getProgress();
2202 }
Cary Clarkd6982c92009-05-29 11:02:22 -04002203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002204 /**
2205 * @return the height of the HTML content.
2206 */
2207 public int getContentHeight() {
2208 return mContentHeight;
2209 }
2210
2211 /**
Leon Scrogginsea96d1e2009-09-23 13:41:01 -04002212 * @return the width of the HTML content.
2213 * @hide
2214 */
2215 public int getContentWidth() {
2216 return mContentWidth;
2217 }
2218
2219 /**
Mike Reedd205d5b2009-05-27 11:02:29 -04002220 * Pause all layout, parsing, and javascript timers for all webviews. This
2221 * is a global requests, not restricted to just this webview. This can be
2222 * useful if the application has been paused.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002223 */
2224 public void pauseTimers() {
2225 mWebViewCore.sendMessage(EventHub.PAUSE_TIMERS);
2226 }
2227
2228 /**
Mike Reedd205d5b2009-05-27 11:02:29 -04002229 * Resume all layout, parsing, and javascript timers for all webviews.
2230 * This will resume dispatching all timers.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002231 */
2232 public void resumeTimers() {
2233 mWebViewCore.sendMessage(EventHub.RESUME_TIMERS);
2234 }
2235
2236 /**
Mike Reedd205d5b2009-05-27 11:02:29 -04002237 * Call this to pause any extra processing associated with this view and
2238 * its associated DOM/plugins/javascript/etc. For example, if the view is
2239 * taken offscreen, this could be called to reduce unnecessary CPU and/or
2240 * network traffic. When the view is again "active", call onResume().
2241 *
2242 * Note that this differs from pauseTimers(), which affects all views/DOMs
2243 * @hide
2244 */
2245 public void onPause() {
2246 if (!mIsPaused) {
2247 mIsPaused = true;
2248 mWebViewCore.sendMessage(EventHub.ON_PAUSE);
2249 }
2250 }
2251
2252 /**
2253 * Call this to balanace a previous call to onPause()
2254 * @hide
2255 */
2256 public void onResume() {
2257 if (mIsPaused) {
2258 mIsPaused = false;
2259 mWebViewCore.sendMessage(EventHub.ON_RESUME);
2260 }
2261 }
2262
2263 /**
2264 * Returns true if the view is paused, meaning onPause() was called. Calling
2265 * onResume() sets the paused state back to false.
2266 * @hide
2267 */
2268 public boolean isPaused() {
2269 return mIsPaused;
2270 }
2271
2272 /**
Derek Sollenbergere0155e92009-06-10 15:35:45 -04002273 * Call this to inform the view that memory is low so that it can
2274 * free any available memory.
2275 * @hide
2276 */
2277 public void freeMemory() {
2278 mWebViewCore.sendMessage(EventHub.FREE_MEMORY);
2279 }
2280
2281 /**
Mike Hearnadcd2ed2009-01-21 16:44:36 +01002282 * Clear the resource cache. Note that the cache is per-application, so
2283 * this will clear the cache for all WebViews used.
2284 *
2285 * @param includeDiskFiles If false, only the RAM cache is cleared.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002286 */
2287 public void clearCache(boolean includeDiskFiles) {
Mike Hearnadcd2ed2009-01-21 16:44:36 +01002288 // Note: this really needs to be a static method as it clears cache for all
2289 // WebView. But we need mWebViewCore to send message to WebCore thread, so
2290 // we can't make this static.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002291 mWebViewCore.sendMessage(EventHub.CLEAR_CACHE,
2292 includeDiskFiles ? 1 : 0, 0);
2293 }
2294
2295 /**
2296 * Make sure that clearing the form data removes the adapter from the
2297 * currently focused textfield if there is one.
2298 */
2299 public void clearFormData() {
2300 if (inEditingMode()) {
2301 AutoCompleteAdapter adapter = null;
Leon Scrogginsd3465f62009-06-02 10:57:54 -04002302 mWebTextView.setAdapterCustom(adapter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002303 }
2304 }
2305
2306 /**
2307 * Tell the WebView to clear its internal back/forward list.
2308 */
2309 public void clearHistory() {
2310 mCallbackProxy.getBackForwardList().setClearPending();
2311 mWebViewCore.sendMessage(EventHub.CLEAR_HISTORY);
2312 }
2313
2314 /**
2315 * Clear the SSL preferences table stored in response to proceeding with SSL
2316 * certificate errors.
2317 */
2318 public void clearSslPreferences() {
2319 mWebViewCore.sendMessage(EventHub.CLEAR_SSL_PREF_TABLE);
2320 }
2321
2322 /**
2323 * Return the WebBackForwardList for this WebView. This contains the
2324 * back/forward list for use in querying each item in the history stack.
2325 * This is a copy of the private WebBackForwardList so it contains only a
2326 * snapshot of the current state. Multiple calls to this method may return
2327 * different objects. The object returned from this method will not be
2328 * updated to reflect any new state.
2329 */
2330 public WebBackForwardList copyBackForwardList() {
2331 return mCallbackProxy.getBackForwardList().clone();
2332 }
2333
2334 /*
2335 * Highlight and scroll to the next occurance of String in findAll.
Cary Clarkd6982c92009-05-29 11:02:22 -04002336 * Wraps the page infinitely, and scrolls. Must be called after
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002337 * calling findAll.
2338 *
2339 * @param forward Direction to search.
2340 */
2341 public void findNext(boolean forward) {
Cary Clark7f970112009-10-15 15:29:08 -04002342 if (0 == mNativeClass) return; // client isn't initialized
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002343 nativeFindNext(forward);
2344 }
2345
2346 /*
2347 * Find all instances of find on the page and highlight them.
2348 * @param find String to find.
2349 * @return int The number of occurances of the String "find"
2350 * that were found.
2351 */
2352 public int findAll(String find) {
Cary Clark7f970112009-10-15 15:29:08 -04002353 if (0 == mNativeClass) return 0; // client isn't initialized
Cary Clark5bb6b522009-09-21 11:58:31 -04002354 if (mFindIsUp == false) {
2355 recordNewContentSize(mContentWidth, mContentHeight + mFindHeight,
2356 false);
2357 mFindIsUp = true;
2358 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002359 int result = nativeFindAll(find.toLowerCase(), find.toUpperCase());
2360 invalidate();
2361 return result;
2362 }
2363
2364 // Used to know whether the find dialog is open. Affects whether
2365 // or not we draw the highlights for matches.
2366 private boolean mFindIsUp;
Cary Clark5bb6b522009-09-21 11:58:31 -04002367 private int mFindHeight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002369 /**
Cary Clarkd6982c92009-05-29 11:02:22 -04002370 * Return the first substring consisting of the address of a physical
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002371 * location. Currently, only addresses in the United States are detected,
2372 * and consist of:
2373 * - a house number
2374 * - a street name
2375 * - a street type (Road, Circle, etc), either spelled out or abbreviated
2376 * - a city name
2377 * - a state or territory, either spelled out or two-letter abbr.
2378 * - an optional 5 digit or 9 digit zip code.
2379 *
2380 * All names must be correctly capitalized, and the zip code, if present,
2381 * must be valid for the state. The street type must be a standard USPS
2382 * spelling or abbreviation. The state or territory must also be spelled
Cary Clarkd6982c92009-05-29 11:02:22 -04002383 * or abbreviated using USPS standards. The house number may not exceed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002384 * five digits.
2385 * @param addr The string to search for addresses.
2386 *
2387 * @return the address, or if no address is found, return null.
2388 */
2389 public static String findAddress(String addr) {
Cary Clark3e399de2009-06-17 10:00:57 -04002390 return findAddress(addr, false);
2391 }
2392
2393 /**
2394 * @hide
2395 * Return the first substring consisting of the address of a physical
2396 * location. Currently, only addresses in the United States are detected,
2397 * and consist of:
2398 * - a house number
2399 * - a street name
2400 * - a street type (Road, Circle, etc), either spelled out or abbreviated
2401 * - a city name
2402 * - a state or territory, either spelled out or two-letter abbr.
2403 * - an optional 5 digit or 9 digit zip code.
2404 *
2405 * Names are optionally capitalized, and the zip code, if present,
2406 * must be valid for the state. The street type must be a standard USPS
2407 * spelling or abbreviation. The state or territory must also be spelled
2408 * or abbreviated using USPS standards. The house number may not exceed
2409 * five digits.
2410 * @param addr The string to search for addresses.
2411 * @param caseInsensitive addr Set to true to make search ignore case.
2412 *
2413 * @return the address, or if no address is found, return null.
2414 */
2415 public static String findAddress(String addr, boolean caseInsensitive) {
2416 return WebViewCore.nativeFindAddress(addr, caseInsensitive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002417 }
2418
2419 /*
2420 * Clear the highlighting surrounding text matches created by findAll.
2421 */
2422 public void clearMatches() {
Cary Clark5bb6b522009-09-21 11:58:31 -04002423 if (mFindIsUp) {
2424 recordNewContentSize(mContentWidth, mContentHeight - mFindHeight,
2425 false);
2426 mFindIsUp = false;
2427 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002428 nativeSetFindIsDown();
2429 // Now that the dialog has been removed, ensure that we scroll to a
2430 // location that is not beyond the end of the page.
2431 pinScrollTo(mScrollX, mScrollY, false, 0);
2432 invalidate();
2433 }
2434
2435 /**
Cary Clark5bb6b522009-09-21 11:58:31 -04002436 * @hide
2437 */
2438 public void setFindDialogHeight(int height) {
2439 if (DebugFlags.WEB_VIEW) {
2440 Log.v(LOGTAG, "setFindDialogHeight height=" + height);
2441 }
2442 mFindHeight = height;
2443 }
2444
2445 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002446 * Query the document to see if it contains any image references. The
2447 * message object will be dispatched with arg1 being set to 1 if images
2448 * were found and 0 if the document does not reference any images.
2449 * @param response The message that will be dispatched with the result.
2450 */
2451 public void documentHasImages(Message response) {
2452 if (response == null) {
2453 return;
2454 }
2455 mWebViewCore.sendMessage(EventHub.DOC_HAS_IMAGES, response);
2456 }
2457
2458 @Override
2459 public void computeScroll() {
2460 if (mScroller.computeScrollOffset()) {
2461 int oldX = mScrollX;
2462 int oldY = mScrollY;
2463 mScrollX = mScroller.getCurrX();
2464 mScrollY = mScroller.getCurrY();
2465 postInvalidate(); // So we draw again
2466 if (oldX != mScrollX || oldY != mScrollY) {
2467 // as onScrollChanged() is not called, sendOurVisibleRect()
2468 // needs to be call explicitly
2469 sendOurVisibleRect();
2470 }
2471 } else {
2472 super.computeScroll();
2473 }
2474 }
2475
2476 private static int computeDuration(int dx, int dy) {
2477 int distance = Math.max(Math.abs(dx), Math.abs(dy));
2478 int duration = distance * 1000 / STD_SPEED;
2479 return Math.min(duration, MAX_DURATION);
2480 }
2481
2482 // helper to pin the scrollBy parameters (already in view coordinates)
2483 // returns true if the scroll was changed
2484 private boolean pinScrollBy(int dx, int dy, boolean animate, int animationDuration) {
2485 return pinScrollTo(mScrollX + dx, mScrollY + dy, animate, animationDuration);
2486 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002487 // helper to pin the scrollTo parameters (already in view coordinates)
2488 // returns true if the scroll was changed
2489 private boolean pinScrollTo(int x, int y, boolean animate, int animationDuration) {
2490 x = pinLocX(x);
2491 y = pinLocY(y);
2492 int dx = x - mScrollX;
2493 int dy = y - mScrollY;
2494
2495 if ((dx | dy) == 0) {
2496 return false;
2497 }
Leon Scrogginsd55de402009-09-17 14:19:49 -04002498 if (animate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 // Log.d(LOGTAG, "startScroll: " + dx + " " + dy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002500 mScroller.startScroll(mScrollX, mScrollY, dx, dy,
2501 animationDuration > 0 ? animationDuration : computeDuration(dx, dy));
Mike Cleronf116bf82009-09-27 19:14:12 -07002502 awakenScrollBars(mScroller.getDuration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002503 invalidate();
2504 } else {
Cary Clark278ce052009-08-31 16:08:42 -04002505 abortAnimation(); // just in case
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002506 scrollTo(x, y);
2507 }
2508 return true;
2509 }
2510
2511 // Scale from content to view coordinates, and pin.
2512 // Also called by jni webview.cpp
Leon Scroggins4c943042009-07-31 15:05:42 -04002513 private boolean setContentScrollBy(int cx, int cy, boolean animate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 if (mDrawHistory) {
2515 // disallow WebView to change the scroll position as History Picture
2516 // is used in the view system.
2517 // TODO: as we switchOutDrawHistory when trackball or navigation
2518 // keys are hit, this should be safe. Right?
Leon Scroggins4c943042009-07-31 15:05:42 -04002519 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002520 }
Mike Reede8853fc2009-09-04 14:01:48 -04002521 cx = contentToViewDimension(cx);
2522 cy = contentToViewDimension(cy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 if (mHeightCanMeasure) {
2524 // move our visible rect according to scroll request
2525 if (cy != 0) {
2526 Rect tempRect = new Rect();
2527 calcOurVisibleRect(tempRect);
2528 tempRect.offset(cx, cy);
2529 requestRectangleOnScreen(tempRect);
2530 }
2531 // FIXME: We scroll horizontally no matter what because currently
2532 // ScrollView and ListView will not scroll horizontally.
2533 // FIXME: Why do we only scroll horizontally if there is no
2534 // vertical scroll?
2535// Log.d(LOGTAG, "setContentScrollBy cy=" + cy);
Leon Scroggins4c943042009-07-31 15:05:42 -04002536 return cy == 0 && cx != 0 && pinScrollBy(cx, 0, animate, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 } else {
Leon Scroggins4c943042009-07-31 15:05:42 -04002538 return pinScrollBy(cx, cy, animate, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002539 }
2540 }
2541
2542 // scale from content to view coordinates, and pin
Leon Scroggins83d4ba82009-09-17 17:27:13 -04002543 // return true if pin caused the final x/y different than the request cx/cy,
2544 // and a future scroll may reach the request cx/cy after our size has
2545 // changed
2546 // return false if the view scroll to the exact position as it is requested,
2547 // where negative numbers are taken to mean 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002548 private boolean setContentScrollTo(int cx, int cy) {
2549 if (mDrawHistory) {
2550 // disallow WebView to change the scroll position as History Picture
2551 // is used in the view system.
2552 // One known case where this is called is that WebCore tries to
2553 // restore the scroll position. As history Picture already uses the
2554 // saved scroll position, it is ok to skip this.
2555 return false;
2556 }
Leon Scrogginsd7b95aa2009-09-21 13:27:02 -04002557 int vx;
2558 int vy;
2559 if ((cx | cy) == 0) {
2560 // If the page is being scrolled to (0,0), do not add in the title
2561 // bar's height, and simply scroll to (0,0). (The only other work
2562 // in contentToView_ is to multiply, so this would not change 0.)
2563 vx = 0;
2564 vy = 0;
2565 } else {
2566 vx = contentToViewX(cx);
2567 vy = contentToViewY(cy);
2568 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569// Log.d(LOGTAG, "content scrollTo [" + cx + " " + cy + "] view=[" +
2570// vx + " " + vy + "]");
Leon Scroggins03c87bf2009-09-18 15:05:59 -04002571 // Some mobile sites attempt to scroll the title bar off the page by
Leon Scrogginsd7b95aa2009-09-21 13:27:02 -04002572 // scrolling to (0,1). If we are at the top left corner of the
Leon Scroggins03c87bf2009-09-18 15:05:59 -04002573 // page, assume this is an attempt to scroll off the title bar, and
2574 // animate the title bar off screen slowly enough that the user can see
2575 // it.
Leon Scrogginsd7b95aa2009-09-21 13:27:02 -04002576 if (cx == 0 && cy == 1 && mScrollX == 0 && mScrollY == 0) {
Leon Scroggins03c87bf2009-09-18 15:05:59 -04002577 pinScrollTo(vx, vy, true, SLIDE_TITLE_DURATION);
2578 // Since we are animating, we have not yet reached the desired
2579 // scroll position. Do not return true to request another attempt
2580 return false;
2581 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002582 pinScrollTo(vx, vy, false, 0);
Leon Scroggins83d4ba82009-09-17 17:27:13 -04002583 // If the request was to scroll to a negative coordinate, treat it as if
2584 // it was a request to scroll to 0
2585 if ((mScrollX != vx && cx >= 0) || (mScrollY != vy && cy >= 0)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002586 return true;
2587 } else {
2588 return false;
2589 }
2590 }
2591
2592 // scale from content to view coordinates, and pin
2593 private void spawnContentScrollTo(int cx, int cy) {
2594 if (mDrawHistory) {
2595 // disallow WebView to change the scroll position as History Picture
2596 // is used in the view system.
2597 return;
2598 }
Leon Scroggins0236e672009-09-02 21:12:08 -04002599 int vx = contentToViewX(cx);
2600 int vy = contentToViewY(cy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002601 pinScrollTo(vx, vy, true, 0);
2602 }
2603
2604 /**
2605 * These are from webkit, and are in content coordinate system (unzoomed)
2606 */
2607 private void contentSizeChanged(boolean updateLayout) {
2608 // suppress 0,0 since we usually see real dimensions soon after
2609 // this avoids drawing the prev content in a funny place. If we find a
2610 // way to consolidate these notifications, this check may become
2611 // obsolete
2612 if ((mContentWidth | mContentHeight) == 0) {
2613 return;
2614 }
2615
2616 if (mHeightCanMeasure) {
Mike Reede8853fc2009-09-04 14:01:48 -04002617 if (getMeasuredHeight() != contentToViewDimension(mContentHeight)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002618 && updateLayout) {
2619 requestLayout();
2620 }
2621 } else if (mWidthCanMeasure) {
Mike Reede8853fc2009-09-04 14:01:48 -04002622 if (getMeasuredWidth() != contentToViewDimension(mContentWidth)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002623 && updateLayout) {
2624 requestLayout();
2625 }
2626 } else {
2627 // If we don't request a layout, try to send our view size to the
2628 // native side to ensure that WebCore has the correct dimensions.
2629 sendViewSizeZoom();
2630 }
2631 }
2632
2633 /**
2634 * Set the WebViewClient that will receive various notifications and
2635 * requests. This will replace the current handler.
2636 * @param client An implementation of WebViewClient.
2637 */
2638 public void setWebViewClient(WebViewClient client) {
2639 mCallbackProxy.setWebViewClient(client);
2640 }
2641
2642 /**
Grace Kloba94ab3b62009-10-07 18:00:19 -07002643 * Gets the WebViewClient
2644 * @return the current WebViewClient instance.
2645 *
2646 *@hide pending API council approval.
2647 */
2648 public WebViewClient getWebViewClient() {
2649 return mCallbackProxy.getWebViewClient();
2650 }
2651
2652 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002653 * Register the interface to be used when content can not be handled by
2654 * the rendering engine, and should be downloaded instead. This will replace
2655 * the current handler.
2656 * @param listener An implementation of DownloadListener.
2657 */
2658 public void setDownloadListener(DownloadListener listener) {
2659 mCallbackProxy.setDownloadListener(listener);
2660 }
2661
2662 /**
2663 * Set the chrome handler. This is an implementation of WebChromeClient for
2664 * use in handling Javascript dialogs, favicons, titles, and the progress.
2665 * This will replace the current handler.
2666 * @param client An implementation of WebChromeClient.
2667 */
2668 public void setWebChromeClient(WebChromeClient client) {
2669 mCallbackProxy.setWebChromeClient(client);
2670 }
2671
2672 /**
Andrei Popescu6fa29582009-06-19 14:54:09 +01002673 * Gets the chrome handler.
2674 * @return the current WebChromeClient instance.
2675 *
2676 * @hide API council approval.
2677 */
2678 public WebChromeClient getWebChromeClient() {
2679 return mCallbackProxy.getWebChromeClient();
2680 }
2681
2682 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002683 * Set the Picture listener. This is an interface used to receive
2684 * notifications of a new Picture.
2685 * @param listener An implementation of WebView.PictureListener.
2686 */
2687 public void setPictureListener(PictureListener listener) {
2688 mPictureListener = listener;
2689 }
2690
2691 /**
2692 * {@hide}
2693 */
2694 /* FIXME: Debug only! Remove for SDK! */
2695 public void externalRepresentation(Message callback) {
2696 mWebViewCore.sendMessage(EventHub.REQUEST_EXT_REPRESENTATION, callback);
2697 }
2698
2699 /**
2700 * {@hide}
2701 */
2702 /* FIXME: Debug only! Remove for SDK! */
2703 public void documentAsText(Message callback) {
2704 mWebViewCore.sendMessage(EventHub.REQUEST_DOC_AS_TEXT, callback);
2705 }
2706
2707 /**
2708 * Use this function to bind an object to Javascript so that the
2709 * methods can be accessed from Javascript.
2710 * <p><strong>IMPORTANT:</strong>
2711 * <ul>
2712 * <li> Using addJavascriptInterface() allows JavaScript to control your
2713 * application. This can be a very useful feature or a dangerous security
2714 * issue. When the HTML in the WebView is untrustworthy (for example, part
2715 * or all of the HTML is provided by some person or process), then an
2716 * attacker could inject HTML that will execute your code and possibly any
2717 * code of the attacker's choosing.<br>
2718 * Do not use addJavascriptInterface() unless all of the HTML in this
2719 * WebView was written by you.</li>
2720 * <li> The Java object that is bound runs in another thread and not in
2721 * the thread that it was constructed in.</li>
2722 * </ul></p>
2723 * @param obj The class instance to bind to Javascript
2724 * @param interfaceName The name to used to expose the class in Javascript
2725 */
2726 public void addJavascriptInterface(Object obj, String interfaceName) {
Cary Clarkded054c2009-06-15 10:26:08 -04002727 WebViewCore.JSInterfaceData arg = new WebViewCore.JSInterfaceData();
2728 arg.mObject = obj;
2729 arg.mInterfaceName = interfaceName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002730 mWebViewCore.sendMessage(EventHub.ADD_JS_INTERFACE, arg);
2731 }
2732
2733 /**
2734 * Return the WebSettings object used to control the settings for this
2735 * WebView.
2736 * @return A WebSettings object that can be used to control this WebView's
2737 * settings.
2738 */
2739 public WebSettings getSettings() {
2740 return mWebViewCore.getSettings();
2741 }
2742
2743 /**
2744 * Return the list of currently loaded plugins.
2745 * @return The list of currently loaded plugins.
Andrei Popescu385df692009-08-13 11:59:57 +01002746 *
2747 * @deprecated This was used for Gears, which has been deprecated.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002748 */
Andrei Popescu385df692009-08-13 11:59:57 +01002749 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002750 public static synchronized PluginList getPluginList() {
Andrei Popescu385df692009-08-13 11:59:57 +01002751 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002752 }
2753
2754 /**
Andrei Popescu385df692009-08-13 11:59:57 +01002755 * @deprecated This was used for Gears, which has been deprecated.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002756 */
Andrei Popescu385df692009-08-13 11:59:57 +01002757 @Deprecated
2758 public void refreshPlugins(boolean reloadOpenPages) { }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002759
2760 //-------------------------------------------------------------------------
2761 // Override View methods
2762 //-------------------------------------------------------------------------
2763
2764 @Override
2765 protected void finalize() throws Throwable {
Cary Clark9a4c0632009-08-10 16:40:08 -04002766 try {
2767 destroy();
2768 } finally {
2769 super.finalize();
2770 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002771 }
Cary Clarkd6982c92009-05-29 11:02:22 -04002772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002773 @Override
Leon Scroggins0236e672009-09-02 21:12:08 -04002774 protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
2775 if (child == mTitleBar) {
2776 // When drawing the title bar, move it horizontally to always show
2777 // at the top of the WebView.
2778 mTitleBar.offsetLeftAndRight(mScrollX - mTitleBar.getLeft());
2779 }
2780 return super.drawChild(canvas, child, drawingTime);
2781 }
2782
2783 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002784 protected void onDraw(Canvas canvas) {
2785 // if mNativeClass is 0, the WebView has been destroyed. Do nothing.
2786 if (mNativeClass == 0) {
2787 return;
2788 }
Leon Scroggins58992ea2009-09-17 15:55:31 -04002789 int saveCount = canvas.save();
2790 if (mTitleBar != null) {
2791 canvas.translate(0, (int) mTitleBar.getHeight());
2792 }
Grace Kloba04b28682009-09-14 14:38:37 -07002793 // Update the buttons in the picture, so when we draw the picture
2794 // to the screen, they are in the correct state.
2795 // Tell the native side if user is a) touching the screen,
2796 // b) pressing the trackball down, or c) pressing the enter key
2797 // If the cursor is on a button, we need to draw it in the pressed
2798 // state.
2799 // If mNativeClass is 0, we should not reach here, so we do not
2800 // need to check it again.
2801 nativeRecordButtons(hasFocus() && hasWindowFocus(),
2802 mTouchMode == TOUCH_SHORTPRESS_START_MODE
2803 || mTrackballDown || mGotCenterDown, false);
2804 drawCoreAndCursorRing(canvas, mBackgroundColor, mDrawCursorRing);
Leon Scroggins0236e672009-09-02 21:12:08 -04002805 canvas.restoreToCount(saveCount);
Cary Clarkd6982c92009-05-29 11:02:22 -04002806
Leon Scroggins58992ea2009-09-17 15:55:31 -04002807 // Now draw the shadow.
2808 if (mTitleBar != null) {
2809 int y = mScrollY + getVisibleTitleHeight();
2810 int height = (int) (5f * getContext().getResources()
2811 .getDisplayMetrics().density);
2812 mTitleShadow.setBounds(mScrollX, y, mScrollX + getWidth(),
2813 y + height);
2814 mTitleShadow.draw(canvas);
2815 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816 if (AUTO_REDRAW_HACK && mAutoRedraw) {
2817 invalidate();
2818 }
2819 }
2820
2821 @Override
2822 public void setLayoutParams(ViewGroup.LayoutParams params) {
2823 if (params.height == LayoutParams.WRAP_CONTENT) {
2824 mWrapContent = true;
2825 }
2826 super.setLayoutParams(params);
2827 }
2828
2829 @Override
2830 public boolean performLongClick() {
Leon Scroggins3ccd3652009-06-26 17:22:50 -04002831 if (mNativeClass != 0 && nativeCursorIsTextInput()) {
2832 // Send the click so that the textfield is in focus
2833 // FIXME: When we start respecting changes to the native textfield's
2834 // selection, need to make sure that this does not change it.
2835 mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(),
2836 nativeCursorNodePointer());
2837 rebuildWebTextView();
2838 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002839 if (inEditingMode()) {
Leon Scrogginsd3465f62009-06-02 10:57:54 -04002840 return mWebTextView.performLongClick();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841 } else {
2842 return super.performLongClick();
2843 }
2844 }
2845
Grace Kloba94c715d2009-09-28 23:23:53 -07002846 boolean inAnimateZoom() {
2847 return mZoomScale != 0;
2848 }
2849
Leon Scroggins608f9f42009-09-03 10:06:04 -04002850 /**
2851 * Need to adjust the WebTextView after a change in zoom, since mActualScale
2852 * has changed. This is especially important for password fields, which are
2853 * drawn by the WebTextView, since it conveys more information than what
2854 * webkit draws. Thus we need to reposition it to show in the correct
2855 * place.
2856 */
2857 private boolean mNeedToAdjustWebTextView;
2858
Cary Clark5da9aeb2009-10-06 17:40:53 -04002859 private boolean didUpdateTextViewBounds(boolean allowIntersect) {
2860 Rect contentBounds = nativeFocusCandidateNodeBounds();
2861 Rect vBox = contentToViewRect(contentBounds);
2862 Rect visibleRect = new Rect();
2863 calcOurVisibleRect(visibleRect);
2864 if (allowIntersect ? Rect.intersects(visibleRect, vBox) :
2865 visibleRect.contains(vBox)) {
2866 mWebTextView.setRect(vBox.left, vBox.top, vBox.width(),
2867 vBox.height());
2868 return true;
2869 } else {
2870 return false;
2871 }
2872 }
2873
Cary Clarkd6982c92009-05-29 11:02:22 -04002874 private void drawCoreAndCursorRing(Canvas canvas, int color,
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04002875 boolean drawCursorRing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002876 if (mDrawHistory) {
2877 canvas.scale(mActualScale, mActualScale);
2878 canvas.drawPicture(mHistoryPicture);
2879 return;
2880 }
2881
2882 boolean animateZoom = mZoomScale != 0;
Cary Clark25415e22009-10-12 13:41:28 -04002883 boolean animateScroll = (!mScroller.isFinished()
2884 || mVelocityTracker != null)
2885 && (mTouchMode != TOUCH_DRAG_MODE ||
2886 mHeldMotionless != MOTIONLESS_TRUE);
2887 if (mTouchMode == TOUCH_DRAG_MODE) {
2888 if (mHeldMotionless == MOTIONLESS_PENDING) {
2889 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
2890 mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
2891 mHeldMotionless = MOTIONLESS_FALSE;
2892 }
2893 if (mHeldMotionless == MOTIONLESS_FALSE) {
2894 mPrivateHandler.sendMessageDelayed(mPrivateHandler
2895 .obtainMessage(DRAG_HELD_MOTIONLESS), MOTIONLESS_TIME);
2896 mHeldMotionless = MOTIONLESS_PENDING;
2897 }
2898 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002899 if (animateZoom) {
2900 float zoomScale;
2901 int interval = (int) (SystemClock.uptimeMillis() - mZoomStart);
2902 if (interval < ZOOM_ANIMATION_LENGTH) {
2903 float ratio = (float) interval / ZOOM_ANIMATION_LENGTH;
Cary Clarkd6982c92009-05-29 11:02:22 -04002904 zoomScale = 1.0f / (mInvInitialZoomScale
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002905 + (mInvFinalZoomScale - mInvInitialZoomScale) * ratio);
2906 invalidate();
2907 } else {
2908 zoomScale = mZoomScale;
2909 // set mZoomScale to be 0 as we have done animation
2910 mZoomScale = 0;
Grace Klobadfe095a2009-09-17 07:56:48 -07002911 // call invalidate() again to draw with the final filters
2912 invalidate();
Leon Scroggins608f9f42009-09-03 10:06:04 -04002913 if (mNeedToAdjustWebTextView) {
2914 mNeedToAdjustWebTextView = false;
Cary Clark5da9aeb2009-10-06 17:40:53 -04002915 // As a result of the zoom, the textfield is now on
2916 // screen. Place the WebTextView in its new place,
2917 // accounting for our new scroll/zoom values.
2918 if (didUpdateTextViewBounds(false)) {
Leon Scroggins10be7542009-09-30 18:01:38 -04002919 mWebTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
2920 contentToViewDimension(
2921 nativeFocusCandidateTextSize()));
Leon Scroggins10be7542009-09-30 18:01:38 -04002922 // If it is a password field, start drawing the
2923 // WebTextView once again.
2924 if (nativeFocusCandidateIsPassword()) {
2925 mWebTextView.setInPassword(true);
2926 }
2927 } else {
2928 // The textfield is now off screen. The user probably
2929 // was not zooming to see the textfield better. Remove
2930 // the WebTextView. If the user types a key, and the
2931 // textfield is still in focus, we will reconstruct
2932 // the WebTextView and scroll it back on screen.
2933 mWebTextView.remove();
Leon Scroggins608f9f42009-09-03 10:06:04 -04002934 }
2935 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002936 }
Grace Klobac0c03af2009-09-17 11:01:44 -07002937 // calculate the intermediate scroll position. As we need to use
2938 // zoomScale, we can't use pinLocX/Y directly. Copy the logic here.
Grace Kloba675c7d22009-07-23 09:21:21 -07002939 float scale = zoomScale * mInvInitialZoomScale;
2940 int tx = Math.round(scale * (mInitialScrollX + mZoomCenterX)
2941 - mZoomCenterX);
2942 tx = -pinLoc(tx, getViewWidth(), Math.round(mContentWidth
2943 * zoomScale)) + mScrollX;
Grace Klobac0c03af2009-09-17 11:01:44 -07002944 int titleHeight = getTitleHeight();
2945 int ty = Math.round(scale
2946 * (mInitialScrollY + mZoomCenterY - titleHeight)
2947 - (mZoomCenterY - titleHeight));
2948 ty = -(ty <= titleHeight ? Math.max(ty, 0) : pinLoc(ty
2949 - titleHeight, getViewHeight(), Math.round(mContentHeight
2950 * zoomScale)) + titleHeight) + mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002951 canvas.translate(tx, ty);
2952 canvas.scale(zoomScale, zoomScale);
Leon Scroggins608f9f42009-09-03 10:06:04 -04002953 if (inEditingMode() && !mNeedToAdjustWebTextView
2954 && mZoomScale != 0) {
2955 // The WebTextView is up. Keep track of this so we can adjust
2956 // its size and placement when we finish zooming
2957 mNeedToAdjustWebTextView = true;
2958 // If it is in password mode, turn it off so it does not draw
2959 // misplaced.
2960 if (nativeFocusCandidateIsPassword()) {
2961 mWebTextView.setInPassword(false);
2962 }
2963 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002964 } else {
2965 canvas.scale(mActualScale, mActualScale);
2966 }
2967
2968 mWebViewCore.drawContentPicture(canvas, color, animateZoom,
2969 animateScroll);
2970
2971 if (mNativeClass == 0) return;
Cary Clarkbadd8392009-10-15 13:32:08 -04002972 if (mShiftIsPressed && !animateZoom) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002973 if (mTouchSelection) {
2974 nativeDrawSelectionRegion(canvas);
2975 } else {
Cary Clarkbadd8392009-10-15 13:32:08 -04002976 nativeDrawSelection(canvas, mInvActualScale, getTitleHeight(),
2977 mSelectX, mSelectY, mExtendSelection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002978 }
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04002979 } else if (drawCursorRing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002980 if (mTouchMode == TOUCH_SHORTPRESS_START_MODE) {
2981 mTouchMode = TOUCH_SHORTPRESS_MODE;
2982 HitTestResult hitTest = getHitTestResult();
2983 if (hitTest != null &&
2984 hitTest.mType != HitTestResult.UNKNOWN_TYPE) {
2985 mPrivateHandler.sendMessageDelayed(mPrivateHandler
2986 .obtainMessage(SWITCH_TO_LONGPRESS),
2987 LONG_PRESS_TIMEOUT);
2988 }
2989 }
Cary Clarkd6982c92009-05-29 11:02:22 -04002990 nativeDrawCursorRing(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002991 }
2992 // When the FindDialog is up, only draw the matches if we are not in
2993 // the process of scrolling them into view.
2994 if (mFindIsUp && !animateScroll) {
2995 nativeDrawMatches(canvas);
2996 }
Cary Clark5da9aeb2009-10-06 17:40:53 -04002997 if (mFocusSizeChanged) {
2998 mFocusSizeChanged = false;
2999 didUpdateTextViewBounds(true);
3000 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003001 }
3002
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003003 // draw history
3004 private boolean mDrawHistory = false;
3005 private Picture mHistoryPicture = null;
3006 private int mHistoryWidth = 0;
3007 private int mHistoryHeight = 0;
3008
3009 // Only check the flag, can be called from WebCore thread
3010 boolean drawHistory() {
3011 return mDrawHistory;
3012 }
3013
3014 // Should only be called in UI thread
3015 void switchOutDrawHistory() {
3016 if (null == mWebViewCore) return; // CallbackProxy may trigger this
Cary Clarkbc2e33b2009-04-23 13:12:19 -04003017 if (mDrawHistory && mWebViewCore.pictureReady()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003018 mDrawHistory = false;
3019 invalidate();
3020 int oldScrollX = mScrollX;
3021 int oldScrollY = mScrollY;
3022 mScrollX = pinLocX(mScrollX);
3023 mScrollY = pinLocY(mScrollY);
3024 if (oldScrollX != mScrollX || oldScrollY != mScrollY) {
3025 mUserScroll = false;
3026 mWebViewCore.sendMessage(EventHub.SYNC_SCROLL, oldScrollX,
3027 oldScrollY);
3028 }
3029 sendOurVisibleRect();
3030 }
3031 }
3032
Cary Clarkd6982c92009-05-29 11:02:22 -04003033 WebViewCore.CursorData cursorData() {
3034 WebViewCore.CursorData result = new WebViewCore.CursorData();
3035 result.mMoveGeneration = nativeMoveGeneration();
3036 result.mFrame = nativeCursorFramePointer();
Cary Clarked56eda2009-06-18 09:48:47 -04003037 Point position = nativeCursorPosition();
3038 result.mX = position.x;
3039 result.mY = position.y;
Cary Clarkd6982c92009-05-29 11:02:22 -04003040 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003041 }
Cary Clarkd6982c92009-05-29 11:02:22 -04003042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003043 /**
3044 * Delete text from start to end in the focused textfield. If there is no
Cary Clarkd6982c92009-05-29 11:02:22 -04003045 * focus, or if start == end, silently fail. If start and end are out of
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003046 * order, swap them.
3047 * @param start Beginning of selection to delete.
3048 * @param end End of selection to delete.
3049 */
3050 /* package */ void deleteSelection(int start, int end) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003051 mTextGeneration++;
Leon Scroggins6679f2f2009-08-12 18:48:10 -04003052 WebViewCore.TextSelectionData data
3053 = new WebViewCore.TextSelectionData(start, end);
3054 mWebViewCore.sendMessage(EventHub.DELETE_SELECTION, mTextGeneration, 0,
3055 data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003056 }
3057
3058 /**
3059 * Set the selection to (start, end) in the focused textfield. If start and
3060 * end are out of order, swap them.
3061 * @param start Beginning of selection.
3062 * @param end End of selection.
3063 */
3064 /* package */ void setSelection(int start, int end) {
Cary Clark2f1d60c2009-06-03 08:05:53 -04003065 mWebViewCore.sendMessage(EventHub.SET_SELECTION, start, end);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003066 }
3067
3068 // Called by JNI when a touch event puts a textfield into focus.
Derek Sollenberger4c41e8d2009-06-29 13:49:27 -04003069 private void displaySoftKeyboard(boolean isTextView) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003070 InputMethodManager imm = (InputMethodManager)
3071 getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
Derek Sollenberger4c41e8d2009-06-29 13:49:27 -04003072
3073 if (isTextView) {
Grace Klobab641abf2009-09-16 17:28:24 -07003074 if (mWebTextView == null) return;
3075
Derek Sollenberger4c41e8d2009-06-29 13:49:27 -04003076 imm.showSoftInput(mWebTextView, 0);
Grace Kloba8b97e4b2009-07-28 13:11:38 -07003077 if (mInZoomOverview) {
3078 // if in zoom overview mode, call doDoubleTap() to bring it back
3079 // to normal mode so that user can enter text.
3080 doDoubleTap();
3081 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003082 }
Derek Sollenberger4c41e8d2009-06-29 13:49:27 -04003083 else { // used by plugins
3084 imm.showSoftInput(this, 0);
3085 }
3086 }
3087
3088 // Called by WebKit to instruct the UI to hide the keyboard
3089 private void hideSoftKeyboard() {
3090 InputMethodManager imm = (InputMethodManager)
3091 getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
3092
3093 imm.hideSoftInputFromWindow(this.getWindowToken(), 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003094 }
3095
Leon Scrogginsd3465f62009-06-02 10:57:54 -04003096 /*
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04003097 * This method checks the current focus and cursor and potentially rebuilds
Leon Scrogginsd3465f62009-06-02 10:57:54 -04003098 * mWebTextView to have the appropriate properties, such as password,
3099 * multiline, and what text it contains. It also removes it if necessary.
3100 */
Leon Scroggins01058282009-07-30 16:33:56 -04003101 /* package */ void rebuildWebTextView() {
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04003102 // If the WebView does not have focus, do nothing until it gains focus.
Grace Kloba04b28682009-09-14 14:38:37 -07003103 if (!hasFocus() && (null == mWebTextView || !mWebTextView.hasFocus())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003104 return;
3105 }
3106 boolean alreadyThere = inEditingMode();
Leon Scrogginsd3465f62009-06-02 10:57:54 -04003107 // inEditingMode can only return true if mWebTextView is non-null,
Leon Scroggins2ca912e2009-04-28 16:51:55 -04003108 // so we can safely call remove() if (alreadyThere)
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04003109 if (0 == mNativeClass || !nativeFocusCandidateIsTextInput()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003110 if (alreadyThere) {
Leon Scrogginsd3465f62009-06-02 10:57:54 -04003111 mWebTextView.remove();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003112 }
3113 return;
3114 }
Leon Scroggins2ca912e2009-04-28 16:51:55 -04003115 // At this point, we know we have found an input field, so go ahead
Leon Scrogginsd3465f62009-06-02 10:57:54 -04003116 // and create the WebTextView if necessary.
3117 if (mWebTextView == null) {
3118 mWebTextView = new WebTextView(mContext, WebView.this);
Leon Scroggins2ca912e2009-04-28 16:51:55 -04003119 // Initialize our generation number.
3120 mTextGeneration = 0;
3121 }
Leon Scroggins3a6c88c2009-09-09 14:50:23 -04003122 mWebTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
3123 contentToViewDimension(nativeFocusCandidateTextSize()));
Cary Clark3524be92009-06-22 13:09:11 -04003124 Rect visibleRect = new Rect();
3125 calcOurContentVisibleRect(visibleRect);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003126 // Note that sendOurVisibleRect calls viewToContent, so the coordinates
3127 // should be in content coordinates.
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04003128 Rect bounds = nativeFocusCandidateNodeBounds();
Cary Clarkd6982c92009-05-29 11:02:22 -04003129 if (!Rect.intersects(bounds, visibleRect)) {
Leon Scroggins40981262009-07-01 10:57:47 -04003130 mWebTextView.bringIntoView();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003131 }
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04003132 String text = nativeFocusCandidateText();
3133 int nodePointer = nativeFocusCandidatePointer();
Leon Scrogginsd3465f62009-06-02 10:57:54 -04003134 if (alreadyThere && mWebTextView.isSameTextField(nodePointer)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003135 // It is possible that we have the same textfield, but it has moved,
3136 // i.e. In the case of opening/closing the screen.
3137 // In that case, we need to set the dimensions, but not the other
3138 // aspects.
3139 // We also need to restore the selection, which gets wrecked by
3140 // calling setTextEntryRect.
Leon Scrogginsd3465f62009-06-02 10:57:54 -04003141 Spannable spannable = (Spannable) mWebTextView.getText();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003142 int start = Selection.getSelectionStart(spannable);
3143 int end = Selection.getSelectionEnd(spannable);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003144 // If the text has been changed by webkit, update it. However, if
3145 // there has been more UI text input, ignore it. We will receive
3146 // another update when that text is recognized.
Cary Clarkd6982c92009-05-29 11:02:22 -04003147 if (text != null && !text.equals(spannable.toString())
3148 && nativeTextGeneration() == mTextGeneration) {
Leon Scrogginsd3465f62009-06-02 10:57:54 -04003149 mWebTextView.setTextAndKeepSelection(text);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003150 } else {
3151 Selection.setSelection(spannable, start, end);
3152 }
3153 } else {
Mike Reede9e86b82009-09-15 11:26:53 -04003154 Rect vBox = contentToViewRect(bounds);
Leon Scrogginsd3465f62009-06-02 10:57:54 -04003155 mWebTextView.setRect(vBox.left, vBox.top, vBox.width(),
3156 vBox.height());
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04003157 mWebTextView.setGravity(nativeFocusCandidateIsRtlText() ?
3158 Gravity.RIGHT : Gravity.NO_GRAVITY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003159 // this needs to be called before update adapter thread starts to
Leon Scrogginsd3465f62009-06-02 10:57:54 -04003160 // ensure the mWebTextView has the same node pointer
3161 mWebTextView.setNodePointer(nodePointer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003162 int maxLength = -1;
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04003163 boolean isTextField = nativeFocusCandidateIsTextField();
Cary Clarkd6982c92009-05-29 11:02:22 -04003164 if (isTextField) {
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04003165 maxLength = nativeFocusCandidateMaxLength();
3166 String name = nativeFocusCandidateName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003167 if (mWebViewCore.getSettings().getSaveFormData()
Cary Clarkd6982c92009-05-29 11:02:22 -04003168 && name != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003169 Message update = mPrivateHandler.obtainMessage(
Cary Clarkded054c2009-06-15 10:26:08 -04003170 REQUEST_FORM_DATA, nodePointer);
Leon Scrogginsd3465f62009-06-02 10:57:54 -04003171 RequestFormData updater = new RequestFormData(name,
3172 getUrl(), update);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003173 Thread t = new Thread(updater);
3174 t.start();
3175 }
3176 }
Leon Scrogginsd3465f62009-06-02 10:57:54 -04003177 mWebTextView.setMaxLength(maxLength);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003178 AutoCompleteAdapter adapter = null;
Leon Scrogginsd3465f62009-06-02 10:57:54 -04003179 mWebTextView.setAdapterCustom(adapter);
3180 mWebTextView.setSingleLine(isTextField);
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04003181 mWebTextView.setInPassword(nativeFocusCandidateIsPassword());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003182 if (null == text) {
Leon Scrogginsd3465f62009-06-02 10:57:54 -04003183 mWebTextView.setText("", 0, 0);
Cary Clark243ea062009-06-25 10:49:32 -04003184 if (DebugFlags.WEB_VIEW) {
3185 Log.v(LOGTAG, "rebuildWebTextView null == text");
3186 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003187 } else {
3188 // Change to true to enable the old style behavior, where
3189 // entering a textfield/textarea always set the selection to the
3190 // whole field. This was desirable for the case where the user
3191 // intends to scroll past the field using the trackball.
3192 // However, it causes a problem when replying to emails - the
3193 // user expects the cursor to be at the beginning of the
3194 // textarea. Testing out a new behavior, where textfields set
3195 // selection at the end, and textareas at the beginning.
3196 if (false) {
Leon Scrogginsd3465f62009-06-02 10:57:54 -04003197 mWebTextView.setText(text, 0, text.length());
Cary Clarkd6982c92009-05-29 11:02:22 -04003198 } else if (isTextField) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199 int length = text.length();
Leon Scrogginsd3465f62009-06-02 10:57:54 -04003200 mWebTextView.setText(text, length, length);
Cary Clark243ea062009-06-25 10:49:32 -04003201 if (DebugFlags.WEB_VIEW) {
3202 Log.v(LOGTAG, "rebuildWebTextView length=" + length);
3203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003204 } else {
Leon Scrogginsd3465f62009-06-02 10:57:54 -04003205 mWebTextView.setText(text, 0, 0);
Cary Clark243ea062009-06-25 10:49:32 -04003206 if (DebugFlags.WEB_VIEW) {
3207 Log.v(LOGTAG, "rebuildWebTextView !isTextField");
3208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003209 }
3210 }
Leon Scrogginsd3465f62009-06-02 10:57:54 -04003211 mWebTextView.requestFocus();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003212 }
3213 }
3214
Leon Scrogginsd3465f62009-06-02 10:57:54 -04003215 /*
3216 * This class requests an Adapter for the WebTextView which shows past
3217 * entries stored in the database. It is a Runnable so that it can be done
3218 * in its own thread, without slowing down the UI.
3219 */
3220 private class RequestFormData implements Runnable {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003221 private String mName;
3222 private String mUrl;
3223 private Message mUpdateMessage;
3224
Leon Scrogginsd3465f62009-06-02 10:57:54 -04003225 public RequestFormData(String name, String url, Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003226 mName = name;
3227 mUrl = url;
3228 mUpdateMessage = msg;
3229 }
3230
3231 public void run() {
3232 ArrayList<String> pastEntries = mDatabase.getFormData(mUrl, mName);
3233 if (pastEntries.size() > 0) {
3234 AutoCompleteAdapter adapter = new
3235 AutoCompleteAdapter(mContext, pastEntries);
Cary Clarkded054c2009-06-15 10:26:08 -04003236 mUpdateMessage.obj = adapter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003237 mUpdateMessage.sendToTarget();
3238 }
3239 }
3240 }
3241
Leon Scrogginse3225672009-06-03 15:53:13 -04003242 // This is used to determine long press with the center key. Does not
3243 // affect long press with the trackball/touch.
3244 private boolean mGotCenterDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003245
3246 @Override
3247 public boolean onKeyDown(int keyCode, KeyEvent event) {
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04003248 if (DebugFlags.WEB_VIEW) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003249 Log.v(LOGTAG, "keyDown at " + System.currentTimeMillis()
Cary Clark215b72c2009-06-26 14:38:43 -04003250 + ", " + event + ", unicode=" + event.getUnicodeChar());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003251 }
3252
3253 if (mNativeClass == 0) {
3254 return false;
3255 }
3256
3257 // do this hack up front, so it always works, regardless of touch-mode
3258 if (AUTO_REDRAW_HACK && (keyCode == KeyEvent.KEYCODE_CALL)) {
3259 mAutoRedraw = !mAutoRedraw;
3260 if (mAutoRedraw) {
3261 invalidate();
3262 }
3263 return true;
3264 }
3265
3266 // Bubble up the key event if
3267 // 1. it is a system key; or
Grace Kloba04b28682009-09-14 14:38:37 -07003268 // 2. the host application wants to handle it;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003269 if (event.isSystem()
Grace Kloba04b28682009-09-14 14:38:37 -07003270 || mCallbackProxy.uiOverrideKeyEvent(event)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003271 return false;
3272 }
3273
Cary Clark2f1d60c2009-06-03 08:05:53 -04003274 if (mShiftIsPressed == false && nativeCursorWantsKeyEvents() == false
Cary Clarkd6982c92009-05-29 11:02:22 -04003275 && (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003276 || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT)) {
3277 mExtendSelection = false;
3278 mShiftIsPressed = true;
Cary Clarkd6982c92009-05-29 11:02:22 -04003279 if (nativeHasCursorNode()) {
3280 Rect rect = nativeCursorNodeBounds();
Leon Scroggins0236e672009-09-02 21:12:08 -04003281 mSelectX = contentToViewX(rect.left);
3282 mSelectY = contentToViewY(rect.top);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003283 } else {
3284 mSelectX = mScrollX + (int) mLastTouchX;
3285 mSelectY = mScrollY + (int) mLastTouchY;
3286 }
Cary Clarke872f3a2009-06-11 09:51:11 -04003287 nativeHideCursor();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003288 }
3289
3290 if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
3291 && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
3292 // always handle the navigation keys in the UI thread
3293 switchOutDrawHistory();
Cary Clarkc05af372009-10-16 10:52:27 -04003294 if (mShiftIsPressed) {
3295 int xRate = keyCode == KeyEvent.KEYCODE_DPAD_LEFT
3296 ? -1 : keyCode == KeyEvent.KEYCODE_DPAD_RIGHT ? 1 : 0;
3297 int yRate = keyCode == KeyEvent.KEYCODE_DPAD_UP ?
3298 -1 : keyCode == KeyEvent.KEYCODE_DPAD_DOWN ? 1 : 0;
3299 int multiplier = event.getRepeatCount() + 1;
3300 moveSelection(xRate * multiplier, yRate * multiplier);
3301 return true;
3302 }
Cary Clark215b72c2009-06-26 14:38:43 -04003303 if (navHandledKey(keyCode, 1, false, event.getEventTime(), false)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003304 playSoundEffect(keyCodeToSoundsEffect(keyCode));
3305 return true;
3306 }
3307 // Bubble up the key event as WebView doesn't handle it
3308 return false;
3309 }
3310
Leon Scrogginse3225672009-06-03 15:53:13 -04003311 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 switchOutDrawHistory();
3313 if (event.getRepeatCount() == 0) {
Cary Clarkc05af372009-10-16 10:52:27 -04003314 if (mShiftIsPressed) {
3315 return true; // discard press if copy in progress
3316 }
Leon Scrogginse3225672009-06-03 15:53:13 -04003317 mGotCenterDown = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003318 mPrivateHandler.sendMessageDelayed(mPrivateHandler
Leon Scrogginse3225672009-06-03 15:53:13 -04003319 .obtainMessage(LONG_PRESS_CENTER), LONG_PRESS_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003320 // Already checked mNativeClass, so we do not need to check it
3321 // again.
3322 nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true);
3323 return true;
3324 }
3325 // Bubble up the key event as WebView doesn't handle it
3326 return false;
3327 }
3328
Cary Clark843bbb82009-04-20 16:03:31 -04003329 if (keyCode != KeyEvent.KEYCODE_SHIFT_LEFT
3330 && keyCode != KeyEvent.KEYCODE_SHIFT_RIGHT) {
3331 // turn off copy select if a shift-key combo is pressed
3332 mExtendSelection = mShiftIsPressed = false;
3333 if (mTouchMode == TOUCH_SELECT_MODE) {
3334 mTouchMode = TOUCH_INIT_MODE;
3335 }
3336 }
3337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003338 if (getSettings().getNavDump()) {
3339 switch (keyCode) {
3340 case KeyEvent.KEYCODE_4:
3341 // "/data/data/com.android.browser/displayTree.txt"
3342 nativeDumpDisplayTree(getUrl());
3343 break;
3344 case KeyEvent.KEYCODE_5:
3345 case KeyEvent.KEYCODE_6:
3346 // 5: dump the dom tree to the file
3347 // "/data/data/com.android.browser/domTree.txt"
3348 // 6: dump the dom tree to the adb log
3349 mWebViewCore.sendMessage(EventHub.DUMP_DOMTREE,
3350 (keyCode == KeyEvent.KEYCODE_5) ? 1 : 0, 0);
3351 break;
3352 case KeyEvent.KEYCODE_7:
3353 case KeyEvent.KEYCODE_8:
3354 // 7: dump the render tree to the file
3355 // "/data/data/com.android.browser/renderTree.txt"
3356 // 8: dump the render tree to the adb log
3357 mWebViewCore.sendMessage(EventHub.DUMP_RENDERTREE,
3358 (keyCode == KeyEvent.KEYCODE_7) ? 1 : 0, 0);
3359 break;
3360 case KeyEvent.KEYCODE_9:
3361 nativeInstrumentReport();
3362 return true;
3363 }
3364 }
3365
Cary Clark3e88ddc2009-10-08 14:59:46 -04003366 if (nativeFocusCandidateIsPlugin()) {
Cary Clark215b72c2009-06-26 14:38:43 -04003367 nativeUpdatePluginReceivesEvents();
3368 invalidate();
Leon Scroggins0658e8f2009-06-26 14:09:09 -04003369 } else if (nativeCursorIsTextInput()) {
Leon Scroggins1cc24202009-06-16 10:10:28 -04003370 // This message will put the node in focus, for the DOM's notion
Leon Scroggins0658e8f2009-06-26 14:09:09 -04003371 // of focus, and make the focuscontroller active
Leon Scroggins01058282009-07-30 16:33:56 -04003372 mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(),
3373 nativeCursorNodePointer());
Leon Scroggins0658e8f2009-06-26 14:09:09 -04003374 // This will bring up the WebTextView and put it in focus, for
3375 // our view system's notion of focus
3376 rebuildWebTextView();
3377 // Now we need to pass the event to it
Leon Scrogginsc66f68a2009-10-02 15:12:30 -04003378 if (inEditingMode()) {
3379 return mWebTextView.onKeyDown(keyCode, event);
3380 }
Leon Scroggins40981262009-07-01 10:57:47 -04003381 } else if (nativeHasFocusNode()) {
3382 // In this case, the cursor is not on a text input, but the focus
3383 // might be. Check it, and if so, hand over to the WebTextView.
3384 rebuildWebTextView();
3385 if (inEditingMode()) {
3386 return mWebTextView.onKeyDown(keyCode, event);
3387 }
Cary Clark19436562009-06-04 16:25:07 -04003388 }
3389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003390 // TODO: should we pass all the keys to DOM or check the meta tag
Cary Clark2f1d60c2009-06-03 08:05:53 -04003391 if (nativeCursorWantsKeyEvents() || true) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003392 // pass the key to DOM
3393 mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
3394 // return true as DOM handles the key
3395 return true;
3396 }
3397
3398 // Bubble up the key event as WebView doesn't handle it
3399 return false;
3400 }
3401
3402 @Override
3403 public boolean onKeyUp(int keyCode, KeyEvent event) {
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04003404 if (DebugFlags.WEB_VIEW) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003405 Log.v(LOGTAG, "keyUp at " + System.currentTimeMillis()
Cary Clark215b72c2009-06-26 14:38:43 -04003406 + ", " + event + ", unicode=" + event.getUnicodeChar());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003407 }
3408
3409 if (mNativeClass == 0) {
3410 return false;
3411 }
3412
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04003413 // special CALL handling when cursor node's href is "tel:XXX"
Cary Clarkd6982c92009-05-29 11:02:22 -04003414 if (keyCode == KeyEvent.KEYCODE_CALL && nativeHasCursorNode()) {
3415 String text = nativeCursorText();
3416 if (!nativeCursorIsTextInput() && text != null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003417 && text.startsWith(SCHEME_TEL)) {
3418 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(text));
3419 getContext().startActivity(intent);
3420 return true;
3421 }
3422 }
3423
3424 // Bubble up the key event if
3425 // 1. it is a system key; or
3426 // 2. the host application wants to handle it;
3427 if (event.isSystem() || mCallbackProxy.uiOverrideKeyEvent(event)) {
3428 return false;
3429 }
3430
Cary Clarkd6982c92009-05-29 11:02:22 -04003431 if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003432 || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) {
3433 if (commitCopy()) {
3434 return true;
3435 }
3436 }
3437
3438 if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
3439 && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
3440 // always handle the navigation keys in the UI thread
3441 // Bubble up the key event as WebView doesn't handle it
3442 return false;
3443 }
3444
Leon Scrogginse3225672009-06-03 15:53:13 -04003445 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003446 // remove the long press message first
Leon Scrogginse3225672009-06-03 15:53:13 -04003447 mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
3448 mGotCenterDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003449
Leon Scrogginse3225672009-06-03 15:53:13 -04003450 if (mShiftIsPressed) {
Cary Clarkc05af372009-10-16 10:52:27 -04003451 if (mExtendSelection) {
3452 commitCopy();
3453 } else {
3454 mExtendSelection = true;
3455 }
3456 return true; // discard press if copy in progress
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003457 }
Grace Klobadd817492009-09-14 10:17:06 -07003458
3459 // perform the single click
3460 Rect visibleRect = sendOurVisibleRect();
3461 // Note that sendOurVisibleRect calls viewToContent, so the
3462 // coordinates should be in content coordinates.
3463 if (!nativeCursorIntersects(visibleRect)) {
3464 return false;
3465 }
3466 nativeSetFollowedLink(true);
3467 nativeUpdatePluginReceivesEvents();
3468 WebViewCore.CursorData data = cursorData();
3469 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, data);
3470 playSoundEffect(SoundEffectConstants.CLICK);
3471 boolean isTextInput = nativeCursorIsTextInput();
3472 if (isTextInput || !mCallbackProxy.uiOverrideUrlLoading(
3473 nativeCursorText())) {
3474 mWebViewCore.sendMessage(EventHub.CLICK, data.mFrame,
3475 nativeCursorNodePointer());
3476 }
3477 if (isTextInput) {
3478 rebuildWebTextView();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003479 }
Leon Scrogginse3225672009-06-03 15:53:13 -04003480 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003481 }
3482
3483 // TODO: should we pass all the keys to DOM or check the meta tag
Cary Clark2f1d60c2009-06-03 08:05:53 -04003484 if (nativeCursorWantsKeyEvents() || true) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003485 // pass the key to DOM
3486 mWebViewCore.sendMessage(EventHub.KEY_UP, event);
3487 // return true as DOM handles the key
3488 return true;
3489 }
3490
3491 // Bubble up the key event as WebView doesn't handle it
3492 return false;
3493 }
Cary Clarkd6982c92009-05-29 11:02:22 -04003494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003495 /**
3496 * @hide
3497 */
3498 public void emulateShiftHeld() {
Cary Clark7f970112009-10-15 15:29:08 -04003499 if (0 == mNativeClass) return; // client isn't initialized
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003500 mExtendSelection = false;
3501 mShiftIsPressed = true;
Cary Clarke872f3a2009-06-11 09:51:11 -04003502 nativeHideCursor();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003503 }
3504
3505 private boolean commitCopy() {
3506 boolean copiedSomething = false;
3507 if (mExtendSelection) {
3508 // copy region so core operates on copy without touching orig.
3509 Region selection = new Region(nativeGetSelection());
3510 if (selection.isEmpty() == false) {
3511 Toast.makeText(mContext
3512 , com.android.internal.R.string.text_copied
3513 , Toast.LENGTH_SHORT).show();
3514 mWebViewCore.sendMessage(EventHub.GET_SELECTION, selection);
3515 copiedSomething = true;
3516 }
3517 mExtendSelection = false;
3518 }
3519 mShiftIsPressed = false;
3520 if (mTouchMode == TOUCH_SELECT_MODE) {
3521 mTouchMode = TOUCH_INIT_MODE;
3522 }
3523 return copiedSomething;
3524 }
3525
3526 // Set this as a hierarchy change listener so we can know when this view
3527 // is removed and still have access to our parent.
3528 @Override
3529 protected void onAttachedToWindow() {
3530 super.onAttachedToWindow();
3531 ViewParent parent = getParent();
3532 if (parent instanceof ViewGroup) {
3533 ViewGroup p = (ViewGroup) parent;
3534 p.setOnHierarchyChangeListener(this);
3535 }
3536 }
3537
3538 @Override
3539 protected void onDetachedFromWindow() {
3540 super.onDetachedFromWindow();
3541 ViewParent parent = getParent();
3542 if (parent instanceof ViewGroup) {
3543 ViewGroup p = (ViewGroup) parent;
3544 p.setOnHierarchyChangeListener(null);
3545 }
3546
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003547 // Clean up the zoom controller
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003548 mZoomButtonsController.setVisible(false);
3549 }
Cary Clarkd6982c92009-05-29 11:02:22 -04003550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003551 // Implementation for OnHierarchyChangeListener
3552 public void onChildViewAdded(View parent, View child) {}
Cary Clarkd6982c92009-05-29 11:02:22 -04003553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003554 public void onChildViewRemoved(View p, View child) {
3555 if (child == this) {
Leon Scroggins3ccd3652009-06-26 17:22:50 -04003556 clearTextEntry();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003557 }
3558 }
3559
3560 /**
3561 * @deprecated WebView should not have implemented
3562 * ViewTreeObserver.OnGlobalFocusChangeListener. This method
3563 * does nothing now.
3564 */
3565 @Deprecated
3566 public void onGlobalFocusChanged(View oldFocus, View newFocus) {
3567 }
3568
Cary Clarkd6982c92009-05-29 11:02:22 -04003569 // To avoid drawing the cursor ring, and remove the TextView when our window
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003570 // loses focus.
3571 @Override
3572 public void onWindowFocusChanged(boolean hasWindowFocus) {
3573 if (hasWindowFocus) {
3574 if (hasFocus()) {
3575 // If our window regained focus, and we have focus, then begin
Leon Scrogginsfa03cde2009-06-15 15:48:46 -04003576 // drawing the cursor ring
Cary Clarkd6982c92009-05-29 11:02:22 -04003577 mDrawCursorRing = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003578 if (mNativeClass != 0) {
3579 nativeRecordButtons(true, false, true);
Leon Scroggins8cdad882009-06-30 08:47:04 -04003580 if (inEditingMode()) {
3581 mWebViewCore.sendMessage(EventHub.SET_ACTIVE, 1, 0);
3582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003583 }
3584 } else {
3585 // If our window gained focus, but we do not have it, do not
Cary Clarkd6982c92009-05-29 11:02:22 -04003586 // draw the cursor ring.
3587 mDrawCursorRing = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003588 // We do not call nativeRecordButtons here because we assume
3589 // that when we lost focus, or window focus, it got called with
3590 // false for the first parameter
3591 }
3592 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07003593 if (getSettings().getBuiltInZoomControls() && !mZoomButtonsController.isVisible()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003594 /*
3595 * The zoom controls come in their own window, so our window
Cary Clarkd6982c92009-05-29 11:02:22 -04003596 * loses focus. Our policy is to not draw the cursor ring if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003597 * our window is not focused, but this is an exception since
3598 * the user can still navigate the web page with the zoom
3599 * controls showing.
3600 */
Cary Clarkd6982c92009-05-29 11:02:22 -04003601 // If our window has lost focus, stop drawing the cursor ring
3602 mDrawCursorRing = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003603 }
3604 mGotKeyDown = false;
3605 mShiftIsPressed = false;
3606 if (mNativeClass != 0) {
3607 nativeRecordButtons(false, false, true);
3608 }
Leon Scrogginsfa03cde2009-06-15 15:48:46 -04003609 setFocusControllerInactive();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003610 }
3611 invalidate();
3612 super.onWindowFocusChanged(hasWindowFocus);
3613 }
3614
Leon Scroggins63dda1c2009-04-15 13:25:00 -04003615 /*
Leon Scrogginsfa03cde2009-06-15 15:48:46 -04003616 * Pass a message to WebCore Thread, telling the WebCore::Page's
3617 * FocusController to be "inactive" so that it will
3618 * not draw the blinking cursor. It gets set to "active" to draw the cursor
3619 * in WebViewCore.cpp, when the WebCore thread receives key events/clicks.
Leon Scroggins63dda1c2009-04-15 13:25:00 -04003620 */
Leon Scroggins01058282009-07-30 16:33:56 -04003621 /* package */ void setFocusControllerInactive() {
Leon Scrogginsfd06bc82009-06-08 13:22:02 -04003622 // Do not need to also check whether mWebViewCore is null, because
3623 // mNativeClass is only set if mWebViewCore is non null
3624 if (mNativeClass == 0) return;
Leon Scroggins8cdad882009-06-30 08:47:04 -04003625 mWebViewCore.sendMessage(EventHub.SET_ACTIVE, 0, 0);
Leon Scroggins63dda1c2009-04-15 13:25:00 -04003626 }
3627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003628 @Override
3629 protected void onFocusChanged(boolean focused, int direction,
3630 Rect previouslyFocusedRect) {
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04003631 if (DebugFlags.WEB_VIEW) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003632 Log.v(LOGTAG, "MT focusChanged " + focused + ", " + direction);
3633 }
3634 if (focused) {
3635 // When we regain focus, if we have window focus, resume drawing
Leon Scrogginsfa03cde2009-06-15 15:48:46 -04003636 // the cursor ring
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003637 if (hasWindowFocus()) {
Cary Clarkd6982c92009-05-29 11:02:22 -04003638 mDrawCursorRing = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003639 if (mNativeClass != 0) {
3640 nativeRecordButtons(true, false, true);
3641 }
3642 //} else {
3643 // The WebView has gained focus while we do not have
3644 // windowfocus. When our window lost focus, we should have
3645 // called nativeRecordButtons(false...)
3646 }
3647 } else {
3648 // When we lost focus, unless focus went to the TextView (which is
Cary Clarkd6982c92009-05-29 11:02:22 -04003649 // true if we are in editing mode), stop drawing the cursor ring.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003650 if (!inEditingMode()) {
Cary Clarkd6982c92009-05-29 11:02:22 -04003651 mDrawCursorRing = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003652 if (mNativeClass != 0) {
3653 nativeRecordButtons(false, false, true);
3654 }
Leon Scrogginsfa03cde2009-06-15 15:48:46 -04003655 setFocusControllerInactive();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003656 }
3657 mGotKeyDown = false;
3658 }
3659
3660 super.onFocusChanged(focused, direction, previouslyFocusedRect);
3661 }
3662
3663 @Override
3664 protected void onSizeChanged(int w, int h, int ow, int oh) {
3665 super.onSizeChanged(w, h, ow, oh);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003666 // Center zooming to the center of the screen.
Cary Clarka91874d2009-08-24 14:08:43 -04003667 if (mZoomScale == 0) { // unless we're already zooming
3668 mZoomCenterX = getViewWidth() * .5f;
3669 mZoomCenterY = getViewHeight() * .5f;
3670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003671
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003672 // update mMinZoomScale if the minimum zoom scale is not fixed
3673 if (!mMinZoomScaleFixed) {
Grace Klobaba672802009-09-25 15:54:08 -07003674 // when change from narrow screen to wide screen, the new viewWidth
3675 // can be wider than the old content width. We limit the minimum
3676 // scale to 1.0f. The proper minimum scale will be calculated when
3677 // the new picture shows up.
3678 mMinZoomScale = Math.min(1.0f, (float) getViewWidth()
Grace Klobae397a882009-08-06 12:04:14 -07003679 / (mDrawHistory ? mHistoryPicture.getWidth()
Grace Klobaba672802009-09-25 15:54:08 -07003680 : mZoomOverviewWidth));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003681 }
3682
3683 // we always force, in case our height changed, in which case we still
3684 // want to send the notification over to webkit
3685 setNewZoomScale(mActualScale, true);
3686 }
3687
3688 @Override
3689 protected void onScrollChanged(int l, int t, int oldl, int oldt) {
3690 super.onScrollChanged(l, t, oldl, oldt);
Patrick Scott0a5ce012009-07-02 08:56:10 -04003691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003692 sendOurVisibleRect();
3693 }
Cary Clarkd6982c92009-05-29 11:02:22 -04003694
3695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003696 @Override
3697 public boolean dispatchKeyEvent(KeyEvent event) {
3698 boolean dispatch = true;
3699
3700 if (!inEditingMode()) {
3701 if (event.getAction() == KeyEvent.ACTION_DOWN) {
3702 mGotKeyDown = true;
3703 } else {
3704 if (!mGotKeyDown) {
3705 /*
3706 * We got a key up for which we were not the recipient of
3707 * the original key down. Don't give it to the view.
3708 */
3709 dispatch = false;
3710 }
3711 mGotKeyDown = false;
3712 }
3713 }
3714
3715 if (dispatch) {
3716 return super.dispatchKeyEvent(event);
3717 } else {
3718 // We didn't dispatch, so let something else handle the key
3719 return false;
3720 }
3721 }
3722
3723 // Here are the snap align logic:
3724 // 1. If it starts nearly horizontally or vertically, snap align;
3725 // 2. If there is a dramitic direction change, let it go;
3726 // 3. If there is a same direction back and forth, lock it.
3727
3728 // adjustable parameters
3729 private int mMinLockSnapReverseDistance;
3730 private static final float MAX_SLOPE_FOR_DIAG = 1.5f;
3731 private static final int MIN_BREAK_SNAP_CROSS_DISTANCE = 80;
3732
3733 @Override
3734 public boolean onTouchEvent(MotionEvent ev) {
3735 if (mNativeClass == 0 || !isClickable() || !isLongClickable()) {
3736 return false;
3737 }
3738
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04003739 if (DebugFlags.WEB_VIEW) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003740 Log.v(LOGTAG, ev + " at " + ev.getEventTime() + " mTouchMode="
3741 + mTouchMode);
3742 }
3743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003744 int action = ev.getAction();
3745 float x = ev.getX();
3746 float y = ev.getY();
3747 long eventTime = ev.getEventTime();
3748
3749 // Due to the touch screen edge effect, a touch closer to the edge
3750 // always snapped to the edge. As getViewWidth() can be different from
3751 // getWidth() due to the scrollbar, adjusting the point to match
3752 // getViewWidth(). Same applied to the height.
3753 if (x > getViewWidth() - 1) {
3754 x = getViewWidth() - 1;
3755 }
Grace Kloba8eff73f2009-09-24 09:34:32 -07003756 if (y > getViewHeightWithTitle() - 1) {
3757 y = getViewHeightWithTitle() - 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003758 }
3759
3760 // pass the touch events from UI thread to WebCore thread
Grace Kloba04b28682009-09-14 14:38:37 -07003761 if (mForwardTouchEvents && (action != MotionEvent.ACTION_MOVE
3762 || eventTime - mLastSentTouchTime > TOUCH_SENT_INTERVAL)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003763 WebViewCore.TouchEventData ted = new WebViewCore.TouchEventData();
3764 ted.mAction = action;
Leon Scroggins0236e672009-09-02 21:12:08 -04003765 ted.mX = viewToContentX((int) x + mScrollX);
3766 ted.mY = viewToContentY((int) y + mScrollY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003767 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
3768 mLastSentTouchTime = eventTime;
3769 }
3770
Cary Clark25415e22009-10-12 13:41:28 -04003771 float fDeltaX = mLastTouchX - x;
3772 float fDeltaY = mLastTouchY - y;
3773 int deltaX = (int) fDeltaX;
3774 int deltaY = (int) fDeltaY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003775
3776 switch (action) {
3777 case MotionEvent.ACTION_DOWN: {
Grace Klobad66d84f2009-09-27 14:48:07 -07003778 mPreventDrag = PREVENT_DRAG_NO;
Grace Kloba04b28682009-09-14 14:38:37 -07003779 if (!mScroller.isFinished()) {
Cary Clark278ce052009-08-31 16:08:42 -04003780 // stop the current scroll animation, but if this is
3781 // the start of a fling, allow it to add to the current
3782 // fling's velocity
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003783 mScroller.abortAnimation();
3784 mTouchMode = TOUCH_DRAG_START_MODE;
3785 mPrivateHandler.removeMessages(RESUME_WEBCORE_UPDATE);
3786 } else if (mShiftIsPressed) {
3787 mSelectX = mScrollX + (int) x;
3788 mSelectY = mScrollY + (int) y;
3789 mTouchMode = TOUCH_SELECT_MODE;
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04003790 if (DebugFlags.WEB_VIEW) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003791 Log.v(LOGTAG, "select=" + mSelectX + "," + mSelectY);
3792 }
Leon Scroggins0236e672009-09-02 21:12:08 -04003793 nativeMoveSelection(viewToContentX(mSelectX),
3794 viewToContentY(mSelectY), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003795 mTouchSelection = mExtendSelection = true;
Grace Kloba8b97e4b2009-07-28 13:11:38 -07003796 } else if (mPrivateHandler.hasMessages(RELEASE_SINGLE_TAP)) {
3797 mPrivateHandler.removeMessages(RELEASE_SINGLE_TAP);
3798 if (deltaX * deltaX + deltaY * deltaY < mDoubleTapSlopSquare) {
3799 mTouchMode = TOUCH_DOUBLE_TAP_MODE;
3800 } else {
3801 // commit the short press action for the previous tap
3802 doShortPress();
3803 // continue, mTouchMode should be still TOUCH_INIT_MODE
3804 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003805 } else {
3806 mTouchMode = TOUCH_INIT_MODE;
Grace Klobaf58af622009-09-24 17:41:23 -07003807 mPreventDrag = mForwardTouchEvents ? PREVENT_DRAG_MAYBE_YES
3808 : PREVENT_DRAG_NO;
Cary Clark77d98f42009-07-31 09:40:38 -04003809 mWebViewCore.sendMessage(
3810 EventHub.UPDATE_FRAME_CACHE_IF_LOADING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003811 if (mLogEvent && eventTime - mLastTouchUpTime < 1000) {
3812 EventLog.writeEvent(EVENT_LOG_DOUBLE_TAP_DURATION,
3813 (eventTime - mLastTouchUpTime), eventTime);
3814 }
3815 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003816 // Trigger the link
Grace Kloba8b97e4b2009-07-28 13:11:38 -07003817 if (mTouchMode == TOUCH_INIT_MODE
3818 || mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003819 mPrivateHandler.sendMessageDelayed(mPrivateHandler
3820 .obtainMessage(SWITCH_TO_SHORTPRESS), TAP_TIMEOUT);
3821 }
3822 // Remember where the motion event started
3823 mLastTouchX = x;
3824 mLastTouchY = y;
3825 mLastTouchTime = eventTime;
3826 mVelocityTracker = VelocityTracker.obtain();
3827 mSnapScrollMode = SNAP_NONE;
3828 break;
3829 }
3830 case MotionEvent.ACTION_MOVE: {
Grace Kloba04b28682009-09-14 14:38:37 -07003831 if (mTouchMode == TOUCH_DONE_MODE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003832 // no dragging during scroll zoom animation
3833 break;
3834 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003835 mVelocityTracker.addMovement(ev);
3836
3837 if (mTouchMode != TOUCH_DRAG_MODE) {
3838 if (mTouchMode == TOUCH_SELECT_MODE) {
3839 mSelectX = mScrollX + (int) x;
3840 mSelectY = mScrollY + (int) y;
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04003841 if (DebugFlags.WEB_VIEW) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003842 Log.v(LOGTAG, "xtend=" + mSelectX + "," + mSelectY);
3843 }
Leon Scroggins0236e672009-09-02 21:12:08 -04003844 nativeMoveSelection(viewToContentX(mSelectX),
3845 viewToContentY(mSelectY), true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003846 invalidate();
3847 break;
3848 }
Grace Klobaf58af622009-09-24 17:41:23 -07003849 if ((deltaX * deltaX + deltaY * deltaY) < mTouchSlopSquare) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003850 break;
3851 }
Grace Klobaf58af622009-09-24 17:41:23 -07003852 if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) {
3853 // track mLastTouchTime as we may need to do fling at
3854 // ACTION_UP
3855 mLastTouchTime = eventTime;
3856 break;
3857 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003858 if (mTouchMode == TOUCH_SHORTPRESS_MODE
3859 || mTouchMode == TOUCH_SHORTPRESS_START_MODE) {
3860 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
Grace Kloba8b97e4b2009-07-28 13:11:38 -07003861 } else if (mTouchMode == TOUCH_INIT_MODE
3862 || mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003863 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
3864 }
3865
3866 // if it starts nearly horizontal or vertical, enforce it
3867 int ax = Math.abs(deltaX);
3868 int ay = Math.abs(deltaY);
3869 if (ax > MAX_SLOPE_FOR_DIAG * ay) {
3870 mSnapScrollMode = SNAP_X;
3871 mSnapPositive = deltaX > 0;
3872 } else if (ay > MAX_SLOPE_FOR_DIAG * ax) {
3873 mSnapScrollMode = SNAP_Y;
3874 mSnapPositive = deltaY > 0;
3875 }
3876
3877 mTouchMode = TOUCH_DRAG_MODE;
3878 WebViewCore.pauseUpdate(mWebViewCore);
Leon Scroggins72543e12009-07-23 15:29:45 -04003879 if (!mDragFromTextInput) {
3880 nativeHideCursor();
3881 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003882 WebSettings settings = getSettings();
Grace Kloba455e3af2009-08-13 11:01:21 -07003883 if (settings.supportZoom()
The Android Open Source Project10592532009-03-18 17:39:46 -07003884 && settings.getBuiltInZoomControls()
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003885 && !mZoomButtonsController.isVisible()
Grace Kloba04b28682009-09-14 14:38:37 -07003886 && mMinZoomScale < mMaxZoomScale) {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003887 mZoomButtonsController.setVisible(true);
Grace Klobaf8d8b462009-09-20 15:57:49 -07003888 int count = settings.getDoubleTapToastCount();
3889 if (mInZoomOverview && count > 0) {
Grace Kloba24a3ff92009-09-22 10:42:22 -07003890 settings.setDoubleTapToastCount(--count);
Grace Klobaf8d8b462009-09-20 15:57:49 -07003891 Toast.makeText(mContext,
3892 com.android.internal.R.string.double_tap_toast,
Grace Kloba24a3ff92009-09-22 10:42:22 -07003893 Toast.LENGTH_LONG).show();
Grace Klobaf8d8b462009-09-20 15:57:49 -07003894 }
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003895 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003896 }
3897
3898 // do pan
3899 int newScrollX = pinLocX(mScrollX + deltaX);
Cary Clark25415e22009-10-12 13:41:28 -04003900 int newDeltaX = newScrollX - mScrollX;
3901 if (deltaX != newDeltaX) {
3902 deltaX = newDeltaX;
3903 fDeltaX = (float) newDeltaX;
3904 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003905 int newScrollY = pinLocY(mScrollY + deltaY);
Cary Clark25415e22009-10-12 13:41:28 -04003906 int newDeltaY = newScrollY - mScrollY;
3907 if (deltaY != newDeltaY) {
3908 deltaY = newDeltaY;
3909 fDeltaY = (float) newDeltaY;
3910 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003911 boolean done = false;
Cary Clark25415e22009-10-12 13:41:28 -04003912 boolean keepScrollBarsVisible = false;
3913 if (Math.abs(fDeltaX) < 1.0f && Math.abs(fDeltaY) < 1.0f) {
3914 keepScrollBarsVisible = done = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003915 } else {
3916 if (mSnapScrollMode == SNAP_X || mSnapScrollMode == SNAP_Y) {
3917 int ax = Math.abs(deltaX);
3918 int ay = Math.abs(deltaY);
3919 if (mSnapScrollMode == SNAP_X) {
3920 // radical change means getting out of snap mode
3921 if (ay > MAX_SLOPE_FOR_DIAG * ax
3922 && ay > MIN_BREAK_SNAP_CROSS_DISTANCE) {
3923 mSnapScrollMode = SNAP_NONE;
3924 }
3925 // reverse direction means lock in the snap mode
Cary Clarkac492e12009-10-14 14:53:37 -04003926 if (ax > MAX_SLOPE_FOR_DIAG * ay &&
3927 (mSnapPositive
3928 ? deltaX < -mMinLockSnapReverseDistance
3929 : deltaX > mMinLockSnapReverseDistance)) {
3930 mSnapScrollMode |= SNAP_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003931 }
3932 } else {
3933 // radical change means getting out of snap mode
Cary Clarkac492e12009-10-14 14:53:37 -04003934 if (ax > MAX_SLOPE_FOR_DIAG * ay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003935 && ax > MIN_BREAK_SNAP_CROSS_DISTANCE) {
3936 mSnapScrollMode = SNAP_NONE;
3937 }
3938 // reverse direction means lock in the snap mode
Cary Clarkac492e12009-10-14 14:53:37 -04003939 if (ay > MAX_SLOPE_FOR_DIAG * ax &&
3940 (mSnapPositive
3941 ? deltaY < -mMinLockSnapReverseDistance
3942 : deltaY > mMinLockSnapReverseDistance)) {
3943 mSnapScrollMode |= SNAP_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003944 }
3945 }
3946 }
Cary Clarkac492e12009-10-14 14:53:37 -04003947 if (mSnapScrollMode != SNAP_NONE) {
3948 if ((mSnapScrollMode & SNAP_X) == SNAP_X) {
3949 deltaY = 0;
Grace Kloba5b2c0562009-09-30 10:17:13 -07003950 } else {
Cary Clarkac492e12009-10-14 14:53:37 -04003951 deltaX = 0;
Grace Kloba5b2c0562009-09-30 10:17:13 -07003952 }
Cary Clarkac492e12009-10-14 14:53:37 -04003953 }
3954 if ((deltaX | deltaY) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003955 scrollBy(deltaX, deltaY);
Cary Clarkac492e12009-10-14 14:53:37 -04003956 if (deltaX != 0) {
3957 mLastTouchX = x;
3958 }
3959 if (deltaY != 0) {
3960 mLastTouchY = y;
3961 }
3962 mHeldMotionless = MOTIONLESS_FALSE;
3963 } else {
3964 // keep the scrollbar on the screen even there is no
3965 // scroll
3966 keepScrollBarsVisible = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003967 }
3968 mLastTouchTime = eventTime;
3969 mUserScroll = true;
3970 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003971
Grace Kloba455e3af2009-08-13 11:01:21 -07003972 if (!getSettings().getBuiltInZoomControls()) {
The Android Open Source Project10592532009-03-18 17:39:46 -07003973 boolean showPlusMinus = mMinZoomScale < mMaxZoomScale;
Grace Kloba04b28682009-09-14 14:38:37 -07003974 if (mZoomControls != null && showPlusMinus) {
The Android Open Source Project10592532009-03-18 17:39:46 -07003975 if (mZoomControls.getVisibility() == View.VISIBLE) {
3976 mPrivateHandler.removeCallbacks(mZoomControlRunnable);
3977 } else {
Grace Kloba04b28682009-09-14 14:38:37 -07003978 mZoomControls.show(showPlusMinus, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07003979 }
3980 mPrivateHandler.postDelayed(mZoomControlRunnable,
3981 ZOOM_CONTROLS_TIMEOUT);
3982 }
3983 }
3984
Cary Clark25415e22009-10-12 13:41:28 -04003985 if (keepScrollBarsVisible) {
3986 if (mHeldMotionless != MOTIONLESS_TRUE) {
3987 mHeldMotionless = MOTIONLESS_TRUE;
3988 invalidate();
3989 }
Grace Kloba5b2c0562009-09-30 10:17:13 -07003990 // keep the scrollbar on the screen even there is no scroll
3991 awakenScrollBars(ViewConfiguration.getScrollDefaultDelay(),
3992 false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003993 // return false to indicate that we can't pan out of the
3994 // view space
Cary Clark25415e22009-10-12 13:41:28 -04003995 return !done;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003996 }
3997 break;
3998 }
3999 case MotionEvent.ACTION_UP: {
4000 mLastTouchUpTime = eventTime;
4001 switch (mTouchMode) {
Grace Kloba8b97e4b2009-07-28 13:11:38 -07004002 case TOUCH_DOUBLE_TAP_MODE: // double tap
4003 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
Grace Klobad3c6d542009-07-31 14:24:19 -07004004 mTouchMode = TOUCH_DONE_MODE;
Grace Kloba8b97e4b2009-07-28 13:11:38 -07004005 doDoubleTap();
4006 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004007 case TOUCH_SELECT_MODE:
4008 commitCopy();
4009 mTouchSelection = false;
4010 break;
Grace Klobaf58af622009-09-24 17:41:23 -07004011 case TOUCH_INIT_MODE: // tap
Grace Klobad66d84f2009-09-27 14:48:07 -07004012 case TOUCH_SHORTPRESS_START_MODE:
4013 case TOUCH_SHORTPRESS_MODE:
Grace Klobaf58af622009-09-24 17:41:23 -07004014 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
Grace Klobad66d84f2009-09-27 14:48:07 -07004015 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
Grace Klobaf58af622009-09-24 17:41:23 -07004016 if ((deltaX * deltaX + deltaY * deltaY) > mTouchSlopSquare) {
4017 Log.w(LOGTAG, "Miss a drag as we are waiting for" +
4018 " WebCore's response for touch down.");
4019 if (computeHorizontalScrollExtent() < computeHorizontalScrollRange()
4020 || computeVerticalScrollExtent() < computeVerticalScrollRange()) {
4021 // we will not rewrite drag code here, but we
4022 // will try fling if it applies.
4023 WebViewCore.pauseUpdate(mWebViewCore);
4024 // fall through to TOUCH_DRAG_MODE
4025 } else {
4026 break;
4027 }
4028 } else {
4029 if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) {
4030 // if mPreventDrag is not confirmed, treat it as
4031 // no so that it won't block tap or double tap.
4032 mPreventDrag = PREVENT_DRAG_NO;
4033 }
4034 if (mPreventDrag == PREVENT_DRAG_NO) {
Grace Klobad66d84f2009-09-27 14:48:07 -07004035 if (mTouchMode == TOUCH_INIT_MODE) {
4036 mPrivateHandler.sendMessageDelayed(
4037 mPrivateHandler.obtainMessage(
4038 RELEASE_SINGLE_TAP),
4039 ViewConfiguration.getDoubleTapTimeout());
4040 } else {
4041 mTouchMode = TOUCH_DONE_MODE;
4042 doShortPress();
4043 }
Grace Klobaf58af622009-09-24 17:41:23 -07004044 }
4045 break;
4046 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004047 case TOUCH_DRAG_MODE:
Cary Clark25415e22009-10-12 13:41:28 -04004048 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
4049 mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
4050 mHeldMotionless = MOTIONLESS_TRUE;
Mike Reeddf4cf292009-09-15 14:31:54 -04004051 // redraw in high-quality, as we're done dragging
4052 invalidate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004053 // if the user waits a while w/o moving before the
4054 // up, we don't want to do a fling
4055 if (eventTime - mLastTouchTime <= MIN_FLING_TIME) {
4056 mVelocityTracker.addMovement(ev);
4057 doFling();
4058 break;
4059 }
Cary Clark278ce052009-08-31 16:08:42 -04004060 mLastVelocity = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004061 WebViewCore.resumeUpdate(mWebViewCore);
4062 break;
4063 case TOUCH_DRAG_START_MODE:
4064 case TOUCH_DONE_MODE:
4065 // do nothing
4066 break;
4067 }
4068 // we also use mVelocityTracker == null to tell us that we are
4069 // not "moving around", so we can take the slower/prettier
4070 // mode in the drawing code
4071 if (mVelocityTracker != null) {
4072 mVelocityTracker.recycle();
4073 mVelocityTracker = null;
4074 }
4075 break;
4076 }
4077 case MotionEvent.ACTION_CANCEL: {
4078 // we also use mVelocityTracker == null to tell us that we are
4079 // not "moving around", so we can take the slower/prettier
4080 // mode in the drawing code
4081 if (mVelocityTracker != null) {
4082 mVelocityTracker.recycle();
4083 mVelocityTracker = null;
4084 }
Grace Kloba04b28682009-09-14 14:38:37 -07004085 if (mTouchMode == TOUCH_DRAG_MODE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004086 WebViewCore.resumeUpdate(mWebViewCore);
4087 }
4088 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
4089 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
Cary Clark25415e22009-10-12 13:41:28 -04004090 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
4091 mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
4092 mHeldMotionless = MOTIONLESS_TRUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004093 mTouchMode = TOUCH_DONE_MODE;
Cary Clarke872f3a2009-06-11 09:51:11 -04004094 nativeHideCursor();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004095 break;
4096 }
4097 }
4098 return true;
4099 }
Cary Clarkd6982c92009-05-29 11:02:22 -04004100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004101 private long mTrackballFirstTime = 0;
4102 private long mTrackballLastTime = 0;
4103 private float mTrackballRemainsX = 0.0f;
4104 private float mTrackballRemainsY = 0.0f;
4105 private int mTrackballXMove = 0;
4106 private int mTrackballYMove = 0;
4107 private boolean mExtendSelection = false;
4108 private boolean mTouchSelection = false;
4109 private static final int TRACKBALL_KEY_TIMEOUT = 1000;
4110 private static final int TRACKBALL_TIMEOUT = 200;
4111 private static final int TRACKBALL_WAIT = 100;
4112 private static final int TRACKBALL_SCALE = 400;
4113 private static final int TRACKBALL_SCROLL_COUNT = 5;
4114 private static final int TRACKBALL_MOVE_COUNT = 10;
4115 private static final int TRACKBALL_MULTIPLIER = 3;
4116 private static final int SELECT_CURSOR_OFFSET = 16;
4117 private int mSelectX = 0;
4118 private int mSelectY = 0;
Cary Clark5da9aeb2009-10-06 17:40:53 -04004119 private boolean mFocusSizeChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004120 private boolean mShiftIsPressed = false;
4121 private boolean mTrackballDown = false;
4122 private long mTrackballUpTime = 0;
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04004123 private long mLastCursorTime = 0;
4124 private Rect mLastCursorBounds;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004125
4126 // Set by default; BrowserActivity clears to interpret trackball data
Cary Clarkd6982c92009-05-29 11:02:22 -04004127 // directly for movement. Currently, the framework only passes
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004128 // arrow key events, not trackball events, from one child to the next
4129 private boolean mMapTrackballToArrowKeys = true;
Cary Clarkd6982c92009-05-29 11:02:22 -04004130
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004131 public void setMapTrackballToArrowKeys(boolean setMap) {
4132 mMapTrackballToArrowKeys = setMap;
4133 }
4134
4135 void resetTrackballTime() {
4136 mTrackballLastTime = 0;
4137 }
4138
4139 @Override
4140 public boolean onTrackballEvent(MotionEvent ev) {
4141 long time = ev.getEventTime();
4142 if ((ev.getMetaState() & KeyEvent.META_ALT_ON) != 0) {
4143 if (ev.getY() > 0) pageDown(true);
4144 if (ev.getY() < 0) pageUp(true);
4145 return true;
4146 }
4147 if (ev.getAction() == MotionEvent.ACTION_DOWN) {
Cary Clarkbadd8392009-10-15 13:32:08 -04004148 if (mShiftIsPressed) {
4149 return true; // discard press if copy in progress
4150 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004151 mTrackballDown = true;
Leon Scroggins3ccd3652009-06-26 17:22:50 -04004152 if (mNativeClass == 0) {
4153 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004154 }
Leon Scroggins3ccd3652009-06-26 17:22:50 -04004155 nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true);
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04004156 if (time - mLastCursorTime <= TRACKBALL_TIMEOUT
4157 && !mLastCursorBounds.equals(nativeGetCursorRingBounds())) {
4158 nativeSelectBestAt(mLastCursorBounds);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004159 }
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04004160 if (DebugFlags.WEB_VIEW) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004161 Log.v(LOGTAG, "onTrackballEvent down ev=" + ev
Cary Clarkd6982c92009-05-29 11:02:22 -04004162 + " time=" + time
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04004163 + " mLastCursorTime=" + mLastCursorTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004164 }
4165 if (isInTouchMode()) requestFocusFromTouch();
4166 return false; // let common code in onKeyDown at it
Cary Clarkd6982c92009-05-29 11:02:22 -04004167 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004168 if (ev.getAction() == MotionEvent.ACTION_UP) {
Leon Scrogginse3225672009-06-03 15:53:13 -04004169 // LONG_PRESS_CENTER is set in common onKeyDown
4170 mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004171 mTrackballDown = false;
4172 mTrackballUpTime = time;
4173 if (mShiftIsPressed) {
4174 if (mExtendSelection) {
4175 commitCopy();
4176 } else {
4177 mExtendSelection = true;
4178 }
Cary Clarkbadd8392009-10-15 13:32:08 -04004179 return true; // discard press if copy in progress
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004180 }
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04004181 if (DebugFlags.WEB_VIEW) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004182 Log.v(LOGTAG, "onTrackballEvent up ev=" + ev
Cary Clarkd6982c92009-05-29 11:02:22 -04004183 + " time=" + time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004184 );
4185 }
4186 return false; // let common code in onKeyUp at it
4187 }
4188 if (mMapTrackballToArrowKeys && mShiftIsPressed == false) {
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04004189 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent gmail quit");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004190 return false;
4191 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004192 if (mTrackballDown) {
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04004193 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent down quit");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004194 return true; // discard move if trackball is down
4195 }
4196 if (time - mTrackballUpTime < TRACKBALL_TIMEOUT) {
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04004197 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent up timeout quit");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004198 return true;
4199 }
4200 // TODO: alternatively we can do panning as touch does
4201 switchOutDrawHistory();
4202 if (time - mTrackballLastTime > TRACKBALL_TIMEOUT) {
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04004203 if (DebugFlags.WEB_VIEW) {
Cary Clarkd6982c92009-05-29 11:02:22 -04004204 Log.v(LOGTAG, "onTrackballEvent time="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004205 + time + " last=" + mTrackballLastTime);
4206 }
4207 mTrackballFirstTime = time;
4208 mTrackballXMove = mTrackballYMove = 0;
4209 }
4210 mTrackballLastTime = time;
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04004211 if (DebugFlags.WEB_VIEW) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004212 Log.v(LOGTAG, "onTrackballEvent ev=" + ev + " time=" + time);
4213 }
4214 mTrackballRemainsX += ev.getX();
4215 mTrackballRemainsY += ev.getY();
4216 doTrackball(time);
4217 return true;
4218 }
Cary Clarkd6982c92009-05-29 11:02:22 -04004219
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004220 void moveSelection(float xRate, float yRate) {
4221 if (mNativeClass == 0)
4222 return;
4223 int width = getViewWidth();
4224 int height = getViewHeight();
Cary Clarkc05af372009-10-16 10:52:27 -04004225 mSelectX += xRate;
4226 mSelectY += yRate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004227 int maxX = width + mScrollX;
4228 int maxY = height + mScrollY;
4229 mSelectX = Math.min(maxX, Math.max(mScrollX - SELECT_CURSOR_OFFSET
4230 , mSelectX));
4231 mSelectY = Math.min(maxY, Math.max(mScrollY - SELECT_CURSOR_OFFSET
4232 , mSelectY));
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04004233 if (DebugFlags.WEB_VIEW) {
Cary Clarkd6982c92009-05-29 11:02:22 -04004234 Log.v(LOGTAG, "moveSelection"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004235 + " mSelectX=" + mSelectX
4236 + " mSelectY=" + mSelectY
4237 + " mScrollX=" + mScrollX
4238 + " mScrollY=" + mScrollY
4239 + " xRate=" + xRate
4240 + " yRate=" + yRate
4241 );
4242 }
Leon Scroggins0236e672009-09-02 21:12:08 -04004243 nativeMoveSelection(viewToContentX(mSelectX),
4244 viewToContentY(mSelectY), mExtendSelection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004245 int scrollX = mSelectX < mScrollX ? -SELECT_CURSOR_OFFSET
Cary Clarkd6982c92009-05-29 11:02:22 -04004246 : mSelectX > maxX - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004247 : 0;
4248 int scrollY = mSelectY < mScrollY ? -SELECT_CURSOR_OFFSET
Cary Clarkd6982c92009-05-29 11:02:22 -04004249 : mSelectY > maxY - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004250 : 0;
4251 pinScrollBy(scrollX, scrollY, true, 0);
4252 Rect select = new Rect(mSelectX, mSelectY, mSelectX + 1, mSelectY + 1);
4253 requestRectangleOnScreen(select);
4254 invalidate();
4255 }
4256
4257 private int scaleTrackballX(float xRate, int width) {
4258 int xMove = (int) (xRate / TRACKBALL_SCALE * width);
4259 int nextXMove = xMove;
4260 if (xMove > 0) {
4261 if (xMove > mTrackballXMove) {
4262 xMove -= mTrackballXMove;
4263 }
4264 } else if (xMove < mTrackballXMove) {
4265 xMove -= mTrackballXMove;
4266 }
4267 mTrackballXMove = nextXMove;
4268 return xMove;
4269 }
4270
4271 private int scaleTrackballY(float yRate, int height) {
4272 int yMove = (int) (yRate / TRACKBALL_SCALE * height);
4273 int nextYMove = yMove;
4274 if (yMove > 0) {
4275 if (yMove > mTrackballYMove) {
4276 yMove -= mTrackballYMove;
4277 }
4278 } else if (yMove < mTrackballYMove) {
4279 yMove -= mTrackballYMove;
4280 }
4281 mTrackballYMove = nextYMove;
4282 return yMove;
4283 }
4284
4285 private int keyCodeToSoundsEffect(int keyCode) {
4286 switch(keyCode) {
4287 case KeyEvent.KEYCODE_DPAD_UP:
4288 return SoundEffectConstants.NAVIGATION_UP;
4289 case KeyEvent.KEYCODE_DPAD_RIGHT:
4290 return SoundEffectConstants.NAVIGATION_RIGHT;
4291 case KeyEvent.KEYCODE_DPAD_DOWN:
4292 return SoundEffectConstants.NAVIGATION_DOWN;
4293 case KeyEvent.KEYCODE_DPAD_LEFT:
4294 return SoundEffectConstants.NAVIGATION_LEFT;
4295 }
4296 throw new IllegalArgumentException("keyCode must be one of " +
4297 "{KEYCODE_DPAD_UP, KEYCODE_DPAD_RIGHT, KEYCODE_DPAD_DOWN, " +
4298 "KEYCODE_DPAD_LEFT}.");
4299 }
4300
4301 private void doTrackball(long time) {
4302 int elapsed = (int) (mTrackballLastTime - mTrackballFirstTime);
4303 if (elapsed == 0) {
4304 elapsed = TRACKBALL_TIMEOUT;
4305 }
Cary Clarkd6982c92009-05-29 11:02:22 -04004306 float xRate = mTrackballRemainsX * 1000 / elapsed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004307 float yRate = mTrackballRemainsY * 1000 / elapsed;
Cary Clarkc05af372009-10-16 10:52:27 -04004308 int viewWidth = getViewWidth();
4309 int viewHeight = getViewHeight();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004310 if (mShiftIsPressed) {
Cary Clarkc05af372009-10-16 10:52:27 -04004311 moveSelection(scaleTrackballX(xRate, viewWidth),
4312 scaleTrackballY(yRate, viewHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004313 mTrackballRemainsX = mTrackballRemainsY = 0;
4314 return;
4315 }
4316 float ax = Math.abs(xRate);
4317 float ay = Math.abs(yRate);
4318 float maxA = Math.max(ax, ay);
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04004319 if (DebugFlags.WEB_VIEW) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004320 Log.v(LOGTAG, "doTrackball elapsed=" + elapsed
4321 + " xRate=" + xRate
4322 + " yRate=" + yRate
4323 + " mTrackballRemainsX=" + mTrackballRemainsX
4324 + " mTrackballRemainsY=" + mTrackballRemainsY);
4325 }
Cary Clarkc05af372009-10-16 10:52:27 -04004326 int width = mContentWidth - viewWidth;
4327 int height = mContentHeight - viewHeight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004328 if (width < 0) width = 0;
4329 if (height < 0) height = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004330 ax = Math.abs(mTrackballRemainsX * TRACKBALL_MULTIPLIER);
4331 ay = Math.abs(mTrackballRemainsY * TRACKBALL_MULTIPLIER);
4332 maxA = Math.max(ax, ay);
4333 int count = Math.max(0, (int) maxA);
4334 int oldScrollX = mScrollX;
4335 int oldScrollY = mScrollY;
4336 if (count > 0) {
Cary Clarkd6982c92009-05-29 11:02:22 -04004337 int selectKeyCode = ax < ay ? mTrackballRemainsY < 0 ?
4338 KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN :
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004339 mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT :
4340 KeyEvent.KEYCODE_DPAD_RIGHT;
4341 count = Math.min(count, TRACKBALL_MOVE_COUNT);
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04004342 if (DebugFlags.WEB_VIEW) {
Cary Clarkd6982c92009-05-29 11:02:22 -04004343 Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004344 + " count=" + count
4345 + " mTrackballRemainsX=" + mTrackballRemainsX
4346 + " mTrackballRemainsY=" + mTrackballRemainsY);
4347 }
Cary Clark215b72c2009-06-26 14:38:43 -04004348 if (navHandledKey(selectKeyCode, count, false, time, false)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004349 playSoundEffect(keyCodeToSoundsEffect(selectKeyCode));
4350 }
4351 mTrackballRemainsX = mTrackballRemainsY = 0;
4352 }
4353 if (count >= TRACKBALL_SCROLL_COUNT) {
4354 int xMove = scaleTrackballX(xRate, width);
4355 int yMove = scaleTrackballY(yRate, height);
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04004356 if (DebugFlags.WEB_VIEW) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004357 Log.v(LOGTAG, "doTrackball pinScrollBy"
4358 + " count=" + count
4359 + " xMove=" + xMove + " yMove=" + yMove
Cary Clarkd6982c92009-05-29 11:02:22 -04004360 + " mScrollX-oldScrollX=" + (mScrollX-oldScrollX)
4361 + " mScrollY-oldScrollY=" + (mScrollY-oldScrollY)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004362 );
4363 }
4364 if (Math.abs(mScrollX - oldScrollX) > Math.abs(xMove)) {
4365 xMove = 0;
4366 }
4367 if (Math.abs(mScrollY - oldScrollY) > Math.abs(yMove)) {
4368 yMove = 0;
4369 }
4370 if (xMove != 0 || yMove != 0) {
4371 pinScrollBy(xMove, yMove, true, 0);
4372 }
4373 mUserScroll = true;
Cary Clarkd6982c92009-05-29 11:02:22 -04004374 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004375 }
4376
Mike Reede8853fc2009-09-04 14:01:48 -04004377 private int computeMaxScrollY() {
Grace Klobae621d6f2009-09-11 13:20:39 -07004378 int maxContentH = computeVerticalScrollRange() + getTitleHeight();
Cary Clark298d32e2009-09-14 14:53:24 -04004379 return Math.max(maxContentH - getHeight(), getTitleHeight());
Mike Reede8853fc2009-09-04 14:01:48 -04004380 }
4381
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004382 public void flingScroll(int vx, int vy) {
4383 int maxX = Math.max(computeHorizontalScrollRange() - getViewWidth(), 0);
Mike Reede8853fc2009-09-04 14:01:48 -04004384 int maxY = computeMaxScrollY();
Cary Clarkd6982c92009-05-29 11:02:22 -04004385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004386 mScroller.fling(mScrollX, mScrollY, vx, vy, 0, maxX, 0, maxY);
4387 invalidate();
4388 }
Cary Clarkd6982c92009-05-29 11:02:22 -04004389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004390 private void doFling() {
4391 if (mVelocityTracker == null) {
4392 return;
4393 }
4394 int maxX = Math.max(computeHorizontalScrollRange() - getViewWidth(), 0);
Mike Reede8853fc2009-09-04 14:01:48 -04004395 int maxY = computeMaxScrollY();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004396
Romain Guy4296fc42009-07-06 11:48:52 -07004397 mVelocityTracker.computeCurrentVelocity(1000, mMaximumFling);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004398 int vx = (int) mVelocityTracker.getXVelocity();
4399 int vy = (int) mVelocityTracker.getYVelocity();
4400
4401 if (mSnapScrollMode != SNAP_NONE) {
Cary Clarkac492e12009-10-14 14:53:37 -04004402 if ((mSnapScrollMode & SNAP_X) == SNAP_X) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004403 vy = 0;
4404 } else {
4405 vx = 0;
4406 }
4407 }
Cary Clarkd6982c92009-05-29 11:02:22 -04004408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004409 if (true /* EMG release: make our fling more like Maps' */) {
4410 // maps cuts their velocity in half
4411 vx = vx * 3 / 4;
4412 vy = vy * 3 / 4;
4413 }
Cary Clarkaa7caa62009-09-08 14:15:07 -04004414 if ((maxX == 0 && vy == 0) || (maxY == 0 && vx == 0)) {
4415 WebViewCore.resumeUpdate(mWebViewCore);
4416 return;
4417 }
Cary Clark278ce052009-08-31 16:08:42 -04004418 float currentVelocity = mScroller.getCurrVelocity();
4419 if (mLastVelocity > 0 && currentVelocity > 0) {
4420 float deltaR = (float) (Math.abs(Math.atan2(mLastVelY, mLastVelX)
4421 - Math.atan2(vy, vx)));
4422 final float circle = (float) (Math.PI) * 2.0f;
4423 if (deltaR > circle * 0.9f || deltaR < circle * 0.1f) {
4424 vx += currentVelocity * mLastVelX / mLastVelocity;
4425 vy += currentVelocity * mLastVelY / mLastVelocity;
4426 if (DebugFlags.WEB_VIEW) {
4427 Log.v(LOGTAG, "doFling vx= " + vx + " vy=" + vy);
4428 }
4429 } else if (DebugFlags.WEB_VIEW) {
4430 Log.v(LOGTAG, "doFling missed " + deltaR / circle);
4431 }
4432 } else if (DebugFlags.WEB_VIEW) {
4433 Log.v(LOGTAG, "doFling start last=" + mLastVelocity
Cary Clarkaa7caa62009-09-08 14:15:07 -04004434 + " current=" + currentVelocity
4435 + " vx=" + vx + " vy=" + vy
4436 + " maxX=" + maxX + " maxY=" + maxY
4437 + " mScrollX=" + mScrollX + " mScrollY=" + mScrollY);
Cary Clark278ce052009-08-31 16:08:42 -04004438 }
4439 mLastVelX = vx;
4440 mLastVelY = vy;
4441 mLastVelocity = (float) Math.hypot(vx, vy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004442
4443 mScroller.fling(mScrollX, mScrollY, -vx, -vy, 0, maxX, 0, maxY);
4444 // TODO: duration is calculated based on velocity, if the range is
4445 // small, the animation will stop before duration is up. We may
4446 // want to calculate how long the animation is going to run to precisely
4447 // resume the webcore update.
4448 final int time = mScroller.getDuration();
4449 mPrivateHandler.sendEmptyMessageDelayed(RESUME_WEBCORE_UPDATE, time);
Mike Cleronf116bf82009-09-27 19:14:12 -07004450 awakenScrollBars(time);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004451 invalidate();
4452 }
4453
4454 private boolean zoomWithPreview(float scale) {
4455 float oldScale = mActualScale;
Grace Kloba675c7d22009-07-23 09:21:21 -07004456 mInitialScrollX = mScrollX;
4457 mInitialScrollY = mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004458
Grace Kloba25737912009-06-19 12:42:47 -07004459 // snap to DEFAULT_SCALE if it is close
Grace Kloba0d8b77c2009-06-25 11:20:51 -07004460 if (scale > (mDefaultScale - 0.05) && scale < (mDefaultScale + 0.05)) {
4461 scale = mDefaultScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004462 }
4463
4464 setNewZoomScale(scale, false);
4465
4466 if (oldScale != mActualScale) {
4467 // use mZoomPickerScale to see zoom preview first
4468 mZoomStart = SystemClock.uptimeMillis();
4469 mInvInitialZoomScale = 1.0f / oldScale;
4470 mInvFinalZoomScale = 1.0f / mActualScale;
4471 mZoomScale = mActualScale;
Grace Kloba8b97e4b2009-07-28 13:11:38 -07004472 if (!mInZoomOverview) {
4473 mLastScale = scale;
4474 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004475 invalidate();
4476 return true;
4477 } else {
4478 return false;
4479 }
4480 }
4481
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07004482 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004483 * Returns a view containing zoom controls i.e. +/- buttons. The caller is
4484 * in charge of installing this view to the view hierarchy. This view will
4485 * become visible when the user starts scrolling via touch and fade away if
4486 * the user does not interact with it.
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07004487 * <p/>
The Android Open Source Project10592532009-03-18 17:39:46 -07004488 * API version 3 introduces a built-in zoom mechanism that is shown
4489 * automatically by the MapView. This is the preferred approach for
4490 * showing the zoom UI.
4491 *
4492 * @deprecated The built-in zoom mechanism is preferred, see
4493 * {@link WebSettings#setBuiltInZoomControls(boolean)}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004494 */
The Android Open Source Project10592532009-03-18 17:39:46 -07004495 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004496 public View getZoomControls() {
The Android Open Source Project10592532009-03-18 17:39:46 -07004497 if (!getSettings().supportZoom()) {
4498 Log.w(LOGTAG, "This WebView doesn't support zoom.");
4499 return null;
4500 }
4501 if (mZoomControls == null) {
4502 mZoomControls = createZoomControls();
Cary Clarkd6982c92009-05-29 11:02:22 -04004503
The Android Open Source Project10592532009-03-18 17:39:46 -07004504 /*
4505 * need to be set to VISIBLE first so that getMeasuredHeight() in
4506 * {@link #onSizeChanged()} can return the measured value for proper
4507 * layout.
4508 */
4509 mZoomControls.setVisibility(View.VISIBLE);
4510 mZoomControlRunnable = new Runnable() {
4511 public void run() {
Cary Clarkd6982c92009-05-29 11:02:22 -04004512
The Android Open Source Project10592532009-03-18 17:39:46 -07004513 /* Don't dismiss the controls if the user has
4514 * focus on them. Wait and check again later.
4515 */
4516 if (!mZoomControls.hasFocus()) {
4517 mZoomControls.hide();
4518 } else {
4519 mPrivateHandler.removeCallbacks(mZoomControlRunnable);
4520 mPrivateHandler.postDelayed(mZoomControlRunnable,
4521 ZOOM_CONTROLS_TIMEOUT);
4522 }
4523 }
4524 };
4525 }
4526 return mZoomControls;
4527 }
4528
4529 private ExtendedZoomControls createZoomControls() {
4530 ExtendedZoomControls zoomControls = new ExtendedZoomControls(mContext
4531 , null);
4532 zoomControls.setOnZoomInClickListener(new OnClickListener() {
4533 public void onClick(View v) {
4534 // reset time out
4535 mPrivateHandler.removeCallbacks(mZoomControlRunnable);
4536 mPrivateHandler.postDelayed(mZoomControlRunnable,
4537 ZOOM_CONTROLS_TIMEOUT);
4538 zoomIn();
4539 }
4540 });
4541 zoomControls.setOnZoomOutClickListener(new OnClickListener() {
4542 public void onClick(View v) {
4543 // reset time out
4544 mPrivateHandler.removeCallbacks(mZoomControlRunnable);
4545 mPrivateHandler.postDelayed(mZoomControlRunnable,
4546 ZOOM_CONTROLS_TIMEOUT);
4547 zoomOut();
4548 }
4549 });
The Android Open Source Project10592532009-03-18 17:39:46 -07004550 return zoomControls;
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07004551 }
4552
4553 /**
4554 * Gets the {@link ZoomButtonsController} which can be used to add
4555 * additional buttons to the zoom controls window.
Cary Clarkd6982c92009-05-29 11:02:22 -04004556 *
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07004557 * @return The instance of {@link ZoomButtonsController} used by this class,
4558 * or null if it is unavailable.
The Android Open Source Project10592532009-03-18 17:39:46 -07004559 * @hide
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07004560 */
4561 public ZoomButtonsController getZoomButtonsController() {
4562 return mZoomButtonsController;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004563 }
4564
4565 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004566 * Perform zoom in in the webview
4567 * @return TRUE if zoom in succeeds. FALSE if no zoom changes.
4568 */
4569 public boolean zoomIn() {
4570 // TODO: alternatively we can disallow this during draw history mode
4571 switchOutDrawHistory();
Grace Kloba8b97e4b2009-07-28 13:11:38 -07004572 // Center zooming to the center of the screen.
Grace Kloba455e3af2009-08-13 11:01:21 -07004573 if (mInZoomOverview) {
4574 // if in overview mode, bring it back to normal mode
4575 mLastTouchX = getViewWidth() * .5f;
4576 mLastTouchY = getViewHeight() * .5f;
4577 doDoubleTap();
4578 return true;
4579 } else {
4580 mZoomCenterX = getViewWidth() * .5f;
4581 mZoomCenterY = getViewHeight() * .5f;
4582 return zoomWithPreview(mActualScale * 1.25f);
4583 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004584 }
4585
4586 /**
4587 * Perform zoom out in the webview
4588 * @return TRUE if zoom out succeeds. FALSE if no zoom changes.
4589 */
4590 public boolean zoomOut() {
4591 // TODO: alternatively we can disallow this during draw history mode
4592 switchOutDrawHistory();
Grace Klobae397a882009-08-06 12:04:14 -07004593 float scale = mActualScale * 0.8f;
Grace Kloba04b28682009-09-14 14:38:37 -07004594 if (scale < (mMinZoomScale + 0.1f)
Grace Klobae397a882009-08-06 12:04:14 -07004595 && mWebViewCore.getSettings().getUseWideViewPort()) {
4596 // when zoom out to min scale, switch to overview mode
4597 doDoubleTap();
4598 return true;
4599 } else {
4600 // Center zooming to the center of the screen.
4601 mZoomCenterX = getViewWidth() * .5f;
4602 mZoomCenterY = getViewHeight() * .5f;
4603 return zoomWithPreview(scale);
4604 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004605 }
4606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004607 private void updateSelection() {
4608 if (mNativeClass == 0) {
4609 return;
4610 }
4611 // mLastTouchX and mLastTouchY are the point in the current viewport
Leon Scroggins0236e672009-09-02 21:12:08 -04004612 int contentX = viewToContentX((int) mLastTouchX + mScrollX);
4613 int contentY = viewToContentY((int) mLastTouchY + mScrollY);
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07004614 Rect rect = new Rect(contentX - mNavSlop, contentY - mNavSlop,
4615 contentX + mNavSlop, contentY + mNavSlop);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004616 nativeSelectBestAt(rect);
4617 }
4618
Leon Scroggins0f5ad842009-07-17 15:08:34 -04004619 /**
Leon Scroggins72543e12009-07-23 15:29:45 -04004620 * Scroll the focused text field/area to match the WebTextView
Cary Clarkeaa18de2009-09-28 12:50:42 -04004621 * @param xPercent New x position of the WebTextView from 0 to 1.
Leon Scroggins72543e12009-07-23 15:29:45 -04004622 * @param y New y position of the WebTextView in view coordinates
4623 */
Cary Clarkeaa18de2009-09-28 12:50:42 -04004624 /*package*/ void scrollFocusedTextInput(float xPercent, int y) {
Leon Scroggins72543e12009-07-23 15:29:45 -04004625 if (!inEditingMode() || mWebViewCore == null) {
4626 return;
4627 }
Cary Clarkeaa18de2009-09-28 12:50:42 -04004628 mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT,
Leon Scrogginsd3997e52009-09-21 14:15:18 -04004629 // Since this position is relative to the top of the text input
4630 // field, we do not need to take the title bar's height into
4631 // consideration.
Cary Clarkeaa18de2009-09-28 12:50:42 -04004632 viewToContentDimension(y),
4633 new Float(xPercent));
Leon Scroggins72543e12009-07-23 15:29:45 -04004634 }
4635
4636 /**
Leon Scroggins0f5ad842009-07-17 15:08:34 -04004637 * Set our starting point and time for a drag from the WebTextView.
4638 */
4639 /*package*/ void initiateTextFieldDrag(float x, float y, long eventTime) {
4640 if (!inEditingMode()) {
4641 return;
4642 }
4643 mLastTouchX = x + (float) (mWebTextView.getLeft() - mScrollX);
4644 mLastTouchY = y + (float) (mWebTextView.getTop() - mScrollY);
4645 mLastTouchTime = eventTime;
4646 if (!mScroller.isFinished()) {
Cary Clark278ce052009-08-31 16:08:42 -04004647 abortAnimation();
Leon Scroggins0f5ad842009-07-17 15:08:34 -04004648 mPrivateHandler.removeMessages(RESUME_WEBCORE_UPDATE);
4649 }
4650 mSnapScrollMode = SNAP_NONE;
4651 mVelocityTracker = VelocityTracker.obtain();
4652 mTouchMode = TOUCH_DRAG_START_MODE;
4653 }
4654
4655 /**
4656 * Given a motion event from the WebTextView, set its location to our
4657 * coordinates, and handle the event.
4658 */
4659 /*package*/ boolean textFieldDrag(MotionEvent event) {
4660 if (!inEditingMode()) {
4661 return false;
4662 }
Leon Scroggins72543e12009-07-23 15:29:45 -04004663 mDragFromTextInput = true;
Leon Scroggins0f5ad842009-07-17 15:08:34 -04004664 event.offsetLocation((float) (mWebTextView.getLeft() - mScrollX),
4665 (float) (mWebTextView.getTop() - mScrollY));
Leon Scroggins72543e12009-07-23 15:29:45 -04004666 boolean result = onTouchEvent(event);
4667 mDragFromTextInput = false;
4668 return result;
Leon Scroggins0f5ad842009-07-17 15:08:34 -04004669 }
4670
Leon Scroggins6679f2f2009-08-12 18:48:10 -04004671 /**
4672 * Do a touch up from a WebTextView. This will be handled by webkit to
4673 * change the selection.
4674 * @param event MotionEvent in the WebTextView's coordinates.
4675 */
4676 /*package*/ void touchUpOnTextField(MotionEvent event) {
4677 if (!inEditingMode()) {
4678 return;
4679 }
Leon Scroggins0236e672009-09-02 21:12:08 -04004680 int x = viewToContentX((int) event.getX() + mWebTextView.getLeft());
4681 int y = viewToContentY((int) event.getY() + mWebTextView.getTop());
Cary Clarkdb6d9392009-09-15 13:13:23 -04004682 if (nativeFocusNodePointer() != nativeCursorNodePointer()) {
4683 nativeMotionUp(x, y, mNavSlop);
4684 }
Leon Scroggins6679f2f2009-08-12 18:48:10 -04004685 nativeTextInputMotionUp(x, y);
4686 }
4687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004688 /*package*/ void shortPressOnTextField() {
4689 if (inEditingMode()) {
Leon Scrogginsd3465f62009-06-02 10:57:54 -04004690 View v = mWebTextView;
Leon Scroggins0236e672009-09-02 21:12:08 -04004691 int x = viewToContentX((v.getLeft() + v.getRight()) >> 1);
4692 int y = viewToContentY((v.getTop() + v.getBottom()) >> 1);
Leon Scroggins6679f2f2009-08-12 18:48:10 -04004693 nativeTextInputMotionUp(x, y);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004694 }
4695 }
4696
4697 private void doShortPress() {
4698 if (mNativeClass == 0) {
4699 return;
4700 }
4701 switchOutDrawHistory();
4702 // mLastTouchX and mLastTouchY are the point in the current viewport
Leon Scroggins0236e672009-09-02 21:12:08 -04004703 int contentX = viewToContentX((int) mLastTouchX + mScrollX);
4704 int contentY = viewToContentY((int) mLastTouchY + mScrollY);
Cary Clark8f9ff7e2009-05-14 10:09:26 -04004705 if (nativeMotionUp(contentX, contentY, mNavSlop)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004706 if (mLogEvent) {
4707 Checkin.updateStats(mContext.getContentResolver(),
4708 Checkin.Stats.Tag.BROWSER_SNAP_CENTER, 1, 0.0);
4709 }
4710 }
Cary Clarkd6982c92009-05-29 11:02:22 -04004711 if (nativeHasCursorNode() && !nativeCursorIsTextInput()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004712 playSoundEffect(SoundEffectConstants.CLICK);
4713 }
4714 }
4715
Grace Kloba8b97e4b2009-07-28 13:11:38 -07004716 private void doDoubleTap() {
Leon Scroggins0236e672009-09-02 21:12:08 -04004717 if (mWebViewCore.getSettings().getUseWideViewPort() == false) {
Grace Kloba8b97e4b2009-07-28 13:11:38 -07004718 return;
4719 }
4720 mZoomCenterX = mLastTouchX;
4721 mZoomCenterY = mLastTouchY;
4722 mInZoomOverview = !mInZoomOverview;
Grace Klobad7660cc2009-08-17 17:13:01 -07004723 // remove the zoom control after double tap
Grace Klobaf8d8b462009-09-20 15:57:49 -07004724 WebSettings settings = getSettings();
4725 if (settings.getBuiltInZoomControls()) {
Grace Klobad7660cc2009-08-17 17:13:01 -07004726 if (mZoomButtonsController.isVisible()) {
4727 mZoomButtonsController.setVisible(false);
Grace Kloba8b97e4b2009-07-28 13:11:38 -07004728 }
Grace Klobad7660cc2009-08-17 17:13:01 -07004729 } else {
4730 if (mZoomControlRunnable != null) {
4731 mPrivateHandler.removeCallbacks(mZoomControlRunnable);
4732 }
4733 if (mZoomControls != null) {
4734 mZoomControls.hide();
4735 }
4736 }
Grace Klobaf8d8b462009-09-20 15:57:49 -07004737 settings.setDoubleTapToastCount(0);
Grace Klobad7660cc2009-08-17 17:13:01 -07004738 if (mInZoomOverview) {
Grace Kloba17dd1ae2009-09-18 15:11:51 -07004739 // Force the titlebar fully reveal in overview mode
4740 if (mScrollY < getTitleHeight()) mScrollY = 0;
Grace Klobae397a882009-08-06 12:04:14 -07004741 zoomWithPreview((float) getViewWidth() / mZoomOverviewWidth);
Grace Kloba8b97e4b2009-07-28 13:11:38 -07004742 } else {
4743 // mLastTouchX and mLastTouchY are the point in the current viewport
Leon Scroggins0236e672009-09-02 21:12:08 -04004744 int contentX = viewToContentX((int) mLastTouchX + mScrollX);
4745 int contentY = viewToContentY((int) mLastTouchY + mScrollY);
Cary Clark77d98f42009-07-31 09:40:38 -04004746 int left = nativeGetBlockLeftEdge(contentX, contentY, mActualScale);
Grace Kloba8b97e4b2009-07-28 13:11:38 -07004747 if (left != NO_LEFTEDGE) {
4748 // add a 5pt padding to the left edge. Re-calculate the zoom
4749 // center so that the new scroll x will be on the left edge.
4750 mZoomCenterX = left < 5 ? 0 : (left - 5) * mLastScale
4751 * mActualScale / (mLastScale - mActualScale);
4752 }
4753 zoomWithPreview(mLastScale);
4754 }
4755 }
4756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004757 // Called by JNI to handle a touch on a node representing an email address,
4758 // address, or phone number
4759 private void overrideLoading(String url) {
4760 mCallbackProxy.uiOverrideUrlLoading(url);
4761 }
4762
Derek Sollenberger945f3b42009-07-02 10:05:21 -04004763 // called by JNI
4764 private void sendPluginState(int state) {
4765 WebViewCore.PluginStateData psd = new WebViewCore.PluginStateData();
Cary Clark3e88ddc2009-10-08 14:59:46 -04004766 psd.mFrame = nativeFocusCandidateFramePointer();
4767 psd.mNode = nativeFocusCandidatePointer();
4768 if (DebugFlags.WEB_VIEW) {
4769 Log.v(LOGTAG, "sendPluginState frame=" + psd.mFrame
4770 + " node=" + psd.mNode);
4771 }
Derek Sollenberger945f3b42009-07-02 10:05:21 -04004772 psd.mState = state;
4773 mWebViewCore.sendMessage(EventHub.PLUGIN_STATE, psd);
4774 }
4775
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004776 @Override
4777 public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
4778 boolean result = false;
4779 if (inEditingMode()) {
Leon Scrogginsd3465f62009-06-02 10:57:54 -04004780 result = mWebTextView.requestFocus(direction,
4781 previouslyFocusedRect);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004782 } else {
4783 result = super.requestFocus(direction, previouslyFocusedRect);
4784 if (mWebViewCore.getSettings().getNeedInitialFocus()) {
4785 // For cases such as GMail, where we gain focus from a direction,
4786 // we want to move to the first available link.
4787 // FIXME: If there are no visible links, we may not want to
4788 int fakeKeyDirection = 0;
4789 switch(direction) {
4790 case View.FOCUS_UP:
4791 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_UP;
4792 break;
4793 case View.FOCUS_DOWN:
4794 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_DOWN;
4795 break;
4796 case View.FOCUS_LEFT:
4797 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_LEFT;
4798 break;
4799 case View.FOCUS_RIGHT:
4800 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_RIGHT;
4801 break;
4802 default:
4803 return result;
4804 }
Cary Clarkd6982c92009-05-29 11:02:22 -04004805 if (mNativeClass != 0 && !nativeHasCursorNode()) {
Cary Clark215b72c2009-06-26 14:38:43 -04004806 navHandledKey(fakeKeyDirection, 1, true, 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004807 }
4808 }
4809 }
4810 return result;
4811 }
4812
4813 @Override
4814 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
4815 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
4816
4817 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
4818 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
4819 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
4820 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
4821
4822 int measuredHeight = heightSize;
4823 int measuredWidth = widthSize;
4824
4825 // Grab the content size from WebViewCore.
Grace Klobae621d6f2009-09-11 13:20:39 -07004826 int contentHeight = contentToViewDimension(mContentHeight);
4827 int contentWidth = contentToViewDimension(mContentWidth);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004828
4829// Log.d(LOGTAG, "------- measure " + heightMode);
4830
4831 if (heightMode != MeasureSpec.EXACTLY) {
4832 mHeightCanMeasure = true;
4833 measuredHeight = contentHeight;
4834 if (heightMode == MeasureSpec.AT_MOST) {
4835 // If we are larger than the AT_MOST height, then our height can
4836 // no longer be measured and we should scroll internally.
4837 if (measuredHeight > heightSize) {
4838 measuredHeight = heightSize;
4839 mHeightCanMeasure = false;
4840 }
4841 }
4842 } else {
4843 mHeightCanMeasure = false;
4844 }
4845 if (mNativeClass != 0) {
4846 nativeSetHeightCanMeasure(mHeightCanMeasure);
4847 }
4848 // For the width, always use the given size unless unspecified.
4849 if (widthMode == MeasureSpec.UNSPECIFIED) {
4850 mWidthCanMeasure = true;
4851 measuredWidth = contentWidth;
4852 } else {
4853 mWidthCanMeasure = false;
4854 }
4855
4856 synchronized (this) {
4857 setMeasuredDimension(measuredWidth, measuredHeight);
4858 }
4859 }
4860
4861 @Override
4862 public boolean requestChildRectangleOnScreen(View child,
4863 Rect rect,
4864 boolean immediate) {
4865 rect.offset(child.getLeft() - child.getScrollX(),
4866 child.getTop() - child.getScrollY());
4867
Grace Kloba8eff73f2009-09-24 09:34:32 -07004868 int height = getViewHeightWithTitle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004869 int screenTop = mScrollY;
4870 int screenBottom = screenTop + height;
4871
4872 int scrollYDelta = 0;
4873
Leon Scrogginsbed911a2009-03-31 14:29:35 -07004874 if (rect.bottom > screenBottom) {
4875 int oneThirdOfScreenHeight = height / 3;
4876 if (rect.height() > 2 * oneThirdOfScreenHeight) {
4877 // If the rectangle is too tall to fit in the bottom two thirds
4878 // of the screen, place it at the top.
4879 scrollYDelta = rect.top - screenTop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004880 } else {
Leon Scrogginsbed911a2009-03-31 14:29:35 -07004881 // If the rectangle will still fit on screen, we want its
4882 // top to be in the top third of the screen.
4883 scrollYDelta = rect.top - (screenTop + oneThirdOfScreenHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004884 }
4885 } else if (rect.top < screenTop) {
Leon Scrogginsbed911a2009-03-31 14:29:35 -07004886 scrollYDelta = rect.top - screenTop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004887 }
4888
4889 int width = getWidth() - getVerticalScrollbarWidth();
4890 int screenLeft = mScrollX;
4891 int screenRight = screenLeft + width;
4892
4893 int scrollXDelta = 0;
4894
4895 if (rect.right > screenRight && rect.left > screenLeft) {
4896 if (rect.width() > width) {
4897 scrollXDelta += (rect.left - screenLeft);
4898 } else {
4899 scrollXDelta += (rect.right - screenRight);
4900 }
4901 } else if (rect.left < screenLeft) {
4902 scrollXDelta -= (screenLeft - rect.left);
4903 }
4904
4905 if ((scrollYDelta | scrollXDelta) != 0) {
4906 return pinScrollBy(scrollXDelta, scrollYDelta, !immediate, 0);
4907 }
4908
4909 return false;
4910 }
Cary Clarkd6982c92009-05-29 11:02:22 -04004911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004912 /* package */ void replaceTextfieldText(int oldStart, int oldEnd,
4913 String replace, int newStart, int newEnd) {
Cary Clarkded054c2009-06-15 10:26:08 -04004914 WebViewCore.ReplaceTextData arg = new WebViewCore.ReplaceTextData();
4915 arg.mReplace = replace;
4916 arg.mNewStart = newStart;
4917 arg.mNewEnd = newEnd;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004918 mTextGeneration++;
Leon Scroggins43488fc2009-07-06 14:32:49 -04004919 arg.mTextGeneration = mTextGeneration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004920 mWebViewCore.sendMessage(EventHub.REPLACE_TEXT, oldStart, oldEnd, arg);
4921 }
4922
4923 /* package */ void passToJavaScript(String currentText, KeyEvent event) {
Cary Clarkf958fcc2009-06-12 17:33:37 -04004924 if (nativeCursorWantsKeyEvents() && !nativeCursorMatchesFocus()) {
4925 mWebViewCore.sendMessage(EventHub.CLICK);
Cary Clark0c5924e2009-09-30 10:24:19 -04004926 if (mWebTextView.mOkayForFocusNotToMatch) {
4927 int select = nativeFocusCandidateIsTextField() ?
4928 nativeFocusCandidateMaxLength() : 0;
4929 setSelection(select, select);
4930 }
Cary Clarkf958fcc2009-06-12 17:33:37 -04004931 }
Cary Clarkded054c2009-06-15 10:26:08 -04004932 WebViewCore.JSKeyData arg = new WebViewCore.JSKeyData();
4933 arg.mEvent = event;
4934 arg.mCurrentText = currentText;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004935 // Increase our text generation number, and pass it to webcore thread
4936 mTextGeneration++;
4937 mWebViewCore.sendMessage(EventHub.PASS_TO_JS, mTextGeneration, 0, arg);
4938 // WebKit's document state is not saved until about to leave the page.
Cary Clarkd6982c92009-05-29 11:02:22 -04004939 // To make sure the host application, like Browser, has the up to date
4940 // document state when it goes to background, we force to save the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004941 // document state.
4942 mWebViewCore.removeMessages(EventHub.SAVE_DOCUMENT_STATE);
4943 mWebViewCore.sendMessageDelayed(EventHub.SAVE_DOCUMENT_STATE,
Cary Clarkd6982c92009-05-29 11:02:22 -04004944 cursorData(), 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004945 }
4946
4947 /* package */ WebViewCore getWebViewCore() {
4948 return mWebViewCore;
4949 }
4950
4951 //-------------------------------------------------------------------------
4952 // Methods can be called from a separate thread, like WebViewCore
4953 // If it needs to call the View system, it has to send message.
4954 //-------------------------------------------------------------------------
4955
4956 /**
4957 * General handler to receive message coming from webkit thread
4958 */
4959 class PrivateHandler extends Handler {
4960 @Override
4961 public void handleMessage(Message msg) {
Cary Clark3e88ddc2009-10-08 14:59:46 -04004962 // exclude INVAL_RECT_MSG_ID since it is frequently output
4963 if (DebugFlags.WEB_VIEW && msg.what != INVAL_RECT_MSG_ID) {
Cary Clarkd6982c92009-05-29 11:02:22 -04004964 Log.v(LOGTAG, msg.what < REMEMBER_PASSWORD || msg.what
Cary Clark3e88ddc2009-10-08 14:59:46 -04004965 > REQUEST_KEYBOARD ? Integer.toString(msg.what)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004966 : HandlerDebugString[msg.what - REMEMBER_PASSWORD]);
4967 }
Grace Kloba207308a2009-09-27 11:44:14 -07004968 if (mWebViewCore == null) {
4969 // after WebView's destroy() is called, skip handling messages.
4970 return;
4971 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004972 switch (msg.what) {
4973 case REMEMBER_PASSWORD: {
4974 mDatabase.setUsernamePassword(
4975 msg.getData().getString("host"),
4976 msg.getData().getString("username"),
4977 msg.getData().getString("password"));
4978 ((Message) msg.obj).sendToTarget();
4979 break;
4980 }
4981 case NEVER_REMEMBER_PASSWORD: {
4982 mDatabase.setUsernamePassword(
4983 msg.getData().getString("host"), null, null);
4984 ((Message) msg.obj).sendToTarget();
4985 break;
4986 }
4987 case SWITCH_TO_SHORTPRESS: {
Grace Klobaf58af622009-09-24 17:41:23 -07004988 // if mPreventDrag is not confirmed, treat it as no so that
4989 // it won't block panning the page.
4990 if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) {
4991 mPreventDrag = PREVENT_DRAG_NO;
4992 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004993 if (mTouchMode == TOUCH_INIT_MODE) {
4994 mTouchMode = TOUCH_SHORTPRESS_START_MODE;
4995 updateSelection();
Grace Kloba8b97e4b2009-07-28 13:11:38 -07004996 } else if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
4997 mTouchMode = TOUCH_DONE_MODE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004998 }
4999 break;
5000 }
5001 case SWITCH_TO_LONGPRESS: {
Grace Klobaf58af622009-09-24 17:41:23 -07005002 if (mPreventDrag == PREVENT_DRAG_NO) {
Grace Kloba6c451b72009-06-25 12:25:30 -07005003 mTouchMode = TOUCH_DONE_MODE;
5004 performLongClick();
Grace Kloba959046c2009-06-25 14:28:04 -07005005 rebuildWebTextView();
Grace Kloba6c451b72009-06-25 12:25:30 -07005006 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005007 break;
5008 }
Grace Kloba8b97e4b2009-07-28 13:11:38 -07005009 case RELEASE_SINGLE_TAP: {
Grace Klobaf58af622009-09-24 17:41:23 -07005010 if (mPreventDrag == PREVENT_DRAG_NO) {
Grace Kloba8b97e4b2009-07-28 13:11:38 -07005011 mTouchMode = TOUCH_DONE_MODE;
5012 doShortPress();
5013 }
5014 break;
5015 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005016 case SCROLL_BY_MSG_ID:
5017 setContentScrollBy(msg.arg1, msg.arg2, (Boolean) msg.obj);
5018 break;
5019 case SYNC_SCROLL_TO_MSG_ID:
5020 if (mUserScroll) {
Cary Clarkd6982c92009-05-29 11:02:22 -04005021 // if user has scrolled explicitly, don't sync the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005022 // scroll position any more
5023 mUserScroll = false;
5024 break;
5025 }
5026 // fall through
5027 case SCROLL_TO_MSG_ID:
5028 if (setContentScrollTo(msg.arg1, msg.arg2)) {
5029 // if we can't scroll to the exact position due to pin,
Cary Clarkd6982c92009-05-29 11:02:22 -04005030 // send a message to WebCore to re-scroll when we get a
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005031 // new picture
5032 mUserScroll = false;
5033 mWebViewCore.sendMessage(EventHub.SYNC_SCROLL,
5034 msg.arg1, msg.arg2);
5035 }
5036 break;
5037 case SPAWN_SCROLL_TO_MSG_ID:
5038 spawnContentScrollTo(msg.arg1, msg.arg2);
5039 break;
Grace Klobae397a882009-08-06 12:04:14 -07005040 case NEW_PICTURE_MSG_ID: {
5041 WebSettings settings = mWebViewCore.getSettings();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005042 // called for new content
Grace Kloba8b97e4b2009-07-28 13:11:38 -07005043 final int viewWidth = getViewWidth();
Cary Clarkd6982c92009-05-29 11:02:22 -04005044 final WebViewCore.DrawData draw =
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005045 (WebViewCore.DrawData) msg.obj;
5046 final Point viewSize = draw.mViewPoint;
Grace Klobae397a882009-08-06 12:04:14 -07005047 boolean useWideViewport = settings.getUseWideViewPort();
Grace Klobaef347ef2009-07-30 11:20:32 -07005048 WebViewCore.RestoreState restoreState = draw.mRestoreState;
5049 if (restoreState != null) {
5050 mInZoomOverview = false;
5051 mLastScale = restoreState.mTextWrapScale;
5052 if (restoreState.mMinScale == 0) {
Grace Kloba3c72fff2009-09-04 13:15:59 -07005053 if (restoreState.mMobileSite) {
Cary Clarkb82665e2009-09-23 12:49:28 -04005054 if (draw.mMinPrefWidth >
5055 Math.max(0, draw.mViewPoint.x)) {
Grace Kloba3c72fff2009-09-04 13:15:59 -07005056 mMinZoomScale = (float) viewWidth
5057 / draw.mMinPrefWidth;
5058 mMinZoomScaleFixed = false;
5059 } else {
Grace Kloba408cf852009-09-20 16:34:44 -07005060 mMinZoomScale = restoreState.mDefaultScale;
Grace Kloba3c72fff2009-09-04 13:15:59 -07005061 mMinZoomScaleFixed = true;
5062 }
5063 } else {
5064 mMinZoomScale = DEFAULT_MIN_ZOOM_SCALE;
5065 mMinZoomScaleFixed = false;
5066 }
Grace Klobaef347ef2009-07-30 11:20:32 -07005067 } else {
5068 mMinZoomScale = restoreState.mMinScale;
5069 mMinZoomScaleFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005070 }
Grace Klobaef347ef2009-07-30 11:20:32 -07005071 if (restoreState.mMaxScale == 0) {
5072 mMaxZoomScale = DEFAULT_MAX_ZOOM_SCALE;
5073 } else {
5074 mMaxZoomScale = restoreState.mMaxScale;
5075 }
Grace Klobaef347ef2009-07-30 11:20:32 -07005076 setNewZoomScale(mLastScale, false);
Leon Scrogginsd7b95aa2009-09-21 13:27:02 -04005077 setContentScrollTo(restoreState.mScrollX,
5078 restoreState.mScrollY);
Grace Kloba04b28682009-09-14 14:38:37 -07005079 if (useWideViewport
Grace Kloba3c72fff2009-09-04 13:15:59 -07005080 && settings.getLoadWithOverviewMode()) {
5081 if (restoreState.mViewScale == 0
5082 || (restoreState.mMobileSite
Grace Kloba408cf852009-09-20 16:34:44 -07005083 && mMinZoomScale < restoreState.mDefaultScale)) {
Leon Scrogginsb2359262009-08-19 16:19:26 -04005084 mInZoomOverview = true;
Leon Scrogginsb2359262009-08-19 16:19:26 -04005085 }
5086 }
Grace Klobaef347ef2009-07-30 11:20:32 -07005087 // As we are on a new page, remove the WebTextView. This
5088 // is necessary for page loads driven by webkit, and in
5089 // particular when the user was on a password field, so
5090 // the WebTextView was visible.
5091 clearTextEntry();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005092 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005093 // We update the layout (i.e. request a layout from the
5094 // view system) if the last view size that we sent to
5095 // WebCore matches the view size of the picture we just
5096 // received in the fixed dimension.
5097 final boolean updateLayout = viewSize.x == mLastWidthSent
5098 && viewSize.y == mLastHeightSent;
Cary Clarkd6982c92009-05-29 11:02:22 -04005099 recordNewContentSize(draw.mWidthHeight.x,
Cary Clark5bb6b522009-09-21 11:58:31 -04005100 draw.mWidthHeight.y
5101 + (mFindIsUp ? mFindHeight : 0), updateLayout);
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04005102 if (DebugFlags.WEB_VIEW) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005103 Rect b = draw.mInvalRegion.getBounds();
5104 Log.v(LOGTAG, "NEW_PICTURE_MSG_ID {" +
5105 b.left+","+b.top+","+b.right+","+b.bottom+"}");
5106 }
Mike Reede9e86b82009-09-15 11:26:53 -04005107 invalidateContentRect(draw.mInvalRegion.getBounds());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005108 if (mPictureListener != null) {
5109 mPictureListener.onNewPicture(WebView.this, capturePicture());
5110 }
Grace Klobaef347ef2009-07-30 11:20:32 -07005111 if (useWideViewport) {
Grace Kloba8b97e4b2009-07-28 13:11:38 -07005112 mZoomOverviewWidth = Math.max(draw.mMinPrefWidth,
5113 draw.mViewPoint.x);
5114 }
5115 if (!mMinZoomScaleFixed) {
Grace Klobae397a882009-08-06 12:04:14 -07005116 mMinZoomScale = (float) viewWidth / mZoomOverviewWidth;
Grace Kloba8b97e4b2009-07-28 13:11:38 -07005117 }
5118 if (!mDrawHistory && mInZoomOverview) {
5119 // fit the content width to the current view. Ignore
5120 // the rounding error case.
5121 if (Math.abs((viewWidth * mInvActualScale)
5122 - mZoomOverviewWidth) > 1) {
Grace Klobae397a882009-08-06 12:04:14 -07005123 setNewZoomScale((float) viewWidth
5124 / mZoomOverviewWidth, false);
Grace Kloba8b97e4b2009-07-28 13:11:38 -07005125 }
5126 }
Cary Clark5da9aeb2009-10-06 17:40:53 -04005127 if (draw.mFocusSizeChanged && inEditingMode()) {
5128 mFocusSizeChanged = true;
5129 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005130 break;
Grace Klobae397a882009-08-06 12:04:14 -07005131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005132 case WEBCORE_INITIALIZED_MSG_ID:
5133 // nativeCreate sets mNativeClass to a non-zero value
5134 nativeCreate(msg.arg1);
5135 break;
5136 case UPDATE_TEXTFIELD_TEXT_MSG_ID:
5137 // Make sure that the textfield is currently focused
Cary Clarkd6982c92009-05-29 11:02:22 -04005138 // and representing the same node as the pointer.
5139 if (inEditingMode() &&
Leon Scrogginsd3465f62009-06-02 10:57:54 -04005140 mWebTextView.isSameTextField(msg.arg1)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005141 if (msg.getData().getBoolean("password")) {
Leon Scrogginsd3465f62009-06-02 10:57:54 -04005142 Spannable text = (Spannable) mWebTextView.getText();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005143 int start = Selection.getSelectionStart(text);
5144 int end = Selection.getSelectionEnd(text);
Leon Scrogginsd3465f62009-06-02 10:57:54 -04005145 mWebTextView.setInPassword(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005146 // Restore the selection, which may have been
5147 // ruined by setInPassword.
Leon Scrogginsd3465f62009-06-02 10:57:54 -04005148 Spannable pword =
5149 (Spannable) mWebTextView.getText();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005150 Selection.setSelection(pword, start, end);
5151 // If the text entry has created more events, ignore
5152 // this one.
5153 } else if (msg.arg2 == mTextGeneration) {
Leon Scrogginsd3465f62009-06-02 10:57:54 -04005154 mWebTextView.setTextAndKeepSelection(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005155 (String) msg.obj);
5156 }
5157 }
5158 break;
Leon Scroggins6679f2f2009-08-12 18:48:10 -04005159 case UPDATE_TEXT_SELECTION_MSG_ID:
5160 if (inEditingMode()
5161 && mWebTextView.isSameTextField(msg.arg1)
5162 && msg.arg2 == mTextGeneration) {
5163 WebViewCore.TextSelectionData tData
5164 = (WebViewCore.TextSelectionData) msg.obj;
5165 mWebTextView.setSelectionFromWebKit(tData.mStart,
5166 tData.mEnd);
5167 }
5168 break;
Cary Clark215b72c2009-06-26 14:38:43 -04005169 case MOVE_OUT_OF_PLUGIN:
5170 if (nativePluginEatsNavKey()) {
5171 navHandledKey(msg.arg1, 1, false, 0, true);
5172 }
5173 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005174 case UPDATE_TEXT_ENTRY_MSG_ID:
Cary Clarkd6982c92009-05-29 11:02:22 -04005175 // this is sent after finishing resize in WebViewCore. Make
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005176 // sure the text edit box is still on the screen.
Cary Clarkd6982c92009-05-29 11:02:22 -04005177 if (inEditingMode() && nativeCursorIsTextInput()) {
Leon Scrogginsd3465f62009-06-02 10:57:54 -04005178 mWebTextView.bringIntoView();
Leon Scroggins4890feb2009-07-02 10:37:10 -04005179 rebuildWebTextView();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005180 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005181 break;
Cary Clark243ea062009-06-25 10:49:32 -04005182 case CLEAR_TEXT_ENTRY:
5183 clearTextEntry();
5184 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005185 case INVAL_RECT_MSG_ID: {
5186 Rect r = (Rect)msg.obj;
5187 if (r == null) {
5188 invalidate();
5189 } else {
5190 // we need to scale r from content into view coords,
5191 // which viewInvalidate() does for us
5192 viewInvalidate(r.left, r.top, r.right, r.bottom);
5193 }
5194 break;
5195 }
Leon Scrogginsd3465f62009-06-02 10:57:54 -04005196 case REQUEST_FORM_DATA:
Cary Clarkded054c2009-06-15 10:26:08 -04005197 AutoCompleteAdapter adapter = (AutoCompleteAdapter) msg.obj;
Leon Scrogginsd3465f62009-06-02 10:57:54 -04005198 if (mWebTextView.isSameTextField(msg.arg1)) {
Leon Scrogginsd3465f62009-06-02 10:57:54 -04005199 mWebTextView.setAdapterCustom(adapter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005200 }
5201 break;
5202 case UPDATE_CLIPBOARD:
5203 String str = (String) msg.obj;
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04005204 if (DebugFlags.WEB_VIEW) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005205 Log.v(LOGTAG, "UPDATE_CLIPBOARD " + str);
5206 }
5207 try {
5208 IClipboard clip = IClipboard.Stub.asInterface(
5209 ServiceManager.getService("clipboard"));
5210 clip.setClipboardText(str);
5211 } catch (android.os.RemoteException e) {
5212 Log.e(LOGTAG, "Clipboard failed", e);
5213 }
5214 break;
5215 case RESUME_WEBCORE_UPDATE:
5216 WebViewCore.resumeUpdate(mWebViewCore);
5217 break;
5218
Leon Scrogginse3225672009-06-03 15:53:13 -04005219 case LONG_PRESS_CENTER:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005220 // as this is shared by keydown and trackballdown, reset all
5221 // the states
Leon Scrogginse3225672009-06-03 15:53:13 -04005222 mGotCenterDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005223 mTrackballDown = false;
Leon Scrogginse3225672009-06-03 15:53:13 -04005224 // LONG_PRESS_CENTER is sent as a delayed message. If we
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005225 // switch to windows overview, the WebView will be
5226 // temporarily removed from the view system. In that case,
5227 // do nothing.
5228 if (getParent() != null) {
5229 performLongClick();
5230 }
5231 break;
5232
5233 case WEBCORE_NEED_TOUCH_EVENTS:
5234 mForwardTouchEvents = (msg.arg1 != 0);
5235 break;
5236
5237 case PREVENT_TOUCH_ID:
5238 if (msg.arg1 == MotionEvent.ACTION_DOWN) {
Grace Klobaf58af622009-09-24 17:41:23 -07005239 // dont override if mPreventDrag has been set to no due
5240 // to time out
5241 if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) {
5242 mPreventDrag = msg.arg2 == 1 ? PREVENT_DRAG_YES
5243 : PREVENT_DRAG_NO;
5244 if (mPreventDrag == PREVENT_DRAG_YES) {
5245 mTouchMode = TOUCH_DONE_MODE;
5246 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005247 }
5248 }
5249 break;
5250
Derek Sollenberger4c41e8d2009-06-29 13:49:27 -04005251 case REQUEST_KEYBOARD:
5252 if (msg.arg1 == 0) {
5253 hideSoftKeyboard();
5254 } else {
5255 displaySoftKeyboard(false);
Cary Clark3e88ddc2009-10-08 14:59:46 -04005256 if (DebugFlags.WEB_VIEW) {
5257 Log.v(LOGTAG, "REQUEST_KEYBOARD"
5258 + " focusCandidateIsPlugin="
5259 + nativeFocusCandidateIsPlugin());
5260 }
Derek Sollenberger4c41e8d2009-06-29 13:49:27 -04005261 }
5262 break;
5263
Cary Clark25415e22009-10-12 13:41:28 -04005264 case DRAG_HELD_MOTIONLESS:
5265 mHeldMotionless = MOTIONLESS_TRUE;
5266 invalidate();
5267 // fall through to keep scrollbars awake
5268
5269 case AWAKEN_SCROLL_BARS:
5270 if (mTouchMode == TOUCH_DRAG_MODE
5271 && mHeldMotionless == MOTIONLESS_TRUE) {
5272 awakenScrollBars(ViewConfiguration
5273 .getScrollDefaultDelay(), false);
5274 mPrivateHandler.sendMessageDelayed(mPrivateHandler
5275 .obtainMessage(AWAKEN_SCROLL_BARS),
5276 ViewConfiguration.getScrollDefaultDelay());
5277 }
5278 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005279 default:
5280 super.handleMessage(msg);
5281 break;
5282 }
5283 }
5284 }
5285
5286 // Class used to use a dropdown for a <select> element
5287 private class InvokeListBox implements Runnable {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005288 // Whether the listbox allows multiple selection.
5289 private boolean mMultiple;
5290 // Passed in to a list with multiple selection to tell
5291 // which items are selected.
5292 private int[] mSelectedArray;
Cary Clarkd6982c92009-05-29 11:02:22 -04005293 // Passed in to a list with single selection to tell
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005294 // where the initial selection is.
5295 private int mSelection;
5296
5297 private Container[] mContainers;
5298
5299 // Need these to provide stable ids to my ArrayAdapter,
5300 // which normally does not have stable ids. (Bug 1250098)
5301 private class Container extends Object {
5302 String mString;
5303 boolean mEnabled;
5304 int mId;
5305
5306 public String toString() {
5307 return mString;
5308 }
5309 }
5310
5311 /**
Cary Clarkd6982c92009-05-29 11:02:22 -04005312 * Subclass ArrayAdapter so we can disable OptionGroupLabels,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005313 * and allow filtering.
5314 */
5315 private class MyArrayListAdapter extends ArrayAdapter<Container> {
5316 public MyArrayListAdapter(Context context, Container[] objects, boolean multiple) {
Cary Clarkd6982c92009-05-29 11:02:22 -04005317 super(context,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005318 multiple ? com.android.internal.R.layout.select_dialog_multichoice :
Cary Clarkd6982c92009-05-29 11:02:22 -04005319 com.android.internal.R.layout.select_dialog_singlechoice,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005320 objects);
5321 }
5322
5323 @Override
5324 public boolean hasStableIds() {
Leon Scroggins3667ce42009-05-13 15:58:03 -04005325 // AdapterView's onChanged method uses this to determine whether
5326 // to restore the old state. Return false so that the old (out
5327 // of date) state does not replace the new, valid state.
5328 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005329 }
5330
5331 private Container item(int position) {
5332 if (position < 0 || position >= getCount()) {
5333 return null;
5334 }
5335 return (Container) getItem(position);
5336 }
5337
5338 @Override
5339 public long getItemId(int position) {
5340 Container item = item(position);
5341 if (item == null) {
5342 return -1;
5343 }
5344 return item.mId;
5345 }
5346
5347 @Override
5348 public boolean areAllItemsEnabled() {
5349 return false;
5350 }
5351
5352 @Override
5353 public boolean isEnabled(int position) {
5354 Container item = item(position);
5355 if (item == null) {
5356 return false;
5357 }
5358 return item.mEnabled;
5359 }
5360 }
5361
5362 private InvokeListBox(String[] array,
5363 boolean[] enabled, int[] selected) {
5364 mMultiple = true;
5365 mSelectedArray = selected;
5366
5367 int length = array.length;
5368 mContainers = new Container[length];
5369 for (int i = 0; i < length; i++) {
5370 mContainers[i] = new Container();
5371 mContainers[i].mString = array[i];
5372 mContainers[i].mEnabled = enabled[i];
5373 mContainers[i].mId = i;
5374 }
5375 }
5376
Cary Clarkd6982c92009-05-29 11:02:22 -04005377 private InvokeListBox(String[] array, boolean[] enabled, int
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005378 selection) {
5379 mSelection = selection;
5380 mMultiple = false;
5381
5382 int length = array.length;
5383 mContainers = new Container[length];
5384 for (int i = 0; i < length; i++) {
5385 mContainers[i] = new Container();
5386 mContainers[i].mString = array[i];
5387 mContainers[i].mEnabled = enabled[i];
5388 mContainers[i].mId = i;
5389 }
5390 }
5391
Leon Scroggins3667ce42009-05-13 15:58:03 -04005392 /*
5393 * Whenever the data set changes due to filtering, this class ensures
5394 * that the checked item remains checked.
5395 */
5396 private class SingleDataSetObserver extends DataSetObserver {
5397 private long mCheckedId;
5398 private ListView mListView;
5399 private Adapter mAdapter;
5400
5401 /*
5402 * Create a new observer.
5403 * @param id The ID of the item to keep checked.
5404 * @param l ListView for getting and clearing the checked states
5405 * @param a Adapter for getting the IDs
5406 */
5407 public SingleDataSetObserver(long id, ListView l, Adapter a) {
5408 mCheckedId = id;
5409 mListView = l;
5410 mAdapter = a;
5411 }
5412
5413 public void onChanged() {
5414 // The filter may have changed which item is checked. Find the
5415 // item that the ListView thinks is checked.
5416 int position = mListView.getCheckedItemPosition();
5417 long id = mAdapter.getItemId(position);
5418 if (mCheckedId != id) {
5419 // Clear the ListView's idea of the checked item, since
5420 // it is incorrect
5421 mListView.clearChoices();
5422 // Search for mCheckedId. If it is in the filtered list,
5423 // mark it as checked
5424 int count = mAdapter.getCount();
5425 for (int i = 0; i < count; i++) {
5426 if (mAdapter.getItemId(i) == mCheckedId) {
5427 mListView.setItemChecked(i, true);
5428 break;
5429 }
5430 }
5431 }
5432 }
5433
5434 public void onInvalidate() {}
5435 }
5436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005437 public void run() {
5438 final ListView listView = (ListView) LayoutInflater.from(mContext)
5439 .inflate(com.android.internal.R.layout.select_dialog, null);
Cary Clarkd6982c92009-05-29 11:02:22 -04005440 final MyArrayListAdapter adapter = new
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005441 MyArrayListAdapter(mContext, mContainers, mMultiple);
5442 AlertDialog.Builder b = new AlertDialog.Builder(mContext)
5443 .setView(listView).setCancelable(true)
5444 .setInverseBackgroundForced(true);
Cary Clarkd6982c92009-05-29 11:02:22 -04005445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005446 if (mMultiple) {
5447 b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
5448 public void onClick(DialogInterface dialog, int which) {
5449 mWebViewCore.sendMessage(
Cary Clarkd6982c92009-05-29 11:02:22 -04005450 EventHub.LISTBOX_CHOICES,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005451 adapter.getCount(), 0,
5452 listView.getCheckedItemPositions());
5453 }});
Leon Scroggins238ddbb2009-04-02 10:47:53 -07005454 b.setNegativeButton(android.R.string.cancel,
5455 new DialogInterface.OnClickListener() {
5456 public void onClick(DialogInterface dialog, int which) {
5457 mWebViewCore.sendMessage(
5458 EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
5459 }});
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005460 }
5461 final AlertDialog dialog = b.create();
5462 listView.setAdapter(adapter);
5463 listView.setFocusableInTouchMode(true);
5464 // There is a bug (1250103) where the checks in a ListView with
5465 // multiple items selected are associated with the positions, not
Cary Clarkd6982c92009-05-29 11:02:22 -04005466 // the ids, so the items do not properly retain their checks when
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005467 // filtered. Do not allow filtering on multiple lists until
5468 // that bug is fixed.
Cary Clarkd6982c92009-05-29 11:02:22 -04005469
Leon Scroggins3667ce42009-05-13 15:58:03 -04005470 listView.setTextFilterEnabled(!mMultiple);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005471 if (mMultiple) {
5472 listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
5473 int length = mSelectedArray.length;
5474 for (int i = 0; i < length; i++) {
5475 listView.setItemChecked(mSelectedArray[i], true);
5476 }
5477 } else {
5478 listView.setOnItemClickListener(new OnItemClickListener() {
5479 public void onItemClick(AdapterView parent, View v,
5480 int position, long id) {
5481 mWebViewCore.sendMessage(
5482 EventHub.SINGLE_LISTBOX_CHOICE, (int)id, 0);
5483 dialog.dismiss();
5484 }
5485 });
5486 if (mSelection != -1) {
5487 listView.setSelection(mSelection);
5488 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
5489 listView.setItemChecked(mSelection, true);
Leon Scroggins3667ce42009-05-13 15:58:03 -04005490 DataSetObserver observer = new SingleDataSetObserver(
5491 adapter.getItemId(mSelection), listView, adapter);
5492 adapter.registerDataSetObserver(observer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005493 }
5494 }
5495 dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
5496 public void onCancel(DialogInterface dialog) {
5497 mWebViewCore.sendMessage(
5498 EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
5499 }
5500 });
5501 dialog.show();
5502 }
5503 }
5504
5505 /*
5506 * Request a dropdown menu for a listbox with multiple selection.
5507 *
5508 * @param array Labels for the listbox.
5509 * @param enabledArray Which positions are enabled.
5510 * @param selectedArray Which positions are initally selected.
5511 */
5512 void requestListBox(String[] array, boolean[]enabledArray, int[]
5513 selectedArray) {
5514 mPrivateHandler.post(
5515 new InvokeListBox(array, enabledArray, selectedArray));
5516 }
5517
5518 /*
5519 * Request a dropdown menu for a listbox with single selection or a single
5520 * <select> element.
5521 *
5522 * @param array Labels for the listbox.
5523 * @param enabledArray Which positions are enabled.
5524 * @param selection Which position is initally selected.
5525 */
5526 void requestListBox(String[] array, boolean[]enabledArray, int selection) {
5527 mPrivateHandler.post(
5528 new InvokeListBox(array, enabledArray, selection));
5529 }
5530
5531 // called by JNI
Cary Clarkd6982c92009-05-29 11:02:22 -04005532 private void sendMoveMouse(int frame, int node, int x, int y) {
5533 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE,
5534 new WebViewCore.CursorData(frame, node, x, y));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005535 }
5536
Leon Scroggins0658e8f2009-06-26 14:09:09 -04005537 /*
5538 * Send a mouse move event to the webcore thread.
5539 *
5540 * @param removeFocus Pass true if the "mouse" cursor is now over a node
5541 * which wants key events, but it is not the focus. This
5542 * will make the visual appear as though nothing is in
5543 * focus. Remove the WebTextView, if present, and stop
5544 * drawing the blinking caret.
5545 * called by JNI
5546 */
5547 private void sendMoveMouseIfLatest(boolean removeFocus) {
5548 if (removeFocus) {
5549 clearTextEntry();
Leon Scrogginsfa03cde2009-06-15 15:48:46 -04005550 setFocusControllerInactive();
Cary Clark19436562009-06-04 16:25:07 -04005551 }
Leon Scroggins0658e8f2009-06-26 14:09:09 -04005552 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE_IF_LATEST,
5553 cursorData());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005554 }
5555
5556 // called by JNI
Cary Clarkd6982c92009-05-29 11:02:22 -04005557 private void sendMotionUp(int touchGeneration,
Leon Scroggins6679f2f2009-08-12 18:48:10 -04005558 int frame, int node, int x, int y) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005559 WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData();
5560 touchUpData.mMoveGeneration = touchGeneration;
Cary Clarkd6982c92009-05-29 11:02:22 -04005561 touchUpData.mFrame = frame;
5562 touchUpData.mNode = node;
5563 touchUpData.mX = x;
5564 touchUpData.mY = y;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005565 mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData);
5566 }
5567
5568
5569 private int getScaledMaxXScroll() {
5570 int width;
5571 if (mHeightCanMeasure == false) {
5572 width = getViewWidth() / 4;
5573 } else {
5574 Rect visRect = new Rect();
5575 calcOurVisibleRect(visRect);
5576 width = visRect.width() / 2;
5577 }
5578 // FIXME the divisor should be retrieved from somewhere
Leon Scroggins0236e672009-09-02 21:12:08 -04005579 return viewToContentX(width);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005580 }
5581
5582 private int getScaledMaxYScroll() {
5583 int height;
5584 if (mHeightCanMeasure == false) {
5585 height = getViewHeight() / 4;
5586 } else {
5587 Rect visRect = new Rect();
5588 calcOurVisibleRect(visRect);
5589 height = visRect.height() / 2;
5590 }
5591 // FIXME the divisor should be retrieved from somewhere
5592 // the closest thing today is hard-coded into ScrollView.java
5593 // (from ScrollView.java, line 363) int maxJump = height/2;
Cary Clarkdf344372009-09-15 12:47:39 -04005594 return Math.round(height * mInvActualScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005595 }
5596
5597 /**
5598 * Called by JNI to invalidate view
5599 */
5600 private void viewInvalidate() {
5601 invalidate();
5602 }
Cary Clarkd6982c92009-05-29 11:02:22 -04005603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005604 // return true if the key was handled
Cary Clark215b72c2009-06-26 14:38:43 -04005605 private boolean navHandledKey(int keyCode, int count, boolean noScroll,
5606 long time, boolean ignorePlugin) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005607 if (mNativeClass == 0) {
5608 return false;
5609 }
Cary Clark215b72c2009-06-26 14:38:43 -04005610 if (ignorePlugin == false && nativePluginEatsNavKey()) {
5611 KeyEvent event = new KeyEvent(time, time, KeyEvent.ACTION_DOWN
5612 , keyCode, count, (mShiftIsPressed ? KeyEvent.META_SHIFT_ON : 0)
5613 | (false ? KeyEvent.META_ALT_ON : 0) // FIXME
5614 | (false ? KeyEvent.META_SYM_ON : 0) // FIXME
5615 , 0, 0, 0);
5616 mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
5617 mWebViewCore.sendMessage(EventHub.KEY_UP, event);
5618 return true;
5619 }
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04005620 mLastCursorTime = time;
5621 mLastCursorBounds = nativeGetCursorRingBounds();
5622 boolean keyHandled
5623 = nativeMoveCursor(keyCode, count, noScroll) == false;
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04005624 if (DebugFlags.WEB_VIEW) {
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04005625 Log.v(LOGTAG, "navHandledKey mLastCursorBounds=" + mLastCursorBounds
5626 + " mLastCursorTime=" + mLastCursorTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005627 + " handled=" + keyHandled);
5628 }
5629 if (keyHandled == false || mHeightCanMeasure == false) {
5630 return keyHandled;
5631 }
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04005632 Rect contentCursorRingBounds = nativeGetCursorRingBounds();
5633 if (contentCursorRingBounds.isEmpty()) return keyHandled;
Mike Reede9e86b82009-09-15 11:26:53 -04005634 Rect viewCursorRingBounds = contentToViewRect(contentCursorRingBounds);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005635 Rect visRect = new Rect();
5636 calcOurVisibleRect(visRect);
5637 Rect outset = new Rect(visRect);
5638 int maxXScroll = visRect.width() / 2;
5639 int maxYScroll = visRect.height() / 2;
5640 outset.inset(-maxXScroll, -maxYScroll);
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04005641 if (Rect.intersects(outset, viewCursorRingBounds) == false) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005642 return keyHandled;
5643 }
5644 // FIXME: Necessary because ScrollView/ListView do not scroll left/right
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04005645 int maxH = Math.min(viewCursorRingBounds.right - visRect.right,
5646 maxXScroll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005647 if (maxH > 0) {
5648 pinScrollBy(maxH, 0, true, 0);
5649 } else {
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04005650 maxH = Math.max(viewCursorRingBounds.left - visRect.left,
5651 -maxXScroll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005652 if (maxH < 0) {
5653 pinScrollBy(maxH, 0, true, 0);
5654 }
5655 }
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04005656 if (mLastCursorBounds.isEmpty()) return keyHandled;
5657 if (mLastCursorBounds.equals(contentCursorRingBounds)) {
5658 return keyHandled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005659 }
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04005660 if (DebugFlags.WEB_VIEW) {
5661 Log.v(LOGTAG, "navHandledKey contentCursorRingBounds="
5662 + contentCursorRingBounds);
5663 }
5664 requestRectangleOnScreen(viewCursorRingBounds);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005665 mUserScroll = true;
5666 return keyHandled;
5667 }
Cary Clarkd6982c92009-05-29 11:02:22 -04005668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005669 /**
5670 * Set the background color. It's white by default. Pass
5671 * zero to make the view transparent.
5672 * @param color the ARGB color described by Color.java
5673 */
5674 public void setBackgroundColor(int color) {
5675 mBackgroundColor = color;
5676 mWebViewCore.sendMessage(EventHub.SET_BACKGROUND_COLOR, color);
5677 }
5678
5679 public void debugDump() {
5680 nativeDebugDump();
5681 mWebViewCore.sendMessage(EventHub.DUMP_NAVTREE);
5682 }
Cary Clarkd6982c92009-05-29 11:02:22 -04005683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005684 /**
Mike Reedefe2c722009-10-14 09:42:02 -04005685 * Draw the HTML page into the specified canvas. This call ignores any
5686 * view-specific zoom, scroll offset, or other changes. It does not draw
5687 * any view-specific chrome, such as progress or URL bars.
5688 *
5689 * @hide only needs to be accessible to Browser and testing
5690 */
5691 public void drawPage(Canvas canvas) {
5692 mWebViewCore.drawContentPicture(canvas, 0, false, false);
5693 }
5694
5695 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005696 * Update our cache with updatedText.
5697 * @param updatedText The new text to put in our cache.
5698 */
5699 /* package */ void updateCachedTextfield(String updatedText) {
5700 // Also place our generation number so that when we look at the cache
5701 // we recognize that it is up to date.
5702 nativeUpdateCachedTextfield(updatedText, mTextGeneration);
5703 }
Cary Clarkd6982c92009-05-29 11:02:22 -04005704
Leon Scroggins4890feb2009-07-02 10:37:10 -04005705 /* package */ native void nativeClearCursor();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005706 private native void nativeCreate(int ptr);
Cary Clarkd6982c92009-05-29 11:02:22 -04005707 private native int nativeCursorFramePointer();
5708 private native Rect nativeCursorNodeBounds();
5709 /* package */ native int nativeCursorNodePointer();
5710 /* package */ native boolean nativeCursorMatchesFocus();
5711 private native boolean nativeCursorIntersects(Rect visibleRect);
5712 private native boolean nativeCursorIsAnchor();
5713 private native boolean nativeCursorIsTextInput();
Cary Clarked56eda2009-06-18 09:48:47 -04005714 private native Point nativeCursorPosition();
Cary Clarkd6982c92009-05-29 11:02:22 -04005715 private native String nativeCursorText();
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04005716 /**
5717 * Returns true if the native cursor node says it wants to handle key events
5718 * (ala plugins). This can only be called if mNativeClass is non-zero!
5719 */
Cary Clark2f1d60c2009-06-03 08:05:53 -04005720 private native boolean nativeCursorWantsKeyEvents();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005721 private native void nativeDebugDump();
5722 private native void nativeDestroy();
Cary Clarkd6982c92009-05-29 11:02:22 -04005723 private native void nativeDrawCursorRing(Canvas content);
5724 private native void nativeDrawMatches(Canvas canvas);
Cary Clarkbadd8392009-10-15 13:32:08 -04005725 private native void nativeDrawSelection(Canvas content, float scale,
5726 int offset, int x, int y, boolean extendSelection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005727 private native void nativeDrawSelectionRegion(Canvas content);
Cary Clarkd6982c92009-05-29 11:02:22 -04005728 private native void nativeDumpDisplayTree(String urlOrNull);
5729 private native int nativeFindAll(String findLower, String findUpper);
5730 private native void nativeFindNext(boolean forward);
Cary Clark3e88ddc2009-10-08 14:59:46 -04005731 private native int nativeFocusCandidateFramePointer();
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04005732 private native boolean nativeFocusCandidateIsPassword();
Cary Clark3e88ddc2009-10-08 14:59:46 -04005733 private native boolean nativeFocusCandidateIsPlugin();
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04005734 private native boolean nativeFocusCandidateIsRtlText();
5735 private native boolean nativeFocusCandidateIsTextField();
5736 private native boolean nativeFocusCandidateIsTextInput();
5737 private native int nativeFocusCandidateMaxLength();
Leon Scroggins0ca70882009-06-26 17:45:29 -04005738 /* package */ native String nativeFocusCandidateName();
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04005739 private native Rect nativeFocusCandidateNodeBounds();
5740 /* package */ native int nativeFocusCandidatePointer();
5741 private native String nativeFocusCandidateText();
5742 private native int nativeFocusCandidateTextSize();
Leon Scroggins4890feb2009-07-02 10:37:10 -04005743 /* package */ native int nativeFocusNodePointer();
Cary Clarkd6982c92009-05-29 11:02:22 -04005744 private native Rect nativeGetCursorRingBounds();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005745 private native Region nativeGetSelection();
Cary Clarkd6982c92009-05-29 11:02:22 -04005746 private native boolean nativeHasCursorNode();
5747 private native boolean nativeHasFocusNode();
Cary Clarke872f3a2009-06-11 09:51:11 -04005748 private native void nativeHideCursor();
Cary Clarkd6982c92009-05-29 11:02:22 -04005749 private native String nativeImageURI(int x, int y);
5750 private native void nativeInstrumentReport();
Leon Scroggins01058282009-07-30 16:33:56 -04005751 /* package */ native void nativeMoveCursorToNextTextInput();
Cary Clarkd6982c92009-05-29 11:02:22 -04005752 // return true if the page has been scrolled
5753 private native boolean nativeMotionUp(int x, int y, int slop);
5754 // returns false if it handled the key
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04005755 private native boolean nativeMoveCursor(int keyCode, int count,
Cary Clarkd6982c92009-05-29 11:02:22 -04005756 boolean noScroll);
5757 private native int nativeMoveGeneration();
5758 private native void nativeMoveSelection(int x, int y,
5759 boolean extendSelection);
Cary Clark215b72c2009-06-26 14:38:43 -04005760 private native boolean nativePluginEatsNavKey();
Cary Clarkd6982c92009-05-29 11:02:22 -04005761 // Like many other of our native methods, you must make sure that
5762 // mNativeClass is not null before calling this method.
5763 private native void nativeRecordButtons(boolean focused,
5764 boolean pressed, boolean invalidate);
5765 private native void nativeSelectBestAt(Rect rect);
5766 private native void nativeSetFindIsDown();
5767 private native void nativeSetFollowedLink(boolean followed);
5768 private native void nativeSetHeightCanMeasure(boolean measure);
Leon Scroggins01058282009-07-30 16:33:56 -04005769 // Returns a value corresponding to CachedFrame::ImeAction
5770 /* package */ native int nativeTextFieldAction();
Leon Scroggins6679f2f2009-08-12 18:48:10 -04005771 /**
5772 * Perform a click on a currently focused text input. Since it is already
5773 * focused, there is no need to go through the nativeMotionUp code, which
5774 * may change the Cursor.
5775 */
5776 private native void nativeTextInputMotionUp(int x, int y);
Cary Clarkd6982c92009-05-29 11:02:22 -04005777 private native int nativeTextGeneration();
5778 // Never call this version except by updateCachedTextfield(String) -
5779 // we always want to pass in our generation number.
5780 private native void nativeUpdateCachedTextfield(String updatedText,
5781 int generation);
Cary Clark215b72c2009-06-26 14:38:43 -04005782 private native void nativeUpdatePluginReceivesEvents();
Grace Kloba8b97e4b2009-07-28 13:11:38 -07005783 // return NO_LEFTEDGE means failure.
5784 private static final int NO_LEFTEDGE = -1;
Cary Clark77d98f42009-07-31 09:40:38 -04005785 private native int nativeGetBlockLeftEdge(int x, int y, float scale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005786}