blob: a9fa879911865cb8b4a67bcea0f10fa2df1a0869 [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
Adam Powell637d3372010-08-25 14:37:03 -070019import com.android.internal.R;
20
Raphael30df2372010-03-06 10:09:54 -080021import android.annotation.Widget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.app.AlertDialog;
Derek Sollenberger41d5e932010-08-23 14:51:41 -040023import android.content.BroadcastReceiver;
Dianne Hackborn90d5e8c2010-08-05 13:47:55 -070024import android.content.ClipboardManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.content.Context;
26import android.content.DialogInterface;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.content.DialogInterface.OnCancelListener;
Adam Powell637d3372010-08-25 14:37:03 -070028import android.content.Intent;
29import android.content.IntentFilter;
Derek Sollenberger41d5e932010-08-23 14:51:41 -040030import android.content.pm.PackageInfo;
31import android.content.pm.PackageManager;
Cary Clarkc5cd5e92010-11-22 15:20:02 -050032import android.content.res.Configuration;
Adam Powell637d3372010-08-25 14:37:03 -070033import android.content.res.Resources;
Leon Scroggins3667ce42009-05-13 15:58:03 -040034import android.database.DataSetObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.graphics.Bitmap;
Adam Powell637d3372010-08-25 14:37:03 -070036import android.graphics.BitmapFactory;
37import android.graphics.BitmapShader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.graphics.Canvas;
39import android.graphics.Color;
Grace Kloba178db412010-05-18 22:22:23 -070040import android.graphics.CornerPathEffect;
Grace Kloba8abd50b2010-07-08 15:02:14 -070041import android.graphics.DrawFilter;
Grace Kloba178db412010-05-18 22:22:23 -070042import android.graphics.Paint;
Grace Kloba8abd50b2010-07-08 15:02:14 -070043import android.graphics.PaintFlagsDrawFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.graphics.Picture;
45import android.graphics.Point;
46import android.graphics.Rect;
Nicolas Roard46318cf2010-05-10 15:15:51 -070047import android.graphics.RectF;
Grace Kloba178db412010-05-18 22:22:23 -070048import android.graphics.Region;
Adam Powell637d3372010-08-25 14:37:03 -070049import android.graphics.Shader;
Mike Reede8853fc2009-09-04 14:01:48 -040050import android.graphics.drawable.Drawable;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.net.Uri;
Adam Powell9d32d242010-03-29 16:02:07 -070052import android.net.http.SslCertificate;
Derek Sollenberger41d5e932010-08-23 14:51:41 -040053import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.os.Bundle;
55import android.os.Handler;
56import android.os.Message;
Svetoslav Ganov585f13f8d2010-08-10 07:59:15 -070057import android.provider.Settings;
Svetoslav Ganovda355512010-05-12 22:04:44 -070058import android.speech.tts.TextToSpeech;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.text.Selection;
60import android.text.Spannable;
61import android.util.AttributeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.util.EventLog;
63import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.view.Gravity;
Jeff Brown6b53e8d2010-11-10 16:03:06 -080065import android.view.KeyCharacterMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.view.KeyEvent;
67import android.view.LayoutInflater;
68import android.view.MotionEvent;
Grace Kloba3a0def22010-01-23 21:11:54 -080069import android.view.ScaleGestureDetector;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.view.SoundEffectConstants;
71import android.view.VelocityTracker;
72import android.view.View;
73import android.view.ViewConfiguration;
74import android.view.ViewGroup;
Leon Scroggins7f7bd522010-11-05 11:23:31 -040075import android.view.ViewParent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.view.ViewTreeObserver;
Svetoslav Ganovda355512010-05-12 22:04:44 -070077import android.view.accessibility.AccessibilityManager;
Derek Sollenberger7cabb032010-01-21 10:37:38 -050078import android.view.inputmethod.EditorInfo;
79import android.view.inputmethod.InputConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import android.view.inputmethod.InputMethodManager;
Leon Scrogginsd3465f62009-06-02 10:57:54 -040081import android.webkit.WebTextView.AutoCompleteAdapter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.webkit.WebViewCore.EventHub;
Grace Klobac2242f22010-03-05 14:00:26 -080083import android.webkit.WebViewCore.TouchEventData;
Grace Kloba178db412010-05-18 22:22:23 -070084import android.webkit.WebViewCore.TouchHighlightData;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.widget.AbsoluteLayout;
Leon Scroggins3667ce42009-05-13 15:58:03 -040086import android.widget.Adapter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.widget.AdapterView;
Michael Kolb73980a92010-08-05 16:32:51 -070088import android.widget.AdapterView.OnItemClickListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.widget.ArrayAdapter;
Leon Scrogginsa8da1732009-10-19 19:04:30 -040090import android.widget.CheckedTextView;
Adam Powell637d3372010-08-25 14:37:03 -070091import android.widget.EdgeGlow;
Leon Scrogginsf1e1fb32009-10-21 13:39:33 -040092import android.widget.LinearLayout;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093import android.widget.ListView;
Adam Powell637d3372010-08-25 14:37:03 -070094import android.widget.OverScroller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import android.widget.Toast;
Michael Kolb73980a92010-08-05 16:32:51 -070096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097import java.io.File;
98import java.io.FileInputStream;
99import java.io.FileNotFoundException;
100import java.io.FileOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101import java.net.URLDecoder;
102import java.util.ArrayList;
Andrei Popescuf5dba882010-01-12 22:42:41 +0000103import java.util.HashMap;
Derek Sollenberger41d5e932010-08-23 14:51:41 -0400104import java.util.HashSet;
Adam Powell9d32d242010-03-29 16:02:07 -0700105import java.util.List;
Andrei Popescu4950b2b2009-09-03 13:56:07 +0100106import java.util.Map;
Andrei Popescua6d747d2010-02-11 13:19:21 +0000107import java.util.Set;
Svetoslav Ganov585f13f8d2010-08-10 07:59:15 -0700108import java.util.regex.Matcher;
109import java.util.regex.Pattern;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110
Adam Powell637d3372010-08-25 14:37:03 -0700111import junit.framework.Assert;
112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113/**
Cary Clarkd6982c92009-05-29 11:02:22 -0400114 * <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 -0800115 * can roll your own web browser or simply display some online content within your Activity.
116 * It uses the WebKit rendering engine to display
117 * web pages and includes methods to navigate forward and backward
118 * through a history, zoom in and out, perform text searches and more.</p>
The Android Open Source Project10592532009-03-18 17:39:46 -0700119 * <p>To enable the built-in zoom, set
120 * {@link #getSettings() WebSettings}.{@link WebSettings#setBuiltInZoomControls(boolean)}
121 * (introduced in API version 3).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 * <p>Note that, in order for your Activity to access the Internet and load web pages
Scott Main8b3cea02010-05-14 14:12:43 -0700123 * in a WebView, you must add the {@code INTERNET} permissions to your
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124 * Android Manifest file:</p>
125 * <pre>&lt;uses-permission android:name="android.permission.INTERNET" /></pre>
Mike Hearnadcd2ed2009-01-21 16:44:36 +0100126 *
Scott Main8b3cea02010-05-14 14:12:43 -0700127 * <p>This must be a child of the <a
Ben Dodson4e8620f2010-08-25 10:55:47 -0700128 * href="{@docRoot}guide/topics/manifest/manifest-element.html">{@code <manifest>}</a>
Scott Main8b3cea02010-05-14 14:12:43 -0700129 * element.</p>
Mike Hearnadcd2ed2009-01-21 16:44:36 +0100130 *
Scott Main41ec6532010-08-19 16:57:07 -0700131 * <p>See the <a href="{@docRoot}resources/tutorials/views/hello-webview.html">Web View
132 * tutorial</a>.</p>
133 *
Mike Hearnadcd2ed2009-01-21 16:44:36 +0100134 * <h3>Basic usage</h3>
135 *
136 * <p>By default, a WebView provides no browser-like widgets, does not
Scott Main8b3cea02010-05-14 14:12:43 -0700137 * enable JavaScript and web page errors are ignored. If your goal is only
Mike Hearnadcd2ed2009-01-21 16:44:36 +0100138 * to display some HTML as a part of your UI, this is probably fine;
139 * the user won't need to interact with the web page beyond reading
140 * it, and the web page won't need to interact with the user. If you
Scott Main8b3cea02010-05-14 14:12:43 -0700141 * actually want a full-blown web browser, then you probably want to
142 * invoke the Browser application with a URL Intent rather than show it
143 * with a WebView. For example:
144 * <pre>
145 * Uri uri = Uri.parse("http://www.example.com");
146 * Intent intent = new Intent(Intent.ACTION_VIEW, uri);
147 * startActivity(intent);
148 * </pre>
149 * <p>See {@link android.content.Intent} for more information.</p>
Mike Hearnadcd2ed2009-01-21 16:44:36 +0100150 *
Ben Dodson4e8620f2010-08-25 10:55:47 -0700151 * <p>To provide a WebView in your own Activity, include a {@code <WebView>} in your layout,
Scott Main8b3cea02010-05-14 14:12:43 -0700152 * or set the entire Activity window as a WebView during {@link
153 * android.app.Activity#onCreate(Bundle) onCreate()}:</p>
Mike Hearnadcd2ed2009-01-21 16:44:36 +0100154 * <pre class="prettyprint">
155 * WebView webview = new WebView(this);
156 * setContentView(webview);
Scott Main8b3cea02010-05-14 14:12:43 -0700157 * </pre>
Mike Hearnadcd2ed2009-01-21 16:44:36 +0100158 *
Scott Main8b3cea02010-05-14 14:12:43 -0700159 * <p>Then load the desired web page:</p>
Scott Maine3b9f8b2010-05-18 08:41:36 -0700160 * <pre>
Mike Hearnadcd2ed2009-01-21 16:44:36 +0100161 * // Simplest usage: note that an exception will NOT be thrown
162 * // if there is an error loading this page (see below).
163 * webview.loadUrl("http://slashdot.org/");
164 *
Scott Main8b3cea02010-05-14 14:12:43 -0700165 * // OR, you can also load from an HTML string:
Scott Maine3b9f8b2010-05-18 08:41:36 -0700166 * String summary = "&lt;html>&lt;body>You scored &lt;b>192&lt;/b> points.&lt;/body>&lt;/html>";
Mike Hearnadcd2ed2009-01-21 16:44:36 +0100167 * webview.loadData(summary, "text/html", "utf-8");
168 * // ... although note that there are restrictions on what this HTML can do.
Scott Main8b3cea02010-05-14 14:12:43 -0700169 * // See the JavaDocs for {@link #loadData(String,String,String) loadData()} and {@link
170 * #loadDataWithBaseURL(String,String,String,String,String) loadDataWithBaseURL()} for more info.
Mike Hearnadcd2ed2009-01-21 16:44:36 +0100171 * </pre>
172 *
173 * <p>A WebView has several customization points where you can add your
174 * own behavior. These are:</p>
175 *
176 * <ul>
177 * <li>Creating and setting a {@link android.webkit.WebChromeClient} subclass.
178 * This class is called when something that might impact a
179 * browser UI happens, for instance, progress updates and
Scott Main8b3cea02010-05-14 14:12:43 -0700180 * JavaScript alerts are sent here (see <a
181 * href="{@docRoot}guide/developing/debug-tasks.html#DebuggingWebPages">Debugging Tasks</a>).
Mike Hearnadcd2ed2009-01-21 16:44:36 +0100182 * </li>
183 * <li>Creating and setting a {@link android.webkit.WebViewClient} subclass.
184 * It will be called when things happen that impact the
185 * rendering of the content, eg, errors or form submissions. You
Scott Main8b3cea02010-05-14 14:12:43 -0700186 * can also intercept URL loading here (via {@link
187 * android.webkit.WebViewClient#shouldOverrideUrlLoading(WebView,String)
188 * shouldOverrideUrlLoading()}).</li>
189 * <li>Modifying the {@link android.webkit.WebSettings}, such as
190 * enabling JavaScript with {@link android.webkit.WebSettings#setJavaScriptEnabled(boolean)
191 * setJavaScriptEnabled()}. </li>
192 * <li>Adding JavaScript-to-Java interfaces with the {@link
193 * android.webkit.WebView#addJavascriptInterface} method.
Mike Hearnadcd2ed2009-01-21 16:44:36 +0100194 * This lets you bind Java objects into the WebView so they can be
195 * controlled from the web pages JavaScript.</li>
196 * </ul>
197 *
198 * <p>Here's a more complicated example, showing error handling,
199 * settings, and progress notification:</p>
200 *
201 * <pre class="prettyprint">
202 * // Let's display the progress in the activity title bar, like the
203 * // browser app does.
204 * getWindow().requestFeature(Window.FEATURE_PROGRESS);
205 *
206 * webview.getSettings().setJavaScriptEnabled(true);
207 *
208 * final Activity activity = this;
209 * webview.setWebChromeClient(new WebChromeClient() {
210 * public void onProgressChanged(WebView view, int progress) {
211 * // Activities and WebViews measure progress with different scales.
212 * // The progress meter will automatically disappear when we reach 100%
213 * activity.setProgress(progress * 1000);
214 * }
215 * });
216 * webview.setWebViewClient(new WebViewClient() {
217 * public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
218 * Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
219 * }
220 * });
221 *
222 * webview.loadUrl("http://slashdot.org/");
223 * </pre>
224 *
225 * <h3>Cookie and window management</h3>
226 *
227 * <p>For obvious security reasons, your application has its own
Scott Main8b3cea02010-05-14 14:12:43 -0700228 * cache, cookie store etc.&mdash;it does not share the Browser
229 * application's data. Cookies are managed on a separate thread, so
Mike Hearnadcd2ed2009-01-21 16:44:36 +0100230 * operations like index building don't block the UI
231 * thread. Follow the instructions in {@link android.webkit.CookieSyncManager}
232 * if you want to use cookies in your application.
233 * </p>
234 *
235 * <p>By default, requests by the HTML to open new windows are
236 * ignored. This is true whether they be opened by JavaScript or by
237 * the target attribute on a link. You can customize your
Scott Main8b3cea02010-05-14 14:12:43 -0700238 * {@link WebChromeClient} to provide your own behaviour for opening multiple windows,
Mike Hearnadcd2ed2009-01-21 16:44:36 +0100239 * and render them in whatever manner you want.</p>
240 *
Scott Main8b3cea02010-05-14 14:12:43 -0700241 * <p>The standard behavior for an Activity is to be destroyed and
242 * recreated when the device orientation or any other configuration changes. This will cause
Mike Hearnadcd2ed2009-01-21 16:44:36 +0100243 * the WebView to reload the current page. If you don't want that, you
Scott Main8b3cea02010-05-14 14:12:43 -0700244 * can set your Activity to handle the {@code orientation} and {@code keyboardHidden}
Mike Hearnadcd2ed2009-01-21 16:44:36 +0100245 * changes, and then just leave the WebView alone. It'll automatically
Scott Main8b3cea02010-05-14 14:12:43 -0700246 * re-orient itself as appropriate. Read <a
247 * href="{@docRoot}guide/topics/resources/runtime-changes.html">Handling Runtime Changes</a> for
248 * more information about how to handle configuration changes during runtime.</p>
249 *
250 *
251 * <h3>Building web pages to support different screen densities</h3>
252 *
253 * <p>The screen density of a device is based on the screen resolution. A screen with low density
254 * has fewer available pixels per inch, where a screen with high density
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700255 * has more &mdash; sometimes significantly more &mdash; pixels per inch. The density of a
Scott Main8b3cea02010-05-14 14:12:43 -0700256 * screen is important because, other things being equal, a UI element (such as a button) whose
257 * height and width are defined in terms of screen pixels will appear larger on the lower density
258 * screen and smaller on the higher density screen.
259 * For simplicity, Android collapses all actual screen densities into three generalized densities:
260 * high, medium, and low.</p>
261 * <p>By default, WebView scales a web page so that it is drawn at a size that matches the default
262 * appearance on a medium density screen. So, it applies 1.5x scaling on a high density screen
263 * (because its pixels are smaller) and 0.75x scaling on a low density screen (because its pixels
264 * are bigger).
265 * Starting with API Level 5 (Android 2.0), WebView supports DOM, CSS, and meta tag features to help
266 * you (as a web developer) target screens with different screen densities.</p>
267 * <p>Here's a summary of the features you can use to handle different screen densities:</p>
268 * <ul>
269 * <li>The {@code window.devicePixelRatio} DOM property. The value of this property specifies the
270 * default scaling factor used for the current device. For example, if the value of {@code
271 * window.devicePixelRatio} is "1.0", then the device is considered a medium density (mdpi) device
272 * and default scaling is not applied to the web page; if the value is "1.5", then the device is
273 * considered a high density device (hdpi) and the page content is scaled 1.5x; if the
274 * value is "0.75", then the device is considered a low density device (ldpi) and the content is
275 * scaled 0.75x. However, if you specify the {@code "target-densitydpi"} meta property
276 * (discussed below), then you can stop this default scaling behavior.</li>
277 * <li>The {@code -webkit-device-pixel-ratio} CSS media query. Use this to specify the screen
278 * densities for which this style sheet is to be used. The corresponding value should be either
279 * "0.75", "1", or "1.5", to indicate that the styles are for devices with low density, medium
280 * density, or high density screens, respectively. For example:
281 * <pre>
282 * &lt;link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio:1.5)" href="hdpi.css" /&gt;</pre>
283 * <p>The {@code hdpi.css} stylesheet is only used for devices with a screen pixel ration of 1.5,
284 * which is the high density pixel ratio.</p>
285 * </li>
286 * <li>The {@code target-densitydpi} property for the {@code viewport} meta tag. You can use
287 * this to specify the target density for which the web page is designed, using the following
288 * values:
289 * <ul>
290 * <li>{@code device-dpi} - Use the device's native dpi as the target dpi. Default scaling never
291 * occurs.</li>
292 * <li>{@code high-dpi} - Use hdpi as the target dpi. Medium and low density screens scale down
293 * as appropriate.</li>
294 * <li>{@code medium-dpi} - Use mdpi as the target dpi. High density screens scale up and
295 * low density screens scale down. This is also the default behavior.</li>
296 * <li>{@code low-dpi} - Use ldpi as the target dpi. Medium and high density screens scale up
297 * as appropriate.</li>
Ben Dodson4e8620f2010-08-25 10:55:47 -0700298 * <li><em>{@code <value>}</em> - Specify a dpi value to use as the target dpi (accepted
Scott Main8b3cea02010-05-14 14:12:43 -0700299 * values are 70-400).</li>
300 * </ul>
301 * <p>Here's an example meta tag to specify the target density:</p>
302 * <pre>&lt;meta name="viewport" content="target-densitydpi=device-dpi" /&gt;</pre></li>
303 * </ul>
304 * <p>If you want to modify your web page for different densities, by using the {@code
305 * -webkit-device-pixel-ratio} CSS media query and/or the {@code
306 * window.devicePixelRatio} DOM property, then you should set the {@code target-densitydpi} meta
307 * property to {@code device-dpi}. This stops Android from performing scaling in your web page and
308 * allows you to make the necessary adjustments for each density via CSS and JavaScript.</p>
309 *
Michael Kolb73980a92010-08-05 16:32:51 -0700310 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 */
Raphael30df2372010-03-06 10:09:54 -0800312@Widget
Cary Clarkd6982c92009-05-29 11:02:22 -0400313public class WebView extends AbsoluteLayout
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800314 implements ViewTreeObserver.OnGlobalFocusChangeListener,
315 ViewGroup.OnHierarchyChangeListener {
316
Teng-Hui Zhua7f76872010-11-29 11:15:32 -0800317 private class InnerGlobalLayoutListener implements ViewTreeObserver.OnGlobalLayoutListener {
318 public void onGlobalLayout() {
319 if (isShown()) {
320 setGLRectViewport();
321 }
322 }
323 }
324
325 // The listener to capture global layout change event.
326 private InnerGlobalLayoutListener mListener = null;
327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800328 // if AUTO_REDRAW_HACK is true, then the CALL key will toggle redrawing
329 // the screen all-the-time. Good for profiling our drawing code
330 static private final boolean AUTO_REDRAW_HACK = false;
331 // true means redraw the screen all-the-time. Only with AUTO_REDRAW_HACK
332 private boolean mAutoRedraw;
333
Mattias Falk0ae2ec82010-09-16 16:24:46 +0200334 // Reference to the AlertDialog displayed by InvokeListBox.
335 // It's used to dismiss the dialog in destroy if not done before.
336 private AlertDialog mListBoxDialog = null;
337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800338 static final String LOGTAG = "webview";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800339
Derek Sollenberger90b6e482010-05-10 12:38:54 -0400340 private ZoomManager mZoomManager;
Cary Clarkd6982c92009-05-29 11:02:22 -0400341
Nicolas Roard12c18e62010-10-13 20:14:31 -0700342 private Rect mGLRectViewport;
343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800344 /**
345 * Transportation object for returning WebView across thread boundaries.
346 */
347 public class WebViewTransport {
348 private WebView mWebview;
349
350 /**
351 * Set the WebView to the transportation object.
352 * @param webview The WebView to transport.
353 */
354 public synchronized void setWebView(WebView webview) {
355 mWebview = webview;
356 }
357
358 /**
359 * Return the WebView object.
360 * @return WebView The transported WebView object.
361 */
362 public synchronized WebView getWebView() {
363 return mWebview;
364 }
365 }
366
367 // A final CallbackProxy shared by WebViewCore and BrowserFrame.
368 private final CallbackProxy mCallbackProxy;
369
370 private final WebViewDatabase mDatabase;
371
372 // SSL certificate for the main top-level page (if secure)
373 private SslCertificate mCertificate;
374
375 // Native WebView pointer that is 0 until the native object has been
376 // created.
377 private int mNativeClass;
378 // This would be final but it needs to be set to null when the WebView is
379 // destroyed.
380 private WebViewCore mWebViewCore;
381 // Handler for dispatching UI messages.
382 /* package */ final Handler mPrivateHandler = new PrivateHandler();
Leon Scrogginsd3465f62009-06-02 10:57:54 -0400383 private WebTextView mWebTextView;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800384 // Used to ignore changes to webkit text that arrives to the UI side after
385 // more key events.
386 private int mTextGeneration;
387
Leon Scroggins IIIb24e18b2010-04-20 17:07:28 -0400388 /* package */ void incrementTextGeneration() { mTextGeneration++; }
389
Patrick Scott0a5ce012009-07-02 08:56:10 -0400390 // Used by WebViewCore to create child views.
391 /* package */ final ViewManager mViewManager;
392
Grace Kloba11438c32009-12-16 11:39:12 -0800393 // Used to display in full screen mode
394 PluginFullScreenHolder mFullScreenHolder;
395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800396 /**
397 * Position of the last touch event.
398 */
399 private float mLastTouchX;
400 private float mLastTouchY;
401
402 /**
403 * Time of the last touch event.
404 */
405 private long mLastTouchTime;
406
407 /**
408 * Time of the last time sending touch event to WebViewCore
409 */
410 private long mLastSentTouchTime;
411
412 /**
413 * The minimum elapsed time before sending another ACTION_MOVE event to
Grace Kloba53d3c1e2009-06-26 11:36:03 -0700414 * WebViewCore. This really should be tuned for each type of the devices.
415 * For example in Google Map api test case, it takes Dream device at least
416 * 150ms to do a full cycle in the WebViewCore by processing a touch event,
417 * triggering the layout and drawing the picture. While the same process
418 * takes 60+ms on the current high speed device. If we make
419 * TOUCH_SENT_INTERVAL too small, there will be multiple touch events sent
420 * to WebViewCore queue and the real layout and draw events will be pushed
421 * to further, which slows down the refresh rate. Choose 50 to favor the
422 * current high speed devices. For Dream like devices, 100 is a better
423 * choice. Maybe make this in the buildspec later.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424 */
Grace Kloba53d3c1e2009-06-26 11:36:03 -0700425 private static final int TOUCH_SENT_INTERVAL = 50;
Ben Murdochecbc65c2010-01-13 10:54:56 +0000426 private int mCurrentTouchInterval = TOUCH_SENT_INTERVAL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800427
428 /**
429 * Helper class to get velocity for fling
430 */
431 VelocityTracker mVelocityTracker;
Romain Guy4296fc42009-07-06 11:48:52 -0700432 private int mMaximumFling;
Cary Clark278ce052009-08-31 16:08:42 -0400433 private float mLastVelocity;
434 private float mLastVelX;
435 private float mLastVelY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436
Patrick Scotta3ebcc92010-07-16 11:52:22 -0400437 // A pointer to the native scrollable layer when dragging layers. Only
438 // valid when mTouchMode is TOUCH_DRAG_LAYER_MODE.
439 private int mScrollingLayer;
440
Grace Kloba3c19d992010-05-17 19:19:06 -0700441 // only trigger accelerated fling if the new velocity is at least
442 // MINIMUM_VELOCITY_RATIO_FOR_ACCELERATION times of the previous velocity
443 private static final float MINIMUM_VELOCITY_RATIO_FOR_ACCELERATION = 0.2f;
444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800445 /**
446 * Touch mode
447 */
448 private int mTouchMode = TOUCH_DONE_MODE;
449 private static final int TOUCH_INIT_MODE = 1;
450 private static final int TOUCH_DRAG_START_MODE = 2;
451 private static final int TOUCH_DRAG_MODE = 3;
452 private static final int TOUCH_SHORTPRESS_START_MODE = 4;
453 private static final int TOUCH_SHORTPRESS_MODE = 5;
Grace Kloba04b28682009-09-14 14:38:37 -0700454 private static final int TOUCH_DOUBLE_TAP_MODE = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455 private static final int TOUCH_DONE_MODE = 7;
Cary Clark924af702010-06-04 16:37:43 -0400456 private static final int TOUCH_PINCH_DRAG = 8;
Patrick Scotta3ebcc92010-07-16 11:52:22 -0400457 private static final int TOUCH_DRAG_LAYER_MODE = 9;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800458
459 // Whether to forward the touch events to WebCore
460 private boolean mForwardTouchEvents = false;
461
Grace Klobac2242f22010-03-05 14:00:26 -0800462 // Whether to prevent default during touch. The initial value depends on
463 // mForwardTouchEvents. If WebCore wants all the touch events, it says yes
464 // for touch down. Otherwise UI will wait for the answer of the first
465 // confirmed move before taking over the control.
466 private static final int PREVENT_DEFAULT_NO = 0;
467 private static final int PREVENT_DEFAULT_MAYBE_YES = 1;
468 private static final int PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN = 2;
469 private static final int PREVENT_DEFAULT_YES = 3;
470 private static final int PREVENT_DEFAULT_IGNORE = 4;
471 private int mPreventDefault = PREVENT_DEFAULT_IGNORE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800472
Grace Klobac2242f22010-03-05 14:00:26 -0800473 // true when the touch movement exceeds the slop
474 private boolean mConfirmMove;
Grace Kloba5f68d6f2009-12-08 18:42:54 -0800475
Grace Klobac2242f22010-03-05 14:00:26 -0800476 // if true, touch events will be first processed by WebCore, if prevent
477 // default is not set, the UI will continue handle them.
478 private boolean mDeferTouchProcess;
479
Huahui Wu41865f42010-09-02 13:41:41 -0700480 // if true, multi-touch events will be passed to webkit directly before UI
481 private boolean mDeferMultitouch = false;
482
Grace Klobac2242f22010-03-05 14:00:26 -0800483 // to avoid interfering with the current touch events, track them
484 // separately. Currently no snapping or fling in the deferred process mode
485 private int mDeferTouchMode = TOUCH_DONE_MODE;
486 private float mLastDeferTouchX;
487 private float mLastDeferTouchY;
Grace Kloba5f68d6f2009-12-08 18:42:54 -0800488
Leon Scroggins72543e12009-07-23 15:29:45 -0400489 // To keep track of whether the current drag was initiated by a WebTextView,
490 // so that we know not to hide the cursor
491 boolean mDragFromTextInput;
492
Cary Clarkd6982c92009-05-29 11:02:22 -0400493 // Whether or not to draw the cursor ring.
494 private boolean mDrawCursorRing = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800495
Mike Reedd205d5b2009-05-27 11:02:29 -0400496 // true if onPause has been called (and not onResume)
497 private boolean mIsPaused;
498
Cary Clarkb8491342010-11-29 16:23:19 -0500499 private HitTestResult mInitialHitTestResult;
500
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800501 /**
502 * Customizable constant
503 */
504 // pre-computed square of ViewConfiguration.getScaledTouchSlop()
505 private int mTouchSlopSquare;
Grace Kloba8b97e4b2009-07-28 13:11:38 -0700506 // pre-computed square of ViewConfiguration.getScaledDoubleTapSlop()
507 private int mDoubleTapSlopSquare;
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700508 // pre-computed density adjusted navigation slop
509 private int mNavSlop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800510 // This should be ViewConfiguration.getTapTimeout()
511 // But system time out is 100ms, which is too short for the browser.
512 // In the browser, if it switches out of tap too soon, jump tap won't work.
513 private static final int TAP_TIMEOUT = 200;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800514 // This should be ViewConfiguration.getLongPressTimeout()
515 // But system time out is 500ms, which is too short for the browser.
516 // With a short timeout, it's difficult to treat trigger a short press.
517 private static final int LONG_PRESS_TIMEOUT = 1000;
518 // needed to avoid flinging after a pause of no movement
519 private static final int MIN_FLING_TIME = 250;
Cary Clark25415e22009-10-12 13:41:28 -0400520 // draw unfiltered after drag is held without movement
521 private static final int MOTIONLESS_TIME = 100;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522 // The amount of content to overlap between two screens when going through
523 // pages with the space bar, in pixels.
524 private static final int PAGE_SCROLL_OVERLAP = 24;
525
526 /**
527 * These prevent calling requestLayout if either dimension is fixed. This
528 * depends on the layout parameters and the measure specs.
529 */
530 boolean mWidthCanMeasure;
531 boolean mHeightCanMeasure;
532
533 // Remember the last dimensions we sent to the native side so we can avoid
534 // sending the same dimensions more than once.
535 int mLastWidthSent;
536 int mLastHeightSent;
537
538 private int mContentWidth; // cache of value from WebViewCore
539 private int mContentHeight; // cache of value from WebViewCore
540
Cary Clarkd6982c92009-05-29 11:02:22 -0400541 // Need to have the separate control for horizontal and vertical scrollbar
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800542 // style than the View's single scrollbar style
543 private boolean mOverlayHorizontalScrollbar = true;
544 private boolean mOverlayVerticalScrollbar = false;
545
546 // our standard speed. this way small distances will be traversed in less
547 // time than large distances, but we cap the duration, so that very large
548 // distances won't take too long to get there.
549 private static final int STD_SPEED = 480; // pixels per second
550 // time for the longest scroll animation
551 private static final int MAX_DURATION = 750; // milliseconds
Leon Scroggins03c87bf2009-09-18 15:05:59 -0400552 private static final int SLIDE_TITLE_DURATION = 500; // milliseconds
Adam Powell637d3372010-08-25 14:37:03 -0700553
554 // Used by OverScrollGlow
555 OverScroller mScroller;
556
557 private boolean mInOverScrollMode = false;
558 private static Paint mOverScrollBackground;
559 private static Paint mOverScrollBorder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560
561 private boolean mWrapContent;
Cary Clark25415e22009-10-12 13:41:28 -0400562 private static final int MOTIONLESS_FALSE = 0;
563 private static final int MOTIONLESS_PENDING = 1;
564 private static final int MOTIONLESS_TRUE = 2;
Grace Kloba9b657802010-04-08 13:46:23 -0700565 private static final int MOTIONLESS_IGNORE = 3;
Cary Clark25415e22009-10-12 13:41:28 -0400566 private int mHeldMotionless;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800567
Svetoslav Ganovda355512010-05-12 22:04:44 -0700568 // An instance for injecting accessibility in WebViews with disabled
569 // JavaScript or ones for which no accessibility script exists
570 private AccessibilityInjector mAccessibilityInjector;
571
Svetoslav Ganov585f13f8d2010-08-10 07:59:15 -0700572 // flag indicating if accessibility script is injected so we
573 // know to handle Shift and arrows natively first
574 private boolean mAccessibilityScriptInjected;
575
Grace Kloba178db412010-05-18 22:22:23 -0700576 // the color used to highlight the touch rectangles
577 private static final int mHightlightColor = 0x33000000;
578 // the round corner for the highlight path
579 private static final float TOUCH_HIGHLIGHT_ARC = 5.0f;
580 // the region indicating where the user touched on the screen
581 private Region mTouchHighlightRegion = new Region();
582 // the paint for the touch highlight
583 private Paint mTouchHightlightPaint;
584 // debug only
585 private static final boolean DEBUG_TOUCH_HIGHLIGHT = true;
586 private static final int TOUCH_HIGHLIGHT_ELAPSE_TIME = 2000;
587 private Paint mTouchCrossHairColor;
588 private int mTouchHighlightX;
589 private int mTouchHighlightY;
590
Grace Klobac2242f22010-03-05 14:00:26 -0800591 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592 * Private message ids
593 */
Leon Scrogginsd3465f62009-06-02 10:57:54 -0400594 private static final int REMEMBER_PASSWORD = 1;
595 private static final int NEVER_REMEMBER_PASSWORD = 2;
596 private static final int SWITCH_TO_SHORTPRESS = 3;
597 private static final int SWITCH_TO_LONGPRESS = 4;
Grace Kloba8b97e4b2009-07-28 13:11:38 -0700598 private static final int RELEASE_SINGLE_TAP = 5;
Leon Scrogginsd3465f62009-06-02 10:57:54 -0400599 private static final int REQUEST_FORM_DATA = 6;
Grace Kloba96949ef2010-01-25 09:53:01 -0800600 private static final int RESUME_WEBCORE_PRIORITY = 7;
Cary Clark25415e22009-10-12 13:41:28 -0400601 private static final int DRAG_HELD_MOTIONLESS = 8;
602 private static final int AWAKEN_SCROLL_BARS = 9;
Grace Klobac2242f22010-03-05 14:00:26 -0800603 private static final int PREVENT_DEFAULT_TIMEOUT = 10;
Cary Clark6f5dfc62010-11-11 13:09:20 -0500604 private static final int SCROLL_SELECT_TEXT = 11;
605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606
Grace Klobac2242f22010-03-05 14:00:26 -0800607 private static final int FIRST_PRIVATE_MSG_ID = REMEMBER_PASSWORD;
Cary Clark6f5dfc62010-11-11 13:09:20 -0500608 private static final int LAST_PRIVATE_MSG_ID = SCROLL_SELECT_TEXT;
Grace Klobac2242f22010-03-05 14:00:26 -0800609
610 /*
611 * Package message ids
612 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 //! arg1=x, arg2=y
Grace Klobac2242f22010-03-05 14:00:26 -0800614 static final int SCROLL_TO_MSG_ID = 101;
615 static final int SCROLL_BY_MSG_ID = 102;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800616 //! arg1=x, arg2=y
Grace Klobac2242f22010-03-05 14:00:26 -0800617 static final int SPAWN_SCROLL_TO_MSG_ID = 103;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 //! arg1=x, arg2=y
Grace Klobac2242f22010-03-05 14:00:26 -0800619 static final int SYNC_SCROLL_TO_MSG_ID = 104;
620 static final int NEW_PICTURE_MSG_ID = 105;
621 static final int UPDATE_TEXT_ENTRY_MSG_ID = 106;
622 static final int WEBCORE_INITIALIZED_MSG_ID = 107;
623 static final int UPDATE_TEXTFIELD_TEXT_MSG_ID = 108;
624 static final int UPDATE_ZOOM_RANGE = 109;
Leon Scroggins9ab32b62010-05-03 14:19:50 +0100625 static final int UNHANDLED_NAV_KEY = 110;
Grace Klobac2242f22010-03-05 14:00:26 -0800626 static final int CLEAR_TEXT_ENTRY = 111;
627 static final int UPDATE_TEXT_SELECTION_MSG_ID = 112;
628 static final int SHOW_RECT_MSG_ID = 113;
629 static final int LONG_PRESS_CENTER = 114;
630 static final int PREVENT_TOUCH_ID = 115;
631 static final int WEBCORE_NEED_TOUCH_EVENTS = 116;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 // obj=Rect in doc coordinates
Grace Klobac2242f22010-03-05 14:00:26 -0800633 static final int INVAL_RECT_MSG_ID = 117;
634 static final int REQUEST_KEYBOARD = 118;
635 static final int DO_MOTION_UP = 119;
636 static final int SHOW_FULLSCREEN = 120;
637 static final int HIDE_FULLSCREEN = 121;
638 static final int DOM_FOCUS_CHANGED = 122;
Grace Kloba8abd50b2010-07-08 15:02:14 -0700639 static final int REPLACE_BASE_CONTENT = 123;
Leon Scrogginsf2e17a82010-09-24 15:58:50 -0400640 static final int FORM_DID_BLUR = 124;
Grace Klobac2242f22010-03-05 14:00:26 -0800641 static final int RETURN_LABEL = 125;
642 static final int FIND_AGAIN = 126;
Grace Klobae8300a12010-03-12 13:32:55 -0800643 static final int CENTER_FIT_RECT = 127;
Leon Scrogginsb4157792010-03-18 12:42:33 -0400644 static final int REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID = 128;
Grace Kloba50004bc2010-04-13 22:58:51 -0700645 static final int SET_SCROLLBAR_MODES = 129;
Svetoslav Ganovda355512010-05-12 22:04:44 -0700646 static final int SELECTION_STRING_CHANGED = 130;
Grace Kloba178db412010-05-18 22:22:23 -0700647 static final int SET_TOUCH_HIGHLIGHT_RECTS = 131;
Elliott Slaughterb48fdbe2010-06-30 11:39:52 -0700648 static final int SAVE_WEBARCHIVE_FINISHED = 132;
Cary Clarkd6982c92009-05-29 11:02:22 -0400649
Ben Murdoch62275a42010-09-07 11:27:28 +0100650 static final int SET_AUTOFILLABLE = 133;
651
Grace Klobac2242f22010-03-05 14:00:26 -0800652 private static final int FIRST_PACKAGE_MSG_ID = SCROLL_TO_MSG_ID;
Grace Kloba178db412010-05-18 22:22:23 -0700653 private static final int LAST_PACKAGE_MSG_ID = SET_TOUCH_HIGHLIGHT_RECTS;
Grace Klobac2242f22010-03-05 14:00:26 -0800654
655 static final String[] HandlerPrivateDebugString = {
Leon Scrogginsd3465f62009-06-02 10:57:54 -0400656 "REMEMBER_PASSWORD", // = 1;
657 "NEVER_REMEMBER_PASSWORD", // = 2;
658 "SWITCH_TO_SHORTPRESS", // = 3;
659 "SWITCH_TO_LONGPRESS", // = 4;
Grace Kloba8b97e4b2009-07-28 13:11:38 -0700660 "RELEASE_SINGLE_TAP", // = 5;
Leon Scrogginsd3465f62009-06-02 10:57:54 -0400661 "REQUEST_FORM_DATA", // = 6;
Grace Kloba96949ef2010-01-25 09:53:01 -0800662 "RESUME_WEBCORE_PRIORITY", // = 7;
Cary Clark25415e22009-10-12 13:41:28 -0400663 "DRAG_HELD_MOTIONLESS", // = 8;
664 "AWAKEN_SCROLL_BARS", // = 9;
Cary Clark6f5dfc62010-11-11 13:09:20 -0500665 "PREVENT_DEFAULT_TIMEOUT", // = 10;
666 "SCROLL_SELECT_TEXT" // = 11;
Grace Klobac2242f22010-03-05 14:00:26 -0800667 };
668
669 static final String[] HandlerPackageDebugString = {
670 "SCROLL_TO_MSG_ID", // = 101;
671 "SCROLL_BY_MSG_ID", // = 102;
672 "SPAWN_SCROLL_TO_MSG_ID", // = 103;
673 "SYNC_SCROLL_TO_MSG_ID", // = 104;
674 "NEW_PICTURE_MSG_ID", // = 105;
675 "UPDATE_TEXT_ENTRY_MSG_ID", // = 106;
676 "WEBCORE_INITIALIZED_MSG_ID", // = 107;
677 "UPDATE_TEXTFIELD_TEXT_MSG_ID", // = 108;
678 "UPDATE_ZOOM_RANGE", // = 109;
Leon Scroggins9ab32b62010-05-03 14:19:50 +0100679 "UNHANDLED_NAV_KEY", // = 110;
Grace Klobac2242f22010-03-05 14:00:26 -0800680 "CLEAR_TEXT_ENTRY", // = 111;
681 "UPDATE_TEXT_SELECTION_MSG_ID", // = 112;
682 "SHOW_RECT_MSG_ID", // = 113;
683 "LONG_PRESS_CENTER", // = 114;
684 "PREVENT_TOUCH_ID", // = 115;
685 "WEBCORE_NEED_TOUCH_EVENTS", // = 116;
686 "INVAL_RECT_MSG_ID", // = 117;
687 "REQUEST_KEYBOARD", // = 118;
688 "DO_MOTION_UP", // = 119;
689 "SHOW_FULLSCREEN", // = 120;
690 "HIDE_FULLSCREEN", // = 121;
691 "DOM_FOCUS_CHANGED", // = 122;
Grace Kloba8abd50b2010-07-08 15:02:14 -0700692 "REPLACE_BASE_CONTENT", // = 123;
Leon Scrogginsf2e17a82010-09-24 15:58:50 -0400693 "FORM_DID_BLUR", // = 124;
Grace Klobac2242f22010-03-05 14:00:26 -0800694 "RETURN_LABEL", // = 125;
Grace Klobae8300a12010-03-12 13:32:55 -0800695 "FIND_AGAIN", // = 126;
Leon Scrogginsb4157792010-03-18 12:42:33 -0400696 "CENTER_FIT_RECT", // = 127;
Grace Kloba50004bc2010-04-13 22:58:51 -0700697 "REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID", // = 128;
Grace Kloba178db412010-05-18 22:22:23 -0700698 "SET_SCROLLBAR_MODES", // = 129;
699 "SELECTION_STRING_CHANGED", // = 130;
Elliott Slaughterb48fdbe2010-06-30 11:39:52 -0700700 "SET_TOUCH_HIGHLIGHT_RECTS", // = 131;
Ben Murdoch62275a42010-09-07 11:27:28 +0100701 "SAVE_WEBARCHIVE_FINISHED", // = 132;
702 "SET_AUTOFILLABLE" // = 133;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 };
704
Grace Klobaa4fa1072009-11-09 12:01:50 -0800705 // If the site doesn't use the viewport meta tag to specify the viewport,
706 // use DEFAULT_VIEWPORT_WIDTH as the default viewport width
Shimeng (Simon) Wang14bcc0e2010-09-17 10:12:05 -0700707 static final int DEFAULT_VIEWPORT_WIDTH = 980;
Grace Klobaa4fa1072009-11-09 12:01:50 -0800708
709 // normally we try to fit the content to the minimum preferred width
710 // calculated by the Webkit. To avoid the bad behavior when some site's
711 // minimum preferred width keeps growing when changing the viewport width or
712 // the minimum preferred width is huge, an upper limit is needed.
713 static int sMaxViewportWidth = DEFAULT_VIEWPORT_WIDTH;
714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 // initial scale in percent. 0 means using default.
Grace Kloba16efce72009-11-10 15:49:03 -0800716 private int mInitialScaleInPercent = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 private boolean mUserScroll = false;
719
720 private int mSnapScrollMode = SNAP_NONE;
Cary Clarkac492e12009-10-14 14:53:37 -0400721 private static final int SNAP_NONE = 0;
722 private static final int SNAP_LOCK = 1; // not a separate state
723 private static final int SNAP_X = 2; // may be combined with SNAP_LOCK
724 private static final int SNAP_Y = 4; // may be combined with SNAP_LOCK
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 private boolean mSnapPositive;
Cary Clarkd6982c92009-05-29 11:02:22 -0400726
Cary Clark2ec30692010-02-23 10:50:38 -0500727 // keep these in sync with their counterparts in WebView.cpp
728 private static final int DRAW_EXTRAS_NONE = 0;
729 private static final int DRAW_EXTRAS_FIND = 1;
730 private static final int DRAW_EXTRAS_SELECTION = 2;
731 private static final int DRAW_EXTRAS_CURSOR_RING = 3;
732
Grace Kloba50004bc2010-04-13 22:58:51 -0700733 // keep this in sync with WebCore:ScrollbarMode in WebKit
734 private static final int SCROLLBAR_AUTO = 0;
735 private static final int SCROLLBAR_ALWAYSOFF = 1;
736 // as we auto fade scrollbar, this is ignored.
737 private static final int SCROLLBAR_ALWAYSON = 2;
738 private int mHorizontalScrollBarMode = SCROLLBAR_AUTO;
739 private int mVerticalScrollBarMode = SCROLLBAR_AUTO;
740
Svetoslav Ganov585f13f8d2010-08-10 07:59:15 -0700741 // constants for determining script injection strategy
742 private static final int ACCESSIBILITY_SCRIPT_INJECTION_UNDEFINED = -1;
743 private static final int ACCESSIBILITY_SCRIPT_INJECTION_OPTED_OUT = 0;
744 private static final int ACCESSIBILITY_SCRIPT_INJECTION_PROVIDED = 1;
745
Svetoslav Ganovda355512010-05-12 22:04:44 -0700746 // the alias via which accessibility JavaScript interface is exposed
747 private static final String ALIAS_ACCESSIBILITY_JS_INTERFACE = "accessibility";
748
749 // JavaScript to inject the script chooser which will
750 // pick the right script for the current URL
751 private static final String ACCESSIBILITY_SCRIPT_CHOOSER_JAVASCRIPT =
752 "javascript:(function() {" +
753 " var chooser = document.createElement('script');" +
754 " chooser.type = 'text/javascript';" +
755 " chooser.src = 'https://ssl.gstatic.com/accessibility/javascript/android/AndroidScriptChooser.user.js';" +
756 " document.getElementsByTagName('head')[0].appendChild(chooser);" +
757 " })();";
758
Svetoslav Ganov585f13f8d2010-08-10 07:59:15 -0700759 // Regular expression that matches the "axs" URL parameter.
760 // The value of 0 means the accessibility script is opted out
761 // The value of 1 means the accessibility script is already injected
762 private static final String PATTERN_MATCH_AXS_URL_PARAMETER = "(\\?axs=(0|1))|(&axs=(0|1))";
763
764 // variable to cache the above pattern in case accessibility is enabled.
765 private Pattern mMatchAxsUrlParameterPattern;
766
Adam Powell637d3372010-08-25 14:37:03 -0700767 /**
768 * Max distance to overscroll by in pixels.
769 * This how far content can be pulled beyond its normal bounds by the user.
770 */
771 private int mOverscrollDistance;
772
773 /**
774 * Max distance to overfling by in pixels.
775 * This is how far flinged content can move beyond the end of its normal bounds.
776 */
777 private int mOverflingDistance;
778
779 private OverScrollGlow mOverScrollGlow;
780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 // Used to match key downs and key ups
782 private boolean mGotKeyDown;
783
784 /* package */ static boolean mLogEvent = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785
786 // for event log
787 private long mLastTouchUpTime = 0;
788
Ben Murdochdb8d19c2010-10-29 11:44:17 +0100789 private WebViewCore.AutoFillData mAutoFillData;
Ben Murdoch62275a42010-09-07 11:27:28 +0100790
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 /**
792 * URI scheme for telephone number
793 */
794 public static final String SCHEME_TEL = "tel:";
795 /**
796 * URI scheme for email address
797 */
798 public static final String SCHEME_MAILTO = "mailto:";
799 /**
800 * URI scheme for map address
801 */
802 public static final String SCHEME_GEO = "geo:0,0?q=";
Cary Clarkd6982c92009-05-29 11:02:22 -0400803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800804 private int mBackgroundColor = Color.WHITE;
805
Cary Clark6f5dfc62010-11-11 13:09:20 -0500806 private static final long SELECT_SCROLL_INTERVAL = 1000 / 60; // 60 / second
807 private int mAutoScrollX = 0;
808 private int mAutoScrollY = 0;
809 private boolean mSentAutoScrollMessage = false;
810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 // Used to notify listeners of a new picture.
812 private PictureListener mPictureListener;
813 /**
814 * Interface to listen for new pictures as they change.
815 */
816 public interface PictureListener {
817 /**
818 * Notify the listener that the picture has changed.
819 * @param view The WebView that owns the picture.
820 * @param picture The new picture.
821 */
822 public void onNewPicture(WebView view, Picture picture);
823 }
824
Leon Scroggins3246c222009-05-26 09:51:23 -0400825 // FIXME: Want to make this public, but need to change the API file.
826 public /*static*/ class HitTestResult {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 /**
828 * Default HitTestResult, where the target is unknown
829 */
830 public static final int UNKNOWN_TYPE = 0;
831 /**
832 * HitTestResult for hitting a HTML::a tag
833 */
834 public static final int ANCHOR_TYPE = 1;
835 /**
836 * HitTestResult for hitting a phone number
837 */
838 public static final int PHONE_TYPE = 2;
839 /**
840 * HitTestResult for hitting a map address
841 */
842 public static final int GEO_TYPE = 3;
843 /**
844 * HitTestResult for hitting an email address
845 */
846 public static final int EMAIL_TYPE = 4;
847 /**
848 * HitTestResult for hitting an HTML::img tag
849 */
850 public static final int IMAGE_TYPE = 5;
851 /**
852 * HitTestResult for hitting a HTML::a tag which contains HTML::img
853 */
854 public static final int IMAGE_ANCHOR_TYPE = 6;
855 /**
856 * HitTestResult for hitting a HTML::a tag with src=http
857 */
858 public static final int SRC_ANCHOR_TYPE = 7;
859 /**
860 * HitTestResult for hitting a HTML::a tag with src=http + HTML::img
861 */
862 public static final int SRC_IMAGE_ANCHOR_TYPE = 8;
863 /**
864 * HitTestResult for hitting an edit text area
865 */
866 public static final int EDIT_TEXT_TYPE = 9;
867
868 private int mType;
869 private String mExtra;
870
871 HitTestResult() {
872 mType = UNKNOWN_TYPE;
873 }
874
875 private void setType(int type) {
876 mType = type;
877 }
878
879 private void setExtra(String extra) {
880 mExtra = extra;
881 }
882
883 public int getType() {
884 return mType;
885 }
886
887 public String getExtra() {
888 return mExtra;
889 }
890 }
891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 /**
893 * Construct a new WebView with a Context object.
894 * @param context A Context object used to access application assets.
895 */
896 public WebView(Context context) {
897 this(context, null);
898 }
899
900 /**
901 * Construct a new WebView with layout parameters.
902 * @param context A Context object used to access application assets.
903 * @param attrs An AttributeSet passed to our parent.
904 */
905 public WebView(Context context, AttributeSet attrs) {
906 this(context, attrs, com.android.internal.R.attr.webViewStyle);
907 }
908
909 /**
910 * Construct a new WebView with layout parameters and a default style.
911 * @param context A Context object used to access application assets.
912 * @param attrs An AttributeSet passed to our parent.
913 * @param defStyle The default style resource ID.
914 */
915 public WebView(Context context, AttributeSet attrs, int defStyle) {
Elliott Slaughterf21d2e32010-07-14 18:08:54 -0700916 this(context, attrs, defStyle, false);
917 }
918
919 /**
920 * Construct a new WebView with layout parameters and a default style.
921 * @param context A Context object used to access application assets.
922 * @param attrs An AttributeSet passed to our parent.
923 * @param defStyle The default style resource ID.
924 */
925 public WebView(Context context, AttributeSet attrs, int defStyle,
926 boolean privateBrowsing) {
927 this(context, attrs, defStyle, null, privateBrowsing);
Andrei Popescu4950b2b2009-09-03 13:56:07 +0100928 }
929
930 /**
931 * Construct a new WebView with layout parameters, a default style and a set
932 * of custom Javscript interfaces to be added to the WebView at initialization
Romain Guy01d0fbf2009-12-01 14:52:19 -0800933 * time. This guarantees that these interfaces will be available when the JS
Andrei Popescu4950b2b2009-09-03 13:56:07 +0100934 * context is initialized.
935 * @param context A Context object used to access application assets.
936 * @param attrs An AttributeSet passed to our parent.
937 * @param defStyle The default style resource ID.
Svetoslav Ganovda355512010-05-12 22:04:44 -0700938 * @param javascriptInterfaces is a Map of interface names, as keys, and
Andrei Popescu4950b2b2009-09-03 13:56:07 +0100939 * object implementing those interfaces, as values.
940 * @hide pending API council approval.
941 */
942 protected WebView(Context context, AttributeSet attrs, int defStyle,
Elliott Slaughterf21d2e32010-07-14 18:08:54 -0700943 Map<String, Object> javascriptInterfaces, boolean privateBrowsing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 super(context, attrs, defStyle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945
Kristian Monsend89a30a2010-11-16 18:11:59 +0000946 // Used by the chrome stack to find application paths
947 JniUtil.setContext(context);
948
Svetoslav Ganovda355512010-05-12 22:04:44 -0700949 if (AccessibilityManager.getInstance(context).isEnabled()) {
950 if (javascriptInterfaces == null) {
951 javascriptInterfaces = new HashMap<String, Object>();
952 }
953 exposeAccessibilityJavaScriptApi(javascriptInterfaces);
954 }
955
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956 mCallbackProxy = new CallbackProxy(context, this);
Grace Kloba9a67c822009-12-20 11:33:58 -0800957 mViewManager = new ViewManager(this);
Ben Murdochb62f8a52010-11-22 16:10:19 +0000958 L10nUtils.loadStrings(context);
Andrei Popescu4950b2b2009-09-03 13:56:07 +0100959 mWebViewCore = new WebViewCore(context, this, mCallbackProxy, javascriptInterfaces);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 mDatabase = WebViewDatabase.getInstance(context);
Adam Powell637d3372010-08-25 14:37:03 -0700961 mScroller = new OverScroller(context, null, 0, 0, false); //TODO Use OverScroller's flywheel
Derek Sollenberger03e48912010-05-18 17:03:42 -0400962 mZoomManager = new ZoomManager(this, mCallbackProxy);
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700963
Derek Sollenberger90b6e482010-05-10 12:38:54 -0400964 /* The init method must follow the creation of certain member variables,
965 * such as the mZoomManager.
966 */
967 init();
Derek Sollenberger41d5e932010-08-23 14:51:41 -0400968 setupPackageListener(context);
Grace Kloba3a0def22010-01-23 21:11:54 -0800969 updateMultiTouchSupport(context);
Elliott Slaughterf21d2e32010-07-14 18:08:54 -0700970
971 if (privateBrowsing) {
972 startPrivateBrowsing();
973 }
Ben Murdochffcc49e2010-10-28 18:24:57 +0100974
Ben Murdoch01b04e12010-11-08 10:49:16 +0000975 mAutoFillData = new WebViewCore.AutoFillData();
Grace Kloba3a0def22010-01-23 21:11:54 -0800976 }
977
Derek Sollenberger41d5e932010-08-23 14:51:41 -0400978 /*
979 * The intent receiver that monitors for changes to relevant packages (e.g.,
980 * sGoogleApps) and notifies WebViewCore of their existence.
981 */
982 private static BroadcastReceiver sPackageInstallationReceiver = null;
983
984 /*
985 * A set of Google packages we monitor for the
986 * navigator.isApplicationInstalled() API. Add additional packages as
987 * needed.
988 */
989 private static Set<String> sGoogleApps;
990 static {
991 sGoogleApps = new HashSet<String>();
992 sGoogleApps.add("com.google.android.youtube");
993 }
994
995 private void setupPackageListener(Context context) {
996
997 /*
998 * we must synchronize the instance check and the creation of the
999 * receiver to ensure that only ONE receiver exists for all WebView
1000 * instances.
1001 */
1002 synchronized (WebView.class) {
1003
1004 // if the receiver already exists then we do not need to register it
1005 // again
1006 if (sPackageInstallationReceiver != null) {
1007 return;
1008 }
1009
1010 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
1011 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1012 filter.addDataScheme("package");
1013 sPackageInstallationReceiver = new BroadcastReceiver() {
1014
1015 @Override
1016 public void onReceive(Context context, Intent intent) {
1017 final String action = intent.getAction();
1018 final String packageName = intent.getData().getSchemeSpecificPart();
1019 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
1020 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
1021 // if it is replacing, refreshPlugins() when adding
1022 return;
1023 }
1024
Derek Sollenbergerc92de672010-09-01 08:55:22 -04001025 if (sGoogleApps.contains(packageName) && mWebViewCore != null) {
Derek Sollenberger41d5e932010-08-23 14:51:41 -04001026 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
1027 mWebViewCore.sendMessage(EventHub.ADD_PACKAGE_NAME, packageName);
1028 } else {
1029 mWebViewCore.sendMessage(EventHub.REMOVE_PACKAGE_NAME, packageName);
1030 }
1031 }
1032
1033 PluginManager pm = PluginManager.getInstance(context);
1034 if (pm.containsPluginPermissionAndSignatures(packageName)) {
1035 pm.refreshPlugins(Intent.ACTION_PACKAGE_ADDED.equals(action));
1036 }
1037 }
1038 };
1039
1040 context.getApplicationContext().registerReceiver(sPackageInstallationReceiver, filter);
1041 }
1042
1043 // check if any of the monitored apps are already installed
1044 AsyncTask<Void, Void, Set<String>> task = new AsyncTask<Void, Void, Set<String>>() {
1045
1046 @Override
1047 protected Set<String> doInBackground(Void... unused) {
1048 Set<String> installedPackages = new HashSet<String>();
1049 PackageManager pm = mContext.getPackageManager();
1050 List<PackageInfo> packages = pm.getInstalledPackages(0);
1051 for (PackageInfo p : packages) {
1052 if (sGoogleApps.contains(p.packageName)) {
1053 installedPackages.add(p.packageName);
1054 }
1055 }
1056 return installedPackages;
1057 }
1058
1059 // Executes on the UI thread
1060 @Override
1061 protected void onPostExecute(Set<String> installedPackages) {
Derek Sollenbergerc92de672010-09-01 08:55:22 -04001062 if (mWebViewCore != null) {
1063 mWebViewCore.sendMessage(EventHub.ADD_PACKAGE_NAMES, installedPackages);
1064 }
Derek Sollenberger41d5e932010-08-23 14:51:41 -04001065 }
1066 };
1067 task.execute();
1068 }
1069
Grace Kloba3a0def22010-01-23 21:11:54 -08001070 void updateMultiTouchSupport(Context context) {
Derek Sollenberger293c3602010-06-04 10:44:48 -04001071 mZoomManager.updateMultiTouchSupport(context);
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001072 }
1073
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 private void init() {
1075 setWillNotDraw(false);
1076 setFocusable(true);
1077 setFocusableInTouchMode(true);
1078 setClickable(true);
1079 setLongClickable(true);
1080
Romain Guy4296fc42009-07-06 11:48:52 -07001081 final ViewConfiguration configuration = ViewConfiguration.get(getContext());
Grace Kloba8b97e4b2009-07-28 13:11:38 -07001082 int slop = configuration.getScaledTouchSlop();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 mTouchSlopSquare = slop * slop;
1084 mMinLockSnapReverseDistance = slop;
Grace Kloba8b97e4b2009-07-28 13:11:38 -07001085 slop = configuration.getScaledDoubleTapSlop();
1086 mDoubleTapSlopSquare = slop * slop;
Grace Kloba25737912009-06-19 12:42:47 -07001087 final float density = getContext().getResources().getDisplayMetrics().density;
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001088 // use one line height, 16 based on our current default font, for how
1089 // far we allow a touch be away from the edge of a link
Grace Kloba25737912009-06-19 12:42:47 -07001090 mNavSlop = (int) (16 * density);
Derek Sollenberger90b6e482010-05-10 12:38:54 -04001091 mZoomManager.init(density);
Romain Guy4296fc42009-07-06 11:48:52 -07001092 mMaximumFling = configuration.getScaledMaximumFlingVelocity();
Patrick Scotta3ebcc92010-07-16 11:52:22 -04001093
1094 // Compute the inverse of the density squared.
1095 DRAG_LAYER_INVERSE_DENSITY_SQUARED = 1 / (density * density);
Adam Powell637d3372010-08-25 14:37:03 -07001096
1097 mOverscrollDistance = configuration.getScaledOverscrollDistance();
1098 mOverflingDistance = configuration.getScaledOverflingDistance();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 }
1100
Svetoslav Ganovda355512010-05-12 22:04:44 -07001101 /**
1102 * Exposes accessibility APIs to JavaScript by appending them to the JavaScript
1103 * interfaces map provided by the WebView client. In case of conflicting
1104 * alias with the one of the accessibility API the user specified one wins.
1105 *
1106 * @param javascriptInterfaces A map with interfaces to be exposed to JavaScript.
1107 */
1108 private void exposeAccessibilityJavaScriptApi(Map<String, Object> javascriptInterfaces) {
1109 if (javascriptInterfaces.containsKey(ALIAS_ACCESSIBILITY_JS_INTERFACE)) {
1110 Log.w(LOGTAG, "JavaScript interface mapped to \"" + ALIAS_ACCESSIBILITY_JS_INTERFACE
1111 + "\" overrides the accessibility API JavaScript interface. No accessibility"
1112 + "API will be exposed to JavaScript!");
1113 return;
1114 }
1115
1116 // expose the TTS for now ...
1117 javascriptInterfaces.put(ALIAS_ACCESSIBILITY_JS_INTERFACE,
1118 new TextToSpeech(getContext(), null));
1119 }
1120
Adam Powell637d3372010-08-25 14:37:03 -07001121 @Override
1122 public void setOverScrollMode(int mode) {
1123 super.setOverScrollMode(mode);
1124 if (mode != OVER_SCROLL_NEVER) {
1125 if (mOverScrollGlow == null) {
1126 mOverScrollGlow = new OverScrollGlow(this);
1127 }
1128 } else {
1129 mOverScrollGlow = null;
1130 }
1131 }
1132
Grace Kloba0d8b77c2009-06-25 11:20:51 -07001133 /* package */void updateDefaultZoomDensity(int zoomDensity) {
Derek Sollenberger03e48912010-05-18 17:03:42 -04001134 final float density = mContext.getResources().getDisplayMetrics().density
Grace Kloba0d8b77c2009-06-25 11:20:51 -07001135 * 100 / zoomDensity;
Derek Sollenberger03e48912010-05-18 17:03:42 -04001136 mNavSlop = (int) (16 * density);
1137 mZoomManager.updateDefaultZoomDensity(density);
Grace Kloba0d8b77c2009-06-25 11:20:51 -07001138 }
1139
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 /* package */ boolean onSavePassword(String schemePlusHost, String username,
1141 String password, final Message resumeMsg) {
1142 boolean rVal = false;
1143 if (resumeMsg == null) {
1144 // null resumeMsg implies saving password silently
1145 mDatabase.setUsernamePassword(schemePlusHost, username, password);
1146 } else {
1147 final Message remember = mPrivateHandler.obtainMessage(
1148 REMEMBER_PASSWORD);
1149 remember.getData().putString("host", schemePlusHost);
1150 remember.getData().putString("username", username);
1151 remember.getData().putString("password", password);
1152 remember.obj = resumeMsg;
1153
1154 final Message neverRemember = mPrivateHandler.obtainMessage(
1155 NEVER_REMEMBER_PASSWORD);
1156 neverRemember.getData().putString("host", schemePlusHost);
1157 neverRemember.getData().putString("username", username);
1158 neverRemember.getData().putString("password", password);
1159 neverRemember.obj = resumeMsg;
1160
1161 new AlertDialog.Builder(getContext())
1162 .setTitle(com.android.internal.R.string.save_password_label)
1163 .setMessage(com.android.internal.R.string.save_password_message)
1164 .setPositiveButton(com.android.internal.R.string.save_password_notnow,
1165 new DialogInterface.OnClickListener() {
1166 public void onClick(DialogInterface dialog, int which) {
1167 resumeMsg.sendToTarget();
1168 }
1169 })
1170 .setNeutralButton(com.android.internal.R.string.save_password_remember,
1171 new DialogInterface.OnClickListener() {
1172 public void onClick(DialogInterface dialog, int which) {
1173 remember.sendToTarget();
1174 }
1175 })
1176 .setNegativeButton(com.android.internal.R.string.save_password_never,
1177 new DialogInterface.OnClickListener() {
1178 public void onClick(DialogInterface dialog, int which) {
1179 neverRemember.sendToTarget();
1180 }
1181 })
1182 .setOnCancelListener(new OnCancelListener() {
1183 public void onCancel(DialogInterface dialog) {
1184 resumeMsg.sendToTarget();
1185 }
1186 }).show();
1187 // Return true so that WebViewCore will pause while the dialog is
1188 // up.
1189 rVal = true;
1190 }
1191 return rVal;
1192 }
1193
1194 @Override
1195 public void setScrollBarStyle(int style) {
1196 if (style == View.SCROLLBARS_INSIDE_INSET
1197 || style == View.SCROLLBARS_OUTSIDE_INSET) {
1198 mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = false;
1199 } else {
1200 mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = true;
1201 }
1202 super.setScrollBarStyle(style);
1203 }
1204
1205 /**
1206 * Specify whether the horizontal scrollbar has overlay style.
1207 * @param overlay TRUE if horizontal scrollbar should have overlay style.
1208 */
1209 public void setHorizontalScrollbarOverlay(boolean overlay) {
1210 mOverlayHorizontalScrollbar = overlay;
1211 }
1212
1213 /**
1214 * Specify whether the vertical scrollbar has overlay style.
1215 * @param overlay TRUE if vertical scrollbar should have overlay style.
1216 */
1217 public void setVerticalScrollbarOverlay(boolean overlay) {
1218 mOverlayVerticalScrollbar = overlay;
1219 }
1220
1221 /**
1222 * Return whether horizontal scrollbar has overlay style
1223 * @return TRUE if horizontal scrollbar has overlay style.
1224 */
1225 public boolean overlayHorizontalScrollbar() {
1226 return mOverlayHorizontalScrollbar;
1227 }
1228
1229 /**
1230 * Return whether vertical scrollbar has overlay style
1231 * @return TRUE if vertical scrollbar has overlay style.
1232 */
1233 public boolean overlayVerticalScrollbar() {
1234 return mOverlayVerticalScrollbar;
1235 }
1236
1237 /*
1238 * Return the width of the view where the content of WebView should render
1239 * to.
Grace Kloba6ed525e2009-09-17 15:31:12 -07001240 * Note: this can be called from WebCoreThread.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241 */
Grace Kloba6ed525e2009-09-17 15:31:12 -07001242 /* package */ int getViewWidth() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001243 if (!isVerticalScrollBarEnabled() || mOverlayVerticalScrollbar) {
1244 return getWidth();
1245 } else {
1246 return getWidth() - getVerticalScrollbarWidth();
1247 }
1248 }
1249
1250 /*
Mike Reede8853fc2009-09-04 14:01:48 -04001251 * returns the height of the titlebarview (if any). Does not care about
1252 * scrolling
1253 */
Derek Sollenberger03e48912010-05-18 17:03:42 -04001254 int getTitleHeight() {
Mike Reede8853fc2009-09-04 14:01:48 -04001255 return mTitleBar != null ? mTitleBar.getHeight() : 0;
1256 }
1257
1258 /*
1259 * Return the amount of the titlebarview (if any) that is visible
Michael Kolb73980a92010-08-05 16:32:51 -07001260 *
1261 * @hide
Mike Reede8853fc2009-09-04 14:01:48 -04001262 */
Michael Kolb73980a92010-08-05 16:32:51 -07001263 public int getVisibleTitleHeight() {
Adam Powell637d3372010-08-25 14:37:03 -07001264 // need to restrict mScrollY due to over scroll
1265 return Math.max(getTitleHeight() - Math.max(0, mScrollY), 0);
Mike Reede8853fc2009-09-04 14:01:48 -04001266 }
1267
1268 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 * Return the height of the view where the content of WebView should render
Leon Scroggins0236e672009-09-02 21:12:08 -04001270 * to. Note that this excludes mTitleBar, if there is one.
Grace Kloba6ed525e2009-09-17 15:31:12 -07001271 * Note: this can be called from WebCoreThread.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272 */
Grace Kloba6ed525e2009-09-17 15:31:12 -07001273 /* package */ int getViewHeight() {
Grace Kloba8eff73f2009-09-24 09:34:32 -07001274 return getViewHeightWithTitle() - getVisibleTitleHeight();
1275 }
1276
1277 private int getViewHeightWithTitle() {
Leon Scroggins0236e672009-09-02 21:12:08 -04001278 int height = getHeight();
Mike Reede8853fc2009-09-04 14:01:48 -04001279 if (isHorizontalScrollBarEnabled() && !mOverlayHorizontalScrollbar) {
Leon Scroggins0236e672009-09-02 21:12:08 -04001280 height -= getHorizontalScrollbarHeight();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 }
Grace Kloba8eff73f2009-09-24 09:34:32 -07001282 return height;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 }
1284
1285 /**
1286 * @return The SSL certificate for the main top-level page or null if
1287 * there is no certificate (the site is not secure).
1288 */
1289 public SslCertificate getCertificate() {
1290 return mCertificate;
1291 }
1292
1293 /**
1294 * Sets the SSL certificate for the main top-level page.
1295 */
1296 public void setCertificate(SslCertificate certificate) {
Brian Carlstromdba8cb72010-03-18 16:56:41 -07001297 if (DebugFlags.WEB_VIEW) {
1298 Log.v(LOGTAG, "setCertificate=" + certificate);
1299 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 // here, the certificate can be null (if the site is not secure)
1301 mCertificate = certificate;
1302 }
1303
1304 //-------------------------------------------------------------------------
1305 // Methods called by activity
1306 //-------------------------------------------------------------------------
1307
1308 /**
1309 * Save the username and password for a particular host in the WebView's
1310 * internal database.
1311 * @param host The host that required the credentials.
1312 * @param username The username for the given host.
1313 * @param password The password for the given host.
1314 */
1315 public void savePassword(String host, String username, String password) {
1316 mDatabase.setUsernamePassword(host, username, password);
1317 }
1318
1319 /**
1320 * Set the HTTP authentication credentials for a given host and realm.
1321 *
1322 * @param host The host for the credentials.
1323 * @param realm The realm for the credentials.
1324 * @param username The username for the password. If it is null, it means
1325 * password can't be saved.
1326 * @param password The password
1327 */
1328 public void setHttpAuthUsernamePassword(String host, String realm,
1329 String username, String password) {
1330 mDatabase.setHttpAuthUsernamePassword(host, realm, username, password);
1331 }
1332
1333 /**
1334 * Retrieve the HTTP authentication username and password for a given
1335 * host & realm pair
1336 *
1337 * @param host The host for which the credentials apply.
1338 * @param realm The realm for which the credentials apply.
1339 * @return String[] if found, String[0] is username, which can be null and
1340 * String[1] is password. Return null if it can't find anything.
1341 */
1342 public String[] getHttpAuthUsernamePassword(String host, String realm) {
1343 return mDatabase.getHttpAuthUsernamePassword(host, realm);
1344 }
1345
1346 /**
Leon Scroggins05919f22010-09-14 17:22:36 -04001347 * Remove Find or Select ActionModes, if active.
1348 */
1349 private void clearActionModes() {
1350 if (mSelectCallback != null) {
1351 mSelectCallback.finish();
1352 }
1353 if (mFindCallback != null) {
1354 mFindCallback.finish();
1355 }
1356 }
1357
1358 /**
1359 * Called to clear state when moving from one page to another, or changing
1360 * in some other way that makes elements associated with the current page
1361 * (such as WebTextView or ActionModes) no longer relevant.
1362 */
1363 private void clearHelpers() {
1364 clearTextEntry();
1365 clearActionModes();
Derek Sollenbergerfa89c502010-10-01 11:19:36 -04001366 dismissFullScreenMode();
Leon Scroggins05919f22010-09-14 17:22:36 -04001367 }
1368
1369 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 * Destroy the internal state of the WebView. This method should be called
1371 * after the WebView has been removed from the view system. No other
1372 * methods may be called on a WebView after destroy.
1373 */
1374 public void destroy() {
Leon Scroggins05919f22010-09-14 17:22:36 -04001375 clearHelpers();
Mattias Falk0ae2ec82010-09-16 16:24:46 +02001376 if (mListBoxDialog != null) {
1377 mListBoxDialog.dismiss();
1378 mListBoxDialog = null;
1379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 if (mWebViewCore != null) {
1381 // Set the handlers to null before destroying WebViewCore so no
Cary Clarkd6982c92009-05-29 11:02:22 -04001382 // more messages will be posted.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 mCallbackProxy.setWebViewClient(null);
1384 mCallbackProxy.setWebChromeClient(null);
1385 // Tell WebViewCore to destroy itself
Andrei Popescu04098572010-03-09 12:23:19 +00001386 synchronized (this) {
1387 WebViewCore webViewCore = mWebViewCore;
1388 mWebViewCore = null; // prevent using partial webViewCore
1389 webViewCore.destroy();
1390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 // Remove any pending messages that might not be serviced yet.
1392 mPrivateHandler.removeCallbacksAndMessages(null);
1393 mCallbackProxy.removeCallbacksAndMessages(null);
1394 // Wake up the WebCore thread just in case it is waiting for a
1395 // javascript dialog.
1396 synchronized (mCallbackProxy) {
1397 mCallbackProxy.notify();
1398 }
1399 }
1400 if (mNativeClass != 0) {
1401 nativeDestroy();
1402 mNativeClass = 0;
1403 }
1404 }
1405
1406 /**
1407 * Enables platform notifications of data state and proxy changes.
1408 */
1409 public static void enablePlatformNotifications() {
1410 Network.enablePlatformNotifications();
1411 }
1412
1413 /**
1414 * If platform notifications are enabled, this should be called
Mike Reedd205d5b2009-05-27 11:02:29 -04001415 * from the Activity's onPause() or onStop().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 */
1417 public static void disablePlatformNotifications() {
1418 Network.disablePlatformNotifications();
1419 }
Cary Clarkd6982c92009-05-29 11:02:22 -04001420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 /**
Feng Qianb3081372009-06-29 15:55:18 -07001422 * Sets JavaScript engine flags.
1423 *
1424 * @param flags JS engine flags in a String
1425 *
1426 * @hide pending API solidification
1427 */
1428 public void setJsFlags(String flags) {
1429 mWebViewCore.sendMessage(EventHub.SET_JS_FLAGS, flags);
1430 }
1431
1432 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 * Inform WebView of the network state. This is used to set
1434 * the javascript property window.navigator.isOnline and
1435 * generates the online/offline event as specified in HTML5, sec. 5.7.7
1436 * @param networkUp boolean indicating if network is available
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 */
1438 public void setNetworkAvailable(boolean networkUp) {
Grace Klobaa72cc092009-04-02 08:50:17 -07001439 mWebViewCore.sendMessage(EventHub.SET_NETWORK_STATE,
1440 networkUp ? 1 : 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 }
1442
1443 /**
Andrei Popescuf5dba882010-01-12 22:42:41 +00001444 * Inform WebView about the current network type.
1445 * {@hide}
1446 */
1447 public void setNetworkType(String type, String subtype) {
1448 Map<String, String> map = new HashMap<String, String>();
1449 map.put("type", type);
1450 map.put("subtype", subtype);
1451 mWebViewCore.sendMessage(EventHub.SET_NETWORK_TYPE, map);
1452 }
1453 /**
Cary Clarkd6982c92009-05-29 11:02:22 -04001454 * Save the state of this WebView used in
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 * {@link android.app.Activity#onSaveInstanceState}. Please note that this
1456 * method no longer stores the display data for this WebView. The previous
1457 * behavior could potentially leak files if {@link #restoreState} was never
1458 * called. See {@link #savePicture} and {@link #restorePicture} for saving
1459 * and restoring the display data.
1460 * @param outState The Bundle to store the WebView state.
1461 * @return The same copy of the back/forward list used to save the state. If
1462 * saveState fails, the returned list will be null.
1463 * @see #savePicture
1464 * @see #restorePicture
1465 */
1466 public WebBackForwardList saveState(Bundle outState) {
1467 if (outState == null) {
1468 return null;
1469 }
1470 // We grab a copy of the back/forward list because a client of WebView
1471 // may have invalidated the history list by calling clearHistory.
1472 WebBackForwardList list = copyBackForwardList();
1473 final int currentIndex = list.getCurrentIndex();
1474 final int size = list.getSize();
1475 // We should fail saving the state if the list is empty or the index is
1476 // not in a valid range.
1477 if (currentIndex < 0 || currentIndex >= size || size == 0) {
1478 return null;
1479 }
1480 outState.putInt("index", currentIndex);
1481 // FIXME: This should just be a byte[][] instead of ArrayList but
1482 // Parcel.java does not have the code to handle multi-dimensional
1483 // arrays.
1484 ArrayList<byte[]> history = new ArrayList<byte[]>(size);
1485 for (int i = 0; i < size; i++) {
1486 WebHistoryItem item = list.getItemAtIndex(i);
Cary Clark4fbf81b2009-09-29 16:07:56 -04001487 if (null == item) {
1488 // FIXME: this shouldn't happen
1489 // need to determine how item got set to null
1490 Log.w(LOGTAG, "saveState: Unexpected null history item.");
1491 return null;
1492 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493 byte[] data = item.getFlattenedData();
1494 if (data == null) {
1495 // It would be very odd to not have any data for a given history
1496 // item. And we will fail to rebuild the history list without
1497 // flattened data.
1498 return null;
1499 }
1500 history.add(data);
1501 }
1502 outState.putSerializable("history", history);
1503 if (mCertificate != null) {
1504 outState.putBundle("certificate",
1505 SslCertificate.saveState(mCertificate));
1506 }
Elliott Slaughterd6284792010-08-18 18:17:52 -07001507 outState.putBoolean("privateBrowsingEnabled", isPrivateBrowsingEnabled());
Shimeng (Simon) Wang4ae1f6f2010-08-26 10:58:38 -07001508 mZoomManager.saveZoomState(outState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 return list;
1510 }
1511
1512 /**
1513 * Save the current display data to the Bundle given. Used in conjunction
1514 * with {@link #saveState}.
1515 * @param b A Bundle to store the display data.
1516 * @param dest The file to store the serialized picture data. Will be
1517 * overwritten with this WebView's picture data.
1518 * @return True if the picture was successfully saved.
1519 */
Patrick Scottda9a22b2010-04-08 08:32:52 -04001520 public boolean savePicture(Bundle b, final File dest) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 if (dest == null || b == null) {
1522 return false;
1523 }
1524 final Picture p = capturePicture();
Patrick Scottda9a22b2010-04-08 08:32:52 -04001525 // Use a temporary file while writing to ensure the destination file
1526 // contains valid data.
1527 final File temp = new File(dest.getPath() + ".writing");
1528 new Thread(new Runnable() {
1529 public void run() {
The Android Open Source Project2d743fe2010-06-04 11:07:49 -07001530 FileOutputStream out = null;
Patrick Scottda9a22b2010-04-08 08:32:52 -04001531 try {
The Android Open Source Project2d743fe2010-06-04 11:07:49 -07001532 out = new FileOutputStream(temp);
Patrick Scottda9a22b2010-04-08 08:32:52 -04001533 p.writeToStream(out);
Patrick Scottda9a22b2010-04-08 08:32:52 -04001534 // Writing the picture succeeded, rename the temporary file
1535 // to the destination.
1536 temp.renameTo(dest);
1537 } catch (Exception e) {
1538 // too late to do anything about it.
1539 } finally {
The Android Open Source Project2d743fe2010-06-04 11:07:49 -07001540 if (out != null) {
1541 try {
1542 out.close();
1543 } catch (Exception e) {
1544 // Can't do anything about that
1545 }
1546 }
Patrick Scottda9a22b2010-04-08 08:32:52 -04001547 temp.delete();
1548 }
1549 }
1550 }).start();
1551 // now update the bundle
1552 b.putInt("scrollX", mScrollX);
1553 b.putInt("scrollY", mScrollY);
Derek Sollenbergerbffa8512010-06-10 14:24:03 -04001554 mZoomManager.saveZoomState(b);
Patrick Scottda9a22b2010-04-08 08:32:52 -04001555 return true;
1556 }
1557
1558 private void restoreHistoryPictureFields(Picture p, Bundle b) {
1559 int sx = b.getInt("scrollX", 0);
1560 int sy = b.getInt("scrollY", 0);
Derek Sollenbergerbffa8512010-06-10 14:24:03 -04001561
Patrick Scottda9a22b2010-04-08 08:32:52 -04001562 mDrawHistory = true;
1563 mHistoryPicture = p;
1564 mScrollX = sx;
1565 mScrollY = sy;
Derek Sollenbergerbffa8512010-06-10 14:24:03 -04001566 mZoomManager.restoreZoomState(b);
1567 final float scale = mZoomManager.getScale();
Patrick Scottda9a22b2010-04-08 08:32:52 -04001568 mHistoryWidth = Math.round(p.getWidth() * scale);
1569 mHistoryHeight = Math.round(p.getHeight() * scale);
Derek Sollenbergerbffa8512010-06-10 14:24:03 -04001570
Patrick Scottda9a22b2010-04-08 08:32:52 -04001571 invalidate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 }
1573
1574 /**
1575 * Restore the display data that was save in {@link #savePicture}. Used in
1576 * conjunction with {@link #restoreState}.
1577 * @param b A Bundle containing the saved display data.
1578 * @param src The file where the picture data was stored.
1579 * @return True if the picture was successfully restored.
1580 */
1581 public boolean restorePicture(Bundle b, File src) {
1582 if (src == null || b == null) {
1583 return false;
1584 }
Patrick Scottda9a22b2010-04-08 08:32:52 -04001585 if (!src.exists()) {
1586 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 }
Patrick Scottda9a22b2010-04-08 08:32:52 -04001588 try {
1589 final FileInputStream in = new FileInputStream(src);
1590 final Bundle copy = new Bundle(b);
1591 new Thread(new Runnable() {
1592 public void run() {
Patrick Scottda9a22b2010-04-08 08:32:52 -04001593 try {
The Android Open Source Project2d743fe2010-06-04 11:07:49 -07001594 final Picture p = Picture.createFromStream(in);
1595 if (p != null) {
1596 // Post a runnable on the main thread to update the
1597 // history picture fields.
1598 mPrivateHandler.post(new Runnable() {
1599 public void run() {
1600 restoreHistoryPictureFields(p, copy);
1601 }
1602 });
1603 }
1604 } finally {
1605 try {
1606 in.close();
1607 } catch (Exception e) {
1608 // Nothing we can do now.
1609 }
Patrick Scottda9a22b2010-04-08 08:32:52 -04001610 }
1611 }
1612 }).start();
1613 } catch (FileNotFoundException e){
1614 e.printStackTrace();
1615 }
1616 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 }
1618
1619 /**
1620 * Restore the state of this WebView from the given map used in
Cary Clarkd6982c92009-05-29 11:02:22 -04001621 * {@link android.app.Activity#onRestoreInstanceState}. This method should
1622 * be called to restore the state of the WebView before using the object. If
1623 * it is called after the WebView has had a chance to build state (load
1624 * pages, create a back/forward list, etc.) there may be undesirable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 * side-effects. Please note that this method no longer restores the
1626 * display data for this WebView. See {@link #savePicture} and {@link
1627 * #restorePicture} for saving and restoring the display data.
1628 * @param inState The incoming Bundle of state.
1629 * @return The restored back/forward list or null if restoreState failed.
1630 * @see #savePicture
1631 * @see #restorePicture
1632 */
1633 public WebBackForwardList restoreState(Bundle inState) {
1634 WebBackForwardList returnList = null;
1635 if (inState == null) {
1636 return returnList;
1637 }
1638 if (inState.containsKey("index") && inState.containsKey("history")) {
1639 mCertificate = SslCertificate.restoreState(
1640 inState.getBundle("certificate"));
1641
1642 final WebBackForwardList list = mCallbackProxy.getBackForwardList();
1643 final int index = inState.getInt("index");
1644 // We can't use a clone of the list because we need to modify the
1645 // shared copy, so synchronize instead to prevent concurrent
1646 // modifications.
1647 synchronized (list) {
1648 final List<byte[]> history =
1649 (List<byte[]>) inState.getSerializable("history");
1650 final int size = history.size();
1651 // Check the index bounds so we don't crash in native code while
1652 // restoring the history index.
1653 if (index < 0 || index >= size) {
1654 return null;
1655 }
1656 for (int i = 0; i < size; i++) {
1657 byte[] data = history.remove(0);
1658 if (data == null) {
1659 // If we somehow have null data, we cannot reconstruct
1660 // the item and thus our history list cannot be rebuilt.
1661 return null;
1662 }
1663 WebHistoryItem item = new WebHistoryItem(data);
1664 list.addHistoryItem(item);
1665 }
1666 // Grab the most recent copy to return to the caller.
1667 returnList = copyBackForwardList();
1668 // Update the copy to have the correct index.
1669 returnList.setCurrentIndex(index);
1670 }
Elliott Slaughterd6284792010-08-18 18:17:52 -07001671 // Restore private browsing setting.
1672 if (inState.getBoolean("privateBrowsingEnabled")) {
1673 getSettings().setPrivateBrowsingEnabled(true);
1674 }
Shimeng (Simon) Wang4ae1f6f2010-08-26 10:58:38 -07001675 mZoomManager.restoreZoomState(inState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 // Remove all pending messages because we are restoring previous
1677 // state.
1678 mWebViewCore.removeMessages();
1679 // Send a restore state message.
1680 mWebViewCore.sendMessage(EventHub.RESTORE_STATE, index);
1681 }
1682 return returnList;
1683 }
1684
1685 /**
Grace Klobad0d9bc22010-01-26 18:08:28 -08001686 * Load the given url with the extra headers.
1687 * @param url The url of the resource to load.
1688 * @param extraHeaders The extra headers sent with this url. This should not
1689 * include the common headers like "user-agent". If it does, it
1690 * will be replaced by the intrinsic value of the WebView.
1691 */
1692 public void loadUrl(String url, Map<String, String> extraHeaders) {
1693 switchOutDrawHistory();
1694 WebViewCore.GetUrlData arg = new WebViewCore.GetUrlData();
1695 arg.mUrl = url;
1696 arg.mExtraHeaders = extraHeaders;
1697 mWebViewCore.sendMessage(EventHub.LOAD_URL, arg);
Leon Scroggins05919f22010-09-14 17:22:36 -04001698 clearHelpers();
Grace Klobad0d9bc22010-01-26 18:08:28 -08001699 }
1700
1701 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001702 * Load the given url.
1703 * @param url The url of the resource to load.
1704 */
1705 public void loadUrl(String url) {
Patrick Scott4c3ca702009-07-15 15:41:05 -04001706 if (url == null) {
1707 return;
1708 }
Grace Klobad0d9bc22010-01-26 18:08:28 -08001709 loadUrl(url, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 }
1711
1712 /**
Grace Kloba57534302009-05-22 18:55:02 -07001713 * Load the url with postData using "POST" method into the WebView. If url
1714 * is not a network url, it will be loaded with {link
1715 * {@link #loadUrl(String)} instead.
Cary Clarkd6982c92009-05-29 11:02:22 -04001716 *
Grace Kloba57534302009-05-22 18:55:02 -07001717 * @param url The url of the resource to load.
1718 * @param postData The data will be passed to "POST" request.
Grace Kloba57534302009-05-22 18:55:02 -07001719 */
1720 public void postUrl(String url, byte[] postData) {
1721 if (URLUtil.isNetworkUrl(url)) {
1722 switchOutDrawHistory();
Cary Clarkded054c2009-06-15 10:26:08 -04001723 WebViewCore.PostUrlData arg = new WebViewCore.PostUrlData();
1724 arg.mUrl = url;
1725 arg.mPostData = postData;
Grace Kloba57534302009-05-22 18:55:02 -07001726 mWebViewCore.sendMessage(EventHub.POST_URL, arg);
Leon Scroggins05919f22010-09-14 17:22:36 -04001727 clearHelpers();
Grace Kloba57534302009-05-22 18:55:02 -07001728 } else {
1729 loadUrl(url);
1730 }
1731 }
1732
1733 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 * Load the given data into the WebView. This will load the data into
1735 * WebView using the data: scheme. Content loaded through this mechanism
1736 * does not have the ability to load content from the network.
Cary Clarkfc2ece42010-03-15 16:01:49 -04001737 * @param data A String of data in the given encoding. The date must
1738 * be URI-escaped -- '#', '%', '\', '?' should be replaced by %23, %25,
1739 * %27, %3f respectively.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 * @param mimeType The MIMEType of the data. i.e. text/html, image/jpeg
1741 * @param encoding The encoding of the data. i.e. utf-8, base64
1742 */
1743 public void loadData(String data, String mimeType, String encoding) {
1744 loadUrl("data:" + mimeType + ";" + encoding + "," + data);
1745 }
1746
1747 /**
1748 * Load the given data into the WebView, use the provided URL as the base
1749 * URL for the content. The base URL is the URL that represents the page
Leon Scroggins1bb1a912010-03-23 15:39:46 -04001750 * that is loaded through this interface. As such, it is used to resolve any
1751 * relative URLs. The historyUrl is used for the history entry.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 * <p>
1753 * Note for post 1.0. Due to the change in the WebKit, the access to asset
1754 * files through "file:///android_asset/" for the sub resources is more
1755 * restricted. If you provide null or empty string as baseUrl, you won't be
1756 * able to access asset files. If the baseUrl is anything other than
1757 * http(s)/ftp(s)/about/javascript as scheme, you can access asset files for
1758 * sub resources.
Cary Clarkd6982c92009-05-29 11:02:22 -04001759 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 * @param baseUrl Url to resolve relative paths with, if null defaults to
1761 * "about:blank"
1762 * @param data A String of data in the given encoding.
1763 * @param mimeType The MIMEType of the data. i.e. text/html. If null,
1764 * defaults to "text/html"
1765 * @param encoding The encoding of the data. i.e. utf-8, us-ascii
Leon Scroggins1bb1a912010-03-23 15:39:46 -04001766 * @param historyUrl URL to use as the history entry. Can be null.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 */
1768 public void loadDataWithBaseURL(String baseUrl, String data,
Leon Scroggins1bb1a912010-03-23 15:39:46 -04001769 String mimeType, String encoding, String historyUrl) {
Cary Clarkd6982c92009-05-29 11:02:22 -04001770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 if (baseUrl != null && baseUrl.toLowerCase().startsWith("data:")) {
1772 loadData(data, mimeType, encoding);
1773 return;
1774 }
1775 switchOutDrawHistory();
Cary Clarkded054c2009-06-15 10:26:08 -04001776 WebViewCore.BaseUrlData arg = new WebViewCore.BaseUrlData();
1777 arg.mBaseUrl = baseUrl;
1778 arg.mData = data;
1779 arg.mMimeType = mimeType;
1780 arg.mEncoding = encoding;
Leon Scroggins1bb1a912010-03-23 15:39:46 -04001781 arg.mHistoryUrl = historyUrl;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 mWebViewCore.sendMessage(EventHub.LOAD_DATA, arg);
Leon Scroggins05919f22010-09-14 17:22:36 -04001783 clearHelpers();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 }
1785
1786 /**
Elliott Slaughterb48fdbe2010-06-30 11:39:52 -07001787 * Saves the current view as a web archive.
1788 *
1789 * @param filename The filename where the archive should be placed.
1790 */
1791 public void saveWebArchive(String filename) {
1792 saveWebArchive(filename, false, null);
1793 }
1794
1795 /* package */ static class SaveWebArchiveMessage {
1796 SaveWebArchiveMessage (String basename, boolean autoname, ValueCallback<String> callback) {
1797 mBasename = basename;
1798 mAutoname = autoname;
1799 mCallback = callback;
1800 }
1801
1802 /* package */ final String mBasename;
1803 /* package */ final boolean mAutoname;
1804 /* package */ final ValueCallback<String> mCallback;
1805 /* package */ String mResultFile;
1806 }
1807
1808 /**
1809 * Saves the current view as a web archive.
1810 *
1811 * @param basename The filename where the archive should be placed.
1812 * @param autoname If false, takes basename to be a file. If true, basename
1813 * is assumed to be a directory in which a filename will be
1814 * chosen according to the url of the current page.
1815 * @param callback Called after the web archive has been saved. The
1816 * parameter for onReceiveValue will either be the filename
1817 * under which the file was saved, or null if saving the
1818 * file failed.
1819 */
1820 public void saveWebArchive(String basename, boolean autoname, ValueCallback<String> callback) {
1821 mWebViewCore.sendMessage(EventHub.SAVE_WEBARCHIVE,
1822 new SaveWebArchiveMessage(basename, autoname, callback));
1823 }
1824
1825 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 * Stop the current load.
1827 */
1828 public void stopLoading() {
1829 // TODO: should we clear all the messages in the queue before sending
1830 // STOP_LOADING?
1831 switchOutDrawHistory();
1832 mWebViewCore.sendMessage(EventHub.STOP_LOADING);
1833 }
1834
1835 /**
1836 * Reload the current url.
1837 */
1838 public void reload() {
Leon Scroggins05919f22010-09-14 17:22:36 -04001839 clearHelpers();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 switchOutDrawHistory();
1841 mWebViewCore.sendMessage(EventHub.RELOAD);
1842 }
1843
1844 /**
1845 * Return true if this WebView has a back history item.
1846 * @return True iff this WebView has a back history item.
1847 */
1848 public boolean canGoBack() {
1849 WebBackForwardList l = mCallbackProxy.getBackForwardList();
1850 synchronized (l) {
1851 if (l.getClearPending()) {
1852 return false;
1853 } else {
1854 return l.getCurrentIndex() > 0;
1855 }
1856 }
1857 }
1858
1859 /**
1860 * Go back in the history of this WebView.
1861 */
1862 public void goBack() {
1863 goBackOrForward(-1);
1864 }
1865
1866 /**
1867 * Return true if this WebView has a forward history item.
1868 * @return True iff this Webview has a forward history item.
1869 */
1870 public boolean canGoForward() {
1871 WebBackForwardList l = mCallbackProxy.getBackForwardList();
1872 synchronized (l) {
1873 if (l.getClearPending()) {
1874 return false;
1875 } else {
1876 return l.getCurrentIndex() < l.getSize() - 1;
1877 }
1878 }
1879 }
1880
1881 /**
1882 * Go forward in the history of this WebView.
1883 */
1884 public void goForward() {
1885 goBackOrForward(1);
1886 }
1887
1888 /**
1889 * Return true if the page can go back or forward the given
1890 * number of steps.
1891 * @param steps The negative or positive number of steps to move the
1892 * history.
1893 */
1894 public boolean canGoBackOrForward(int steps) {
1895 WebBackForwardList l = mCallbackProxy.getBackForwardList();
1896 synchronized (l) {
1897 if (l.getClearPending()) {
1898 return false;
1899 } else {
1900 int newIndex = l.getCurrentIndex() + steps;
1901 return newIndex >= 0 && newIndex < l.getSize();
1902 }
1903 }
1904 }
1905
1906 /**
1907 * Go to the history item that is the number of steps away from
1908 * the current item. Steps is negative if backward and positive
1909 * if forward.
1910 * @param steps The number of steps to take back or forward in the back
1911 * forward list.
1912 */
1913 public void goBackOrForward(int steps) {
1914 goBackOrForward(steps, false);
1915 }
1916
1917 private void goBackOrForward(int steps, boolean ignoreSnapshot) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001918 if (steps != 0) {
Leon Scroggins05919f22010-09-14 17:22:36 -04001919 clearHelpers();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 mWebViewCore.sendMessage(EventHub.GO_BACK_FORWARD, steps,
1921 ignoreSnapshot ? 1 : 0);
1922 }
1923 }
Cary Clarkd6982c92009-05-29 11:02:22 -04001924
Elliott Slaughterf21d2e32010-07-14 18:08:54 -07001925 /**
1926 * Returns true if private browsing is enabled in this WebView.
1927 */
Elliott Slaughter7c2d1352010-08-20 15:57:18 -07001928 public boolean isPrivateBrowsingEnabled() {
Elliott Slaughterf21d2e32010-07-14 18:08:54 -07001929 return getSettings().isPrivateBrowsingEnabled();
1930 }
1931
Elliott Slaughter7c2d1352010-08-20 15:57:18 -07001932 private void startPrivateBrowsing() {
Elliott Slaughterf21d2e32010-07-14 18:08:54 -07001933 boolean wasPrivateBrowsingEnabled = isPrivateBrowsingEnabled();
1934
1935 getSettings().setPrivateBrowsingEnabled(true);
1936
1937 if (!wasPrivateBrowsingEnabled) {
Elliott Slaughterd6284792010-08-18 18:17:52 -07001938 loadUrl("browser:incognito");
Elliott Slaughterf21d2e32010-07-14 18:08:54 -07001939 }
1940 }
1941
Elliott Slaughter7c2d1352010-08-20 15:57:18 -07001942 /**
1943 * Deletes any files that were created as a part of the last private
1944 * browsing session and clears any internal state associated with that
1945 * session. The consequences of calling this method while a private
1946 * browsing session is active are unspecified.
Elliott Slaughter7c2d1352010-08-20 15:57:18 -07001947 * @return True if the private browsing files were successfully deleted,
1948 * false otherwise.
1949 * @hide pending API council approval.
1950 */
Steve Block5fd5d742010-11-26 11:55:35 +00001951 public static boolean cleanupPrivateBrowsingFiles() {
1952 return nativeCleanupPrivateBrowsingFiles();
Elliott Slaughter7c2d1352010-08-20 15:57:18 -07001953 }
1954
Steve Block5fd5d742010-11-26 11:55:35 +00001955 private static native boolean nativeCleanupPrivateBrowsingFiles();
Elliott Slaughter7c2d1352010-08-20 15:57:18 -07001956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001957 private boolean extendScroll(int y) {
1958 int finalY = mScroller.getFinalY();
1959 int newY = pinLocY(finalY + y);
1960 if (newY == finalY) return false;
1961 mScroller.setFinalY(newY);
1962 mScroller.extendDuration(computeDuration(0, y));
1963 return true;
1964 }
Cary Clarkd6982c92009-05-29 11:02:22 -04001965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001966 /**
1967 * Scroll the contents of the view up by half the view size
1968 * @param top true to jump to the top of the page
1969 * @return true if the page was scrolled
1970 */
1971 public boolean pageUp(boolean top) {
1972 if (mNativeClass == 0) {
1973 return false;
1974 }
Cary Clarke872f3a2009-06-11 09:51:11 -04001975 nativeClearCursor(); // start next trackball movement from page edge
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 if (top) {
1977 // go to the top of the document
1978 return pinScrollTo(mScrollX, 0, true, 0);
1979 }
1980 // Page up
1981 int h = getHeight();
1982 int y;
1983 if (h > 2 * PAGE_SCROLL_OVERLAP) {
1984 y = -h + PAGE_SCROLL_OVERLAP;
1985 } else {
1986 y = -h / 2;
1987 }
1988 mUserScroll = true;
Cary Clarkd6982c92009-05-29 11:02:22 -04001989 return mScroller.isFinished() ? pinScrollBy(0, y, true, 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 : extendScroll(y);
1991 }
Cary Clarkd6982c92009-05-29 11:02:22 -04001992
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 /**
1994 * Scroll the contents of the view down by half the page size
1995 * @param bottom true to jump to bottom of page
1996 * @return true if the page was scrolled
1997 */
1998 public boolean pageDown(boolean bottom) {
1999 if (mNativeClass == 0) {
2000 return false;
2001 }
Cary Clarke872f3a2009-06-11 09:51:11 -04002002 nativeClearCursor(); // start next trackball movement from page edge
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 if (bottom) {
Adam Powell637d3372010-08-25 14:37:03 -07002004 return pinScrollTo(mScrollX, computeRealVerticalScrollRange(), true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002005 }
2006 // Page down.
2007 int h = getHeight();
2008 int y;
2009 if (h > 2 * PAGE_SCROLL_OVERLAP) {
2010 y = h - PAGE_SCROLL_OVERLAP;
2011 } else {
2012 y = h / 2;
2013 }
2014 mUserScroll = true;
Cary Clarkd6982c92009-05-29 11:02:22 -04002015 return mScroller.isFinished() ? pinScrollBy(0, y, true, 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016 : extendScroll(y);
2017 }
2018
2019 /**
2020 * Clear the view so that onDraw() will draw nothing but white background,
2021 * and onMeasure() will return 0 if MeasureSpec is not MeasureSpec.EXACTLY
2022 */
2023 public void clearView() {
2024 mContentWidth = 0;
2025 mContentHeight = 0;
Nicolas Roard67a9f2a2010-09-07 14:49:06 -07002026 setBaseLayer(0, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002027 mWebViewCore.sendMessage(EventHub.CLEAR_CONTENT);
2028 }
Cary Clarkd6982c92009-05-29 11:02:22 -04002029
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002030 /**
2031 * Return a new picture that captures the current display of the webview.
2032 * This is a copy of the display, and will be unaffected if the webview
2033 * later loads a different URL.
2034 *
2035 * @return a picture containing the current contents of the view. Note this
2036 * picture is of the entire document, and is not restricted to the
2037 * bounds of the view.
2038 */
2039 public Picture capturePicture() {
Cary Clark5ffbb812010-10-08 15:38:39 -04002040 if (mNativeClass == 0) return null;
Grace Kloba8abd50b2010-07-08 15:02:14 -07002041 Picture result = new Picture();
2042 nativeCopyBaseContentToPicture(result);
2043 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 }
2045
2046 /**
2047 * Return true if the browser is displaying a TextView for text input.
2048 */
2049 private boolean inEditingMode() {
Leon Scroggins63284ed2010-04-09 14:54:46 -04002050 return mWebTextView != null && mWebTextView.getParent() != null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 }
2052
Leon Scroggins6088e832010-02-17 13:17:32 -05002053 /**
2054 * Remove the WebTextView.
Leon Scroggins6088e832010-02-17 13:17:32 -05002055 */
Leon Scroggins2aed7762010-08-13 17:11:42 -04002056 private void clearTextEntry() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002057 if (inEditingMode()) {
Leon Scrogginsd3465f62009-06-02 10:57:54 -04002058 mWebTextView.remove();
Leon Scroggins III6f992702010-08-12 14:24:00 -04002059 } else {
2060 // The keyboard may be open with the WebView as the served view
2061 hideSoftKeyboard();
2062 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002063 }
2064
Cary Clarkd6982c92009-05-29 11:02:22 -04002065 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002066 * Return the current scale of the WebView
2067 * @return The current scale.
2068 */
2069 public float getScale() {
Derek Sollenbergerbffa8512010-06-10 14:24:03 -04002070 return mZoomManager.getScale();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 }
2072
2073 /**
2074 * Set the initial scale for the WebView. 0 means default. If
2075 * {@link WebSettings#getUseWideViewPort()} is true, it zooms out all the
2076 * way. Otherwise it starts with 100%. If initial scale is greater than 0,
2077 * WebView starts will this value as initial scale.
2078 *
2079 * @param scaleInPercent The initial scale in percent.
2080 */
2081 public void setInitialScale(int scaleInPercent) {
Derek Sollenberger341e22f2010-06-02 12:34:34 -04002082 mZoomManager.setInitialScaleInPercent(scaleInPercent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002083 }
2084
2085 /**
2086 * Invoke the graphical zoom picker widget for this WebView. This will
2087 * result in the zoom widget appearing on the screen to control the zoom
2088 * level of this WebView.
2089 */
2090 public void invokeZoomPicker() {
2091 if (!getSettings().supportZoom()) {
2092 Log.w(LOGTAG, "This WebView doesn't support zoom.");
2093 return;
2094 }
Leon Scroggins05919f22010-09-14 17:22:36 -04002095 clearHelpers();
Derek Sollenberger90b6e482010-05-10 12:38:54 -04002096 mZoomManager.invokeZoomPicker();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002097 }
2098
2099 /**
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04002100 * Return a HitTestResult based on the current cursor node. If a HTML::a tag
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002101 * is found and the anchor has a non-javascript url, the HitTestResult type
2102 * is set to SRC_ANCHOR_TYPE and the url is set in the "extra" field. If the
2103 * anchor does not have a url or if it is a javascript url, the type will
2104 * be UNKNOWN_TYPE and the url has to be retrieved through
2105 * {@link #requestFocusNodeHref} asynchronously. If a HTML::img tag is
2106 * found, the HitTestResult type is set to IMAGE_TYPE and the url is set in
2107 * the "extra" field. A type of
2108 * SRC_IMAGE_ANCHOR_TYPE indicates an anchor with a url that has an image as
2109 * a child node. If a phone number is found, the HitTestResult type is set
2110 * to PHONE_TYPE and the phone number is set in the "extra" field of
2111 * HitTestResult. If a map address is found, the HitTestResult type is set
2112 * to GEO_TYPE and the address is set in the "extra" field of HitTestResult.
2113 * If an email address is found, the HitTestResult type is set to EMAIL_TYPE
2114 * and the email is set in the "extra" field of HitTestResult. Otherwise,
2115 * HitTestResult type is set to UNKNOWN_TYPE.
2116 */
2117 public HitTestResult getHitTestResult() {
Cary Clarkb8491342010-11-29 16:23:19 -05002118 return hitTestResult(mInitialHitTestResult);
2119 }
2120
2121 private HitTestResult hitTestResult(HitTestResult fallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002122 if (mNativeClass == 0) {
2123 return null;
2124 }
2125
2126 HitTestResult result = new HitTestResult();
Cary Clarkd6982c92009-05-29 11:02:22 -04002127 if (nativeHasCursorNode()) {
2128 if (nativeCursorIsTextInput()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002129 result.setType(HitTestResult.EDIT_TEXT_TYPE);
Cary Clarkd6982c92009-05-29 11:02:22 -04002130 } else {
2131 String text = nativeCursorText();
2132 if (text != null) {
2133 if (text.startsWith(SCHEME_TEL)) {
2134 result.setType(HitTestResult.PHONE_TYPE);
2135 result.setExtra(text.substring(SCHEME_TEL.length()));
2136 } else if (text.startsWith(SCHEME_MAILTO)) {
2137 result.setType(HitTestResult.EMAIL_TYPE);
2138 result.setExtra(text.substring(SCHEME_MAILTO.length()));
2139 } else if (text.startsWith(SCHEME_GEO)) {
2140 result.setType(HitTestResult.GEO_TYPE);
2141 result.setExtra(URLDecoder.decode(text
2142 .substring(SCHEME_GEO.length())));
2143 } else if (nativeCursorIsAnchor()) {
2144 result.setType(HitTestResult.SRC_ANCHOR_TYPE);
2145 result.setExtra(text);
2146 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002147 }
2148 }
Cary Clarkb8491342010-11-29 16:23:19 -05002149 } else if (fallback != null) {
2150 /* If webkit causes a rebuild while the long press is in progress,
2151 * the cursor node may be reset, even if it is still around. This
2152 * uses the cursor node saved when the touch began. Since the
2153 * nativeImageURI below only changes the result if it is successful,
2154 * this uses the data beneath the touch if available or the original
2155 * tap data otherwise.
2156 */
2157 Log.v(LOGTAG, "hitTestResult use fallback");
2158 result = fallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002159 }
2160 int type = result.getType();
2161 if (type == HitTestResult.UNKNOWN_TYPE
2162 || type == HitTestResult.SRC_ANCHOR_TYPE) {
2163 // Now check to see if it is an image.
Leon Scroggins0236e672009-09-02 21:12:08 -04002164 int contentX = viewToContentX((int) mLastTouchX + mScrollX);
2165 int contentY = viewToContentY((int) mLastTouchY + mScrollY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002166 String text = nativeImageURI(contentX, contentY);
2167 if (text != null) {
Cary Clarkd6982c92009-05-29 11:02:22 -04002168 result.setType(type == HitTestResult.UNKNOWN_TYPE ?
2169 HitTestResult.IMAGE_TYPE :
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002170 HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
2171 result.setExtra(text);
2172 }
2173 }
2174 return result;
2175 }
2176
Leon Scrogginse26efa32009-12-15 16:38:45 -05002177 // Called by JNI when the DOM has changed the focus. Clear the focus so
2178 // that new keys will go to the newly focused field
2179 private void domChangedFocus() {
2180 if (inEditingMode()) {
2181 mPrivateHandler.obtainMessage(DOM_FOCUS_CHANGED).sendToTarget();
2182 }
2183 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002184 /**
2185 * Request the href of an anchor element due to getFocusNodePath returning
2186 * "href." If hrefMsg is null, this method returns immediately and does not
2187 * dispatch hrefMsg to its target.
Cary Clarkd6982c92009-05-29 11:02:22 -04002188 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002189 * @param hrefMsg This message will be dispatched with the result of the
2190 * request as the data member with "url" as key. The result can
2191 * be null.
2192 */
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04002193 // FIXME: API change required to change the name of this function. We now
2194 // look at the cursor node, and not the focus node. Also, what is
2195 // getFocusNodePath?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002196 public void requestFocusNodeHref(Message hrefMsg) {
Cary Clarke41bb532010-11-30 15:59:59 -05002197 if (hrefMsg == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002198 return;
2199 }
Cary Clarke41bb532010-11-30 15:59:59 -05002200 int contentX = viewToContentX((int) mLastTouchX + mScrollX);
2201 int contentY = viewToContentY((int) mLastTouchY + mScrollY);
2202 mWebViewCore.sendMessage(EventHub.REQUEST_CURSOR_HREF,
2203 contentX, contentY, hrefMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002204 }
Cary Clarkd6982c92009-05-29 11:02:22 -04002205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002206 /**
2207 * Request the url of the image last touched by the user. msg will be sent
2208 * to its target with a String representing the url as its object.
Cary Clarkd6982c92009-05-29 11:02:22 -04002209 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002210 * @param msg This message will be dispatched with the result of the request
2211 * as the data member with "url" as key. The result can be null.
2212 */
2213 public void requestImageRef(Message msg) {
Cary Clark7f970112009-10-15 15:29:08 -04002214 if (0 == mNativeClass) return; // client isn't initialized
Leon Scroggins0236e672009-09-02 21:12:08 -04002215 int contentX = viewToContentX((int) mLastTouchX + mScrollX);
2216 int contentY = viewToContentY((int) mLastTouchY + mScrollY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002217 String ref = nativeImageURI(contentX, contentY);
2218 Bundle data = msg.getData();
2219 data.putString("url", ref);
2220 msg.setData(data);
2221 msg.sendToTarget();
2222 }
2223
Derek Sollenberger87b17be52010-06-01 11:49:31 -04002224 static int pinLoc(int x, int viewMax, int docMax) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002225// Log.d(LOGTAG, "-- pinLoc " + x + " " + viewMax + " " + docMax);
2226 if (docMax < viewMax) { // the doc has room on the sides for "blank"
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002227 // pin the short document to the top/left of the screen
2228 x = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002229// Log.d(LOGTAG, "--- center " + x);
2230 } else if (x < 0) {
2231 x = 0;
2232// Log.d(LOGTAG, "--- zero");
2233 } else if (x + viewMax > docMax) {
2234 x = docMax - viewMax;
2235// Log.d(LOGTAG, "--- pin " + x);
2236 }
2237 return x;
2238 }
2239
2240 // Expects x in view coordinates
Derek Sollenberger03e48912010-05-18 17:03:42 -04002241 int pinLocX(int x) {
Adam Powell637d3372010-08-25 14:37:03 -07002242 if (mInOverScrollMode) return x;
2243 return pinLoc(x, getViewWidth(), computeRealHorizontalScrollRange());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002244 }
2245
2246 // Expects y in view coordinates
Derek Sollenberger03e48912010-05-18 17:03:42 -04002247 int pinLocY(int y) {
Adam Powell637d3372010-08-25 14:37:03 -07002248 if (mInOverScrollMode) return y;
Mike Reede5e63f42010-03-19 14:38:23 -04002249 return pinLoc(y, getViewHeightWithTitle(),
Adam Powell637d3372010-08-25 14:37:03 -07002250 computeRealVerticalScrollRange() + getTitleHeight());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002251 }
2252
Leon Scroggins0236e672009-09-02 21:12:08 -04002253 /**
2254 * A title bar which is embedded in this WebView, and scrolls along with it
2255 * vertically, but not horizontally.
2256 */
2257 private View mTitleBar;
2258
2259 /**
2260 * Add or remove a title bar to be embedded into the WebView, and scroll
2261 * along with it vertically, while remaining in view horizontally. Pass
2262 * null to remove the title bar from the WebView, and return to drawing
2263 * the WebView normally without translating to account for the title bar.
2264 * @hide
2265 */
Leon Scroggins078c52c2009-09-04 16:58:09 -04002266 public void setEmbeddedTitleBar(View v) {
2267 if (mTitleBar == v) return;
2268 if (mTitleBar != null) {
Leon Scroggins0236e672009-09-02 21:12:08 -04002269 removeView(mTitleBar);
Leon Scroggins078c52c2009-09-04 16:58:09 -04002270 }
2271 if (null != v) {
Leon Scroggins0236e672009-09-02 21:12:08 -04002272 addView(v, new AbsoluteLayout.LayoutParams(
Romain Guy980a9382010-01-08 15:06:28 -08002273 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins078c52c2009-09-04 16:58:09 -04002274 ViewGroup.LayoutParams.WRAP_CONTENT, 0, 0));
Leon Scroggins0236e672009-09-02 21:12:08 -04002275 }
2276 mTitleBar = v;
2277 }
2278
2279 /**
Leon Scrogginsd3997e52009-09-21 14:15:18 -04002280 * Given a distance in view space, convert it to content space. Note: this
2281 * does not reflect translation, just scaling, so this should not be called
2282 * with coordinates, but should be called for dimensions like width or
2283 * height.
2284 */
2285 private int viewToContentDimension(int d) {
Derek Sollenbergerbffa8512010-06-10 14:24:03 -04002286 return Math.round(d * mZoomManager.getInvScale());
Leon Scrogginsd3997e52009-09-21 14:15:18 -04002287 }
2288
2289 /**
Leon Scroggins0236e672009-09-02 21:12:08 -04002290 * Given an x coordinate in view space, convert it to content space. Also
2291 * may be used for absolute heights (such as for the WebTextView's
2292 * textSize, which is unaffected by the height of the title bar).
2293 */
2294 /*package*/ int viewToContentX(int x) {
Leon Scrogginsd3997e52009-09-21 14:15:18 -04002295 return viewToContentDimension(x);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002296 }
2297
Leon Scroggins0236e672009-09-02 21:12:08 -04002298 /**
2299 * Given a y coordinate in view space, convert it to content space.
2300 * Takes into account the height of the title bar if there is one
2301 * embedded into the WebView.
2302 */
2303 /*package*/ int viewToContentY(int y) {
Leon Scrogginsd3997e52009-09-21 14:15:18 -04002304 return viewToContentDimension(y - getTitleHeight());
Mike Reede8853fc2009-09-04 14:01:48 -04002305 }
2306
2307 /**
Nicolas Roard46318cf2010-05-10 15:15:51 -07002308 * Given a x coordinate in view space, convert it to content space.
2309 * Returns the result as a float.
2310 */
2311 private float viewToContentXf(int x) {
Derek Sollenbergerbffa8512010-06-10 14:24:03 -04002312 return x * mZoomManager.getInvScale();
Nicolas Roard46318cf2010-05-10 15:15:51 -07002313 }
2314
2315 /**
2316 * Given a y coordinate in view space, convert it to content space.
2317 * Takes into account the height of the title bar if there is one
2318 * embedded into the WebView. Returns the result as a float.
2319 */
2320 private float viewToContentYf(int y) {
Derek Sollenbergerbffa8512010-06-10 14:24:03 -04002321 return (y - getTitleHeight()) * mZoomManager.getInvScale();
Nicolas Roard46318cf2010-05-10 15:15:51 -07002322 }
2323
2324 /**
Mike Reede8853fc2009-09-04 14:01:48 -04002325 * Given a distance in content space, convert it to view space. Note: this
2326 * does not reflect translation, just scaling, so this should not be called
2327 * with coordinates, but should be called for dimensions like width or
2328 * height.
2329 */
2330 /*package*/ int contentToViewDimension(int d) {
Derek Sollenbergerbffa8512010-06-10 14:24:03 -04002331 return Math.round(d * mZoomManager.getScale());
Leon Scroggins0236e672009-09-02 21:12:08 -04002332 }
2333
2334 /**
2335 * Given an x coordinate in content space, convert it to view
Leon Scrogginsd3997e52009-09-21 14:15:18 -04002336 * space.
Leon Scroggins0236e672009-09-02 21:12:08 -04002337 */
2338 /*package*/ int contentToViewX(int x) {
Mike Reede8853fc2009-09-04 14:01:48 -04002339 return contentToViewDimension(x);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002340 }
2341
Leon Scroggins0236e672009-09-02 21:12:08 -04002342 /**
2343 * Given a y coordinate in content space, convert it to view
2344 * space. Takes into account the height of the title bar.
2345 */
2346 /*package*/ int contentToViewY(int y) {
Mike Reede8853fc2009-09-04 14:01:48 -04002347 return contentToViewDimension(y) + getTitleHeight();
Leon Scroggins0236e672009-09-02 21:12:08 -04002348 }
2349
Mike Reede9e86b82009-09-15 11:26:53 -04002350 private Rect contentToViewRect(Rect x) {
2351 return new Rect(contentToViewX(x.left), contentToViewY(x.top),
2352 contentToViewX(x.right), contentToViewY(x.bottom));
2353 }
2354
2355 /* To invalidate a rectangle in content coordinates, we need to transform
2356 the rect into view coordinates, so we can then call invalidate(...).
2357
2358 Normally, we would just call contentToView[XY](...), which eventually
2359 calls Math.round(coordinate * mActualScale). However, for invalidates,
2360 we need to account for the slop that occurs with antialiasing. To
2361 address that, we are a little more liberal in the size of the rect that
2362 we invalidate.
2363
2364 This liberal calculation calls floor() for the top/left, and ceil() for
2365 the bottom/right coordinates. This catches the possible extra pixels of
2366 antialiasing that we might have missed with just round().
2367 */
2368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002369 // Called by JNI to invalidate the View, given rectangle coordinates in
2370 // content space
2371 private void viewInvalidate(int l, int t, int r, int b) {
Derek Sollenbergerbffa8512010-06-10 14:24:03 -04002372 final float scale = mZoomManager.getScale();
Mike Reede9e86b82009-09-15 11:26:53 -04002373 final int dy = getTitleHeight();
2374 invalidate((int)Math.floor(l * scale),
2375 (int)Math.floor(t * scale) + dy,
2376 (int)Math.ceil(r * scale),
2377 (int)Math.ceil(b * scale) + dy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002378 }
2379
2380 // Called by JNI to invalidate the View after a delay, given rectangle
2381 // coordinates in content space
2382 private void viewInvalidateDelayed(long delay, int l, int t, int r, int b) {
Derek Sollenbergerbffa8512010-06-10 14:24:03 -04002383 final float scale = mZoomManager.getScale();
Mike Reede9e86b82009-09-15 11:26:53 -04002384 final int dy = getTitleHeight();
2385 postInvalidateDelayed(delay,
2386 (int)Math.floor(l * scale),
2387 (int)Math.floor(t * scale) + dy,
2388 (int)Math.ceil(r * scale),
2389 (int)Math.ceil(b * scale) + dy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002390 }
2391
Mike Reede9e86b82009-09-15 11:26:53 -04002392 private void invalidateContentRect(Rect r) {
2393 viewInvalidate(r.left, r.top, r.right, r.bottom);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002394 }
2395
Cary Clark278ce052009-08-31 16:08:42 -04002396 // stop the scroll animation, and don't let a subsequent fling add
2397 // to the existing velocity
2398 private void abortAnimation() {
2399 mScroller.abortAnimation();
2400 mLastVelocity = 0;
2401 }
2402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002403 /* call from webcoreview.draw(), so we're still executing in the UI thread
2404 */
2405 private void recordNewContentSize(int w, int h, boolean updateLayout) {
2406
2407 // premature data from webkit, ignore
2408 if ((w | h) == 0) {
2409 return;
2410 }
Cary Clarkd6982c92009-05-29 11:02:22 -04002411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002412 // don't abort a scroll animation if we didn't change anything
2413 if (mContentWidth != w || mContentHeight != h) {
2414 // record new dimensions
2415 mContentWidth = w;
2416 mContentHeight = h;
2417 // If history Picture is drawn, don't update scroll. They will be
2418 // updated when we get out of that mode.
2419 if (!mDrawHistory) {
2420 // repin our scroll, taking into account the new content size
Derek Sollenberger03e48912010-05-18 17:03:42 -04002421 updateScrollCoordinates(pinLocX(mScrollX), pinLocY(mScrollY));
Leon Scrogginsd84e7d52009-09-29 11:11:45 -04002422 if (!mScroller.isFinished()) {
2423 // We are in the middle of a scroll. Repin the final scroll
2424 // position.
2425 mScroller.setFinalX(pinLocX(mScroller.getFinalX()));
2426 mScroller.setFinalY(pinLocY(mScroller.getFinalY()));
2427 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002428 }
2429 }
2430 contentSizeChanged(updateLayout);
2431 }
2432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002433 // Used to avoid sending many visible rect messages.
2434 private Rect mLastVisibleRectSent;
2435 private Rect mLastGlobalRect;
2436
Derek Sollenberger03e48912010-05-18 17:03:42 -04002437 Rect sendOurVisibleRect() {
Derek Sollenberger293c3602010-06-04 10:44:48 -04002438 if (mZoomManager.isPreventingWebkitUpdates()) return mLastVisibleRectSent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 Rect rect = new Rect();
2440 calcOurContentVisibleRect(rect);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002441 // Rect.equals() checks for null input.
2442 if (!rect.equals(mLastVisibleRectSent)) {
Cary Clarked56eda2009-06-18 09:48:47 -04002443 Point pos = new Point(rect.left, rect.top);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002444 mWebViewCore.sendMessage(EventHub.SET_SCROLL_OFFSET,
Shimeng (Simon) Wang50b10342010-10-21 17:14:39 -07002445 nativeMoveGeneration(), mUserScroll ? 1 : 0, pos);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002446 mLastVisibleRectSent = rect;
Cary Clark32820242010-12-03 10:27:20 -05002447 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002448 }
2449 Rect globalRect = new Rect();
2450 if (getGlobalVisibleRect(globalRect)
2451 && !globalRect.equals(mLastGlobalRect)) {
Cary Clark3524be92009-06-22 13:09:11 -04002452 if (DebugFlags.WEB_VIEW) {
2453 Log.v(LOGTAG, "sendOurVisibleRect=(" + globalRect.left + ","
2454 + globalRect.top + ",r=" + globalRect.right + ",b="
2455 + globalRect.bottom);
2456 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002457 // TODO: the global offset is only used by windowRect()
2458 // in ChromeClientAndroid ; other clients such as touch
2459 // and mouse events could return view + screen relative points.
2460 mWebViewCore.sendMessage(EventHub.SET_GLOBAL_BOUNDS, globalRect);
2461 mLastGlobalRect = globalRect;
2462 }
2463 return rect;
2464 }
2465
2466 // Sets r to be the visible rectangle of our webview in view coordinates
2467 private void calcOurVisibleRect(Rect r) {
2468 Point p = new Point();
2469 getGlobalVisibleRect(r, p);
2470 r.offset(-p.x, -p.y);
2471 }
2472
2473 // Sets r to be our visible rectangle in content coordinates
2474 private void calcOurContentVisibleRect(Rect r) {
2475 calcOurVisibleRect(r);
Adam Powell637d3372010-08-25 14:37:03 -07002476 // since we might overscroll, pin the rect to the bounds of the content
Mike Reed180403a2010-03-10 11:34:26 -05002477 r.left = Math.max(viewToContentX(r.left), 0);
Leon Scroggins37df6a82009-09-23 10:31:23 -04002478 // viewToContentY will remove the total height of the title bar. Add
2479 // the visible height back in to account for the fact that if the title
2480 // bar is partially visible, the part of the visible rect which is
2481 // displaying our content is displaced by that amount.
Mike Reed180403a2010-03-10 11:34:26 -05002482 r.top = Math.max(viewToContentY(r.top + getVisibleTitleHeight()), 0);
2483 r.right = Math.min(viewToContentX(r.right), mContentWidth);
2484 r.bottom = Math.min(viewToContentY(r.bottom), mContentHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002485 }
2486
Nicolas Roard46318cf2010-05-10 15:15:51 -07002487 // Sets r to be our visible rectangle in content coordinates. We use this
2488 // method on the native side to compute the position of the fixed layers.
2489 // Uses floating coordinates (necessary to correctly place elements when
2490 // the scale factor is not 1)
2491 private void calcOurContentVisibleRectF(RectF r) {
2492 Rect ri = new Rect(0,0,0,0);
2493 calcOurVisibleRect(ri);
2494 // pin the rect to the bounds of the content
Nicolas Roardf78acac2010-05-10 15:15:51 -07002495 r.left = Math.max(viewToContentXf(ri.left), 0.0f);
Nicolas Roard46318cf2010-05-10 15:15:51 -07002496 // viewToContentY will remove the total height of the title bar. Add
2497 // the visible height back in to account for the fact that if the title
2498 // bar is partially visible, the part of the visible rect which is
2499 // displaying our content is displaced by that amount.
Nicolas Roardf78acac2010-05-10 15:15:51 -07002500 r.top = Math.max(viewToContentYf(ri.top + getVisibleTitleHeight()), 0.0f);
Nicolas Roard46318cf2010-05-10 15:15:51 -07002501 r.right = Math.min(viewToContentXf(ri.right), (float)mContentWidth);
2502 r.bottom = Math.min(viewToContentYf(ri.bottom), (float)mContentHeight);
2503 }
2504
Grace Klobaef347ef2009-07-30 11:20:32 -07002505 static class ViewSizeData {
2506 int mWidth;
2507 int mHeight;
2508 int mTextWrapWidth;
Grace Kloba3a0def22010-01-23 21:11:54 -08002509 int mAnchorX;
2510 int mAnchorY;
Grace Klobaef347ef2009-07-30 11:20:32 -07002511 float mScale;
Cary Clark6d45acc2009-08-27 15:42:57 -04002512 boolean mIgnoreHeight;
Grace Klobaef347ef2009-07-30 11:20:32 -07002513 }
2514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515 /**
2516 * Compute unzoomed width and height, and if they differ from the last
Derek Sollenberger03e48912010-05-18 17:03:42 -04002517 * values we sent, send them to webkit (to be used as new viewport)
2518 *
2519 * @param force ensures that the message is sent to webkit even if the width
2520 * or height has not changed since the last message
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002521 *
2522 * @return true if new values were sent
2523 */
Derek Sollenberger03e48912010-05-18 17:03:42 -04002524 boolean sendViewSizeZoom(boolean force) {
Derek Sollenberger293c3602010-06-04 10:44:48 -04002525 if (mZoomManager.isPreventingWebkitUpdates()) return false;
Grace Kloba3a0def22010-01-23 21:11:54 -08002526
Grace Klobaef347ef2009-07-30 11:20:32 -07002527 int viewWidth = getViewWidth();
Derek Sollenbergerbffa8512010-06-10 14:24:03 -04002528 int newWidth = Math.round(viewWidth * mZoomManager.getInvScale());
Shimeng (Simon) Wang346f97f2010-10-25 10:51:05 -07002529 int newHeight = Math.round((getViewHeightWithTitle() - getTitleHeight()) * mZoomManager.getInvScale());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002530 /*
2531 * Because the native side may have already done a layout before the
2532 * View system was able to measure us, we have to send a height of 0 to
2533 * remove excess whitespace when we grow our width. This will trigger a
2534 * layout and a change in content size. This content size change will
2535 * mean that contentSizeChanged will either call this method directly or
2536 * indirectly from onSizeChanged.
2537 */
2538 if (newWidth > mLastWidthSent && mWrapContent) {
2539 newHeight = 0;
2540 }
2541 // Avoid sending another message if the dimensions have not changed.
Derek Sollenberger03e48912010-05-18 17:03:42 -04002542 if (newWidth != mLastWidthSent || newHeight != mLastHeightSent || force) {
Grace Klobaef347ef2009-07-30 11:20:32 -07002543 ViewSizeData data = new ViewSizeData();
2544 data.mWidth = newWidth;
2545 data.mHeight = newHeight;
Derek Sollenbergerbffa8512010-06-10 14:24:03 -04002546 data.mTextWrapWidth = Math.round(viewWidth / mZoomManager.getTextWrapScale());
2547 data.mScale = mZoomManager.getScale();
Derek Sollenberger293c3602010-06-04 10:44:48 -04002548 data.mIgnoreHeight = mZoomManager.isFixedLengthAnimationInProgress()
2549 && !mHeightCanMeasure;
Derek Sollenberger15c5ddb2010-06-10 12:31:29 -04002550 data.mAnchorX = mZoomManager.getDocumentAnchorX();
2551 data.mAnchorY = mZoomManager.getDocumentAnchorY();
Grace Klobaef347ef2009-07-30 11:20:32 -07002552 mWebViewCore.sendMessage(EventHub.VIEW_SIZE_CHANGED, data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002553 mLastWidthSent = newWidth;
2554 mLastHeightSent = newHeight;
Derek Sollenberger15c5ddb2010-06-10 12:31:29 -04002555 mZoomManager.clearDocumentAnchor();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 return true;
2557 }
2558 return false;
2559 }
2560
Adam Powell637d3372010-08-25 14:37:03 -07002561 private int computeRealHorizontalScrollRange() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 if (mDrawHistory) {
2563 return mHistoryWidth;
Grace Kloba0653d222010-04-23 15:21:24 -07002564 } else if (mHorizontalScrollBarMode == SCROLLBAR_ALWAYSOFF
Grace Kloba6164ef12010-06-01 15:59:13 -07002565 && !mZoomManager.canZoomOut()) {
Grace Kloba0653d222010-04-23 15:21:24 -07002566 // only honor the scrollbar mode when it is at minimum zoom level
Grace Kloba50004bc2010-04-13 22:58:51 -07002567 return computeHorizontalScrollExtent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002568 } else {
Grace Klobae621d6f2009-09-11 13:20:39 -07002569 // to avoid rounding error caused unnecessary scrollbar, use floor
Derek Sollenbergerbffa8512010-06-10 14:24:03 -04002570 return (int) Math.floor(mContentWidth * mZoomManager.getScale());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 }
2572 }
2573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 @Override
Adam Powell637d3372010-08-25 14:37:03 -07002575 protected int computeHorizontalScrollRange() {
2576 int range = computeRealHorizontalScrollRange();
2577
2578 // Adjust reported range if overscrolled to compress the scroll bars
2579 final int scrollX = mScrollX;
2580 final int overscrollRight = computeMaxScrollX();
2581 if (scrollX < 0) {
2582 range -= scrollX;
2583 } else if (scrollX > overscrollRight) {
2584 range += scrollX - overscrollRight;
2585 }
2586
2587 return range;
2588 }
2589
2590 @Override
2591 protected int computeHorizontalScrollOffset() {
2592 return Math.max(mScrollX, 0);
2593 }
2594
2595 private int computeRealVerticalScrollRange() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002596 if (mDrawHistory) {
2597 return mHistoryHeight;
Grace Kloba0653d222010-04-23 15:21:24 -07002598 } else if (mVerticalScrollBarMode == SCROLLBAR_ALWAYSOFF
Grace Kloba6164ef12010-06-01 15:59:13 -07002599 && !mZoomManager.canZoomOut()) {
Grace Kloba0653d222010-04-23 15:21:24 -07002600 // only honor the scrollbar mode when it is at minimum zoom level
Grace Kloba50004bc2010-04-13 22:58:51 -07002601 return computeVerticalScrollExtent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002602 } else {
Grace Klobae621d6f2009-09-11 13:20:39 -07002603 // to avoid rounding error caused unnecessary scrollbar, use floor
Derek Sollenbergerbffa8512010-06-10 14:24:03 -04002604 return (int) Math.floor(mContentHeight * mZoomManager.getScale());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002605 }
2606 }
2607
Leon Scroggins0236e672009-09-02 21:12:08 -04002608 @Override
Adam Powell637d3372010-08-25 14:37:03 -07002609 protected int computeVerticalScrollRange() {
2610 int range = computeRealVerticalScrollRange();
2611
2612 // Adjust reported range if overscrolled to compress the scroll bars
2613 final int scrollY = mScrollY;
2614 final int overscrollBottom = computeMaxScrollY();
2615 if (scrollY < 0) {
2616 range -= scrollY;
2617 } else if (scrollY > overscrollBottom) {
2618 range += scrollY - overscrollBottom;
2619 }
2620
2621 return range;
2622 }
2623
2624 @Override
Leon Scroggins0236e672009-09-02 21:12:08 -04002625 protected int computeVerticalScrollOffset() {
Mike Reede8853fc2009-09-04 14:01:48 -04002626 return Math.max(mScrollY - getTitleHeight(), 0);
Leon Scroggins0236e672009-09-02 21:12:08 -04002627 }
2628
2629 @Override
2630 protected int computeVerticalScrollExtent() {
2631 return getViewHeight();
2632 }
2633
Mike Reede8853fc2009-09-04 14:01:48 -04002634 /** @hide */
2635 @Override
2636 protected void onDrawVerticalScrollBar(Canvas canvas,
2637 Drawable scrollBar,
2638 int l, int t, int r, int b) {
Adam Powell637d3372010-08-25 14:37:03 -07002639 if (mScrollY < 0) {
2640 t -= mScrollY;
2641 }
Mike Reede8853fc2009-09-04 14:01:48 -04002642 scrollBar.setBounds(l, t + getVisibleTitleHeight(), r, b);
2643 scrollBar.draw(canvas);
2644 }
2645
Adam Powell637d3372010-08-25 14:37:03 -07002646 @Override
2647 protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX,
2648 boolean clampedY) {
2649 mInOverScrollMode = false;
2650 int maxX = computeMaxScrollX();
2651 int maxY = computeMaxScrollY();
2652 if (maxX == 0) {
2653 // do not over scroll x if the page just fits the screen
2654 scrollX = pinLocX(scrollX);
2655 } else if (scrollX < 0 || scrollX > maxX) {
2656 mInOverScrollMode = true;
2657 }
2658 if (scrollY < 0 || scrollY > maxY) {
2659 mInOverScrollMode = true;
2660 }
2661
2662 int oldX = mScrollX;
2663 int oldY = mScrollY;
2664
2665 super.scrollTo(scrollX, scrollY);
2666
2667 if (mOverScrollGlow != null) {
2668 mOverScrollGlow.pullGlow(mScrollX, mScrollY, oldX, oldY, maxX, maxY);
2669 }
2670 }
2671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002672 /**
2673 * Get the url for the current page. This is not always the same as the url
2674 * passed to WebViewClient.onPageStarted because although the load for
2675 * that url has begun, the current page may not have changed.
2676 * @return The url for the current page.
2677 */
2678 public String getUrl() {
2679 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2680 return h != null ? h.getUrl() : null;
2681 }
Cary Clarkd6982c92009-05-29 11:02:22 -04002682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002683 /**
Cary Clarkd6982c92009-05-29 11:02:22 -04002684 * Get the original url for the current page. This is not always the same
2685 * as the url passed to WebViewClient.onPageStarted because although the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 * load for that url has begun, the current page may not have changed.
2687 * Also, there may have been redirects resulting in a different url to that
2688 * originally requested.
2689 * @return The url that was originally requested for the current page.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002690 */
2691 public String getOriginalUrl() {
2692 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2693 return h != null ? h.getOriginalUrl() : null;
2694 }
2695
2696 /**
2697 * Get the title for the current page. This is the title of the current page
2698 * until WebViewClient.onReceivedTitle is called.
2699 * @return The title for the current page.
2700 */
2701 public String getTitle() {
2702 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2703 return h != null ? h.getTitle() : null;
2704 }
2705
2706 /**
2707 * Get the favicon for the current page. This is the favicon of the current
2708 * page until WebViewClient.onReceivedIcon is called.
2709 * @return The favicon for the current page.
2710 */
2711 public Bitmap getFavicon() {
2712 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2713 return h != null ? h.getFavicon() : null;
2714 }
2715
2716 /**
Ben Murdoch372dfc82010-07-01 15:56:01 +01002717 * Get the touch icon url for the apple-touch-icon <link> element, or
2718 * a URL on this site's server pointing to the standard location of a
2719 * touch icon.
Patrick Scott2ba12622009-08-04 13:20:05 -04002720 * @hide
2721 */
2722 public String getTouchIconUrl() {
2723 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2724 return h != null ? h.getTouchIconUrl() : null;
2725 }
2726
2727 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002728 * Get the progress for the current page.
2729 * @return The progress for the current page between 0 and 100.
2730 */
2731 public int getProgress() {
2732 return mCallbackProxy.getProgress();
2733 }
Cary Clarkd6982c92009-05-29 11:02:22 -04002734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002735 /**
2736 * @return the height of the HTML content.
2737 */
2738 public int getContentHeight() {
2739 return mContentHeight;
2740 }
2741
2742 /**
Leon Scrogginsea96d1e2009-09-23 13:41:01 -04002743 * @return the width of the HTML content.
2744 * @hide
2745 */
2746 public int getContentWidth() {
2747 return mContentWidth;
2748 }
2749
2750 /**
Mike Reedd205d5b2009-05-27 11:02:29 -04002751 * Pause all layout, parsing, and javascript timers for all webviews. This
2752 * is a global requests, not restricted to just this webview. This can be
2753 * useful if the application has been paused.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002754 */
2755 public void pauseTimers() {
2756 mWebViewCore.sendMessage(EventHub.PAUSE_TIMERS);
2757 }
2758
2759 /**
Mike Reedd205d5b2009-05-27 11:02:29 -04002760 * Resume all layout, parsing, and javascript timers for all webviews.
2761 * This will resume dispatching all timers.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002762 */
2763 public void resumeTimers() {
2764 mWebViewCore.sendMessage(EventHub.RESUME_TIMERS);
2765 }
2766
2767 /**
Mike Reedd205d5b2009-05-27 11:02:29 -04002768 * Call this to pause any extra processing associated with this view and
2769 * its associated DOM/plugins/javascript/etc. For example, if the view is
2770 * taken offscreen, this could be called to reduce unnecessary CPU and/or
2771 * network traffic. When the view is again "active", call onResume().
2772 *
2773 * Note that this differs from pauseTimers(), which affects all views/DOMs
2774 * @hide
2775 */
2776 public void onPause() {
2777 if (!mIsPaused) {
2778 mIsPaused = true;
2779 mWebViewCore.sendMessage(EventHub.ON_PAUSE);
2780 }
2781 }
2782
2783 /**
2784 * Call this to balanace a previous call to onPause()
2785 * @hide
2786 */
2787 public void onResume() {
2788 if (mIsPaused) {
2789 mIsPaused = false;
2790 mWebViewCore.sendMessage(EventHub.ON_RESUME);
2791 }
2792 }
2793
2794 /**
2795 * Returns true if the view is paused, meaning onPause() was called. Calling
2796 * onResume() sets the paused state back to false.
2797 * @hide
2798 */
2799 public boolean isPaused() {
2800 return mIsPaused;
2801 }
2802
2803 /**
Derek Sollenbergere0155e92009-06-10 15:35:45 -04002804 * Call this to inform the view that memory is low so that it can
2805 * free any available memory.
Derek Sollenbergere0155e92009-06-10 15:35:45 -04002806 */
2807 public void freeMemory() {
2808 mWebViewCore.sendMessage(EventHub.FREE_MEMORY);
2809 }
2810
2811 /**
Mike Hearnadcd2ed2009-01-21 16:44:36 +01002812 * Clear the resource cache. Note that the cache is per-application, so
2813 * this will clear the cache for all WebViews used.
2814 *
2815 * @param includeDiskFiles If false, only the RAM cache is cleared.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816 */
2817 public void clearCache(boolean includeDiskFiles) {
Mike Hearnadcd2ed2009-01-21 16:44:36 +01002818 // Note: this really needs to be a static method as it clears cache for all
2819 // WebView. But we need mWebViewCore to send message to WebCore thread, so
2820 // we can't make this static.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821 mWebViewCore.sendMessage(EventHub.CLEAR_CACHE,
2822 includeDiskFiles ? 1 : 0, 0);
2823 }
2824
2825 /**
2826 * Make sure that clearing the form data removes the adapter from the
2827 * currently focused textfield if there is one.
2828 */
2829 public void clearFormData() {
2830 if (inEditingMode()) {
2831 AutoCompleteAdapter adapter = null;
Leon Scrogginsd3465f62009-06-02 10:57:54 -04002832 mWebTextView.setAdapterCustom(adapter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 }
2834 }
2835
2836 /**
2837 * Tell the WebView to clear its internal back/forward list.
2838 */
2839 public void clearHistory() {
2840 mCallbackProxy.getBackForwardList().setClearPending();
2841 mWebViewCore.sendMessage(EventHub.CLEAR_HISTORY);
2842 }
2843
2844 /**
2845 * Clear the SSL preferences table stored in response to proceeding with SSL
2846 * certificate errors.
2847 */
2848 public void clearSslPreferences() {
2849 mWebViewCore.sendMessage(EventHub.CLEAR_SSL_PREF_TABLE);
2850 }
2851
2852 /**
2853 * Return the WebBackForwardList for this WebView. This contains the
2854 * back/forward list for use in querying each item in the history stack.
2855 * This is a copy of the private WebBackForwardList so it contains only a
2856 * snapshot of the current state. Multiple calls to this method may return
2857 * different objects. The object returned from this method will not be
2858 * updated to reflect any new state.
2859 */
2860 public WebBackForwardList copyBackForwardList() {
2861 return mCallbackProxy.getBackForwardList().clone();
2862 }
2863
2864 /*
2865 * Highlight and scroll to the next occurance of String in findAll.
Cary Clarkd6982c92009-05-29 11:02:22 -04002866 * Wraps the page infinitely, and scrolls. Must be called after
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002867 * calling findAll.
2868 *
2869 * @param forward Direction to search.
2870 */
2871 public void findNext(boolean forward) {
Cary Clark7f970112009-10-15 15:29:08 -04002872 if (0 == mNativeClass) return; // client isn't initialized
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002873 nativeFindNext(forward);
2874 }
2875
2876 /*
2877 * Find all instances of find on the page and highlight them.
2878 * @param find String to find.
2879 * @return int The number of occurances of the String "find"
2880 * that were found.
2881 */
2882 public int findAll(String find) {
Cary Clark7f970112009-10-15 15:29:08 -04002883 if (0 == mNativeClass) return 0; // client isn't initialized
Cary Clarkde023c12010-03-03 10:05:16 -05002884 int result = find != null ? nativeFindAll(find.toLowerCase(),
Leon Scroggins4f4a5672010-10-19 13:58:11 -04002885 find.toUpperCase(), find.equalsIgnoreCase(mLastFind)) : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002886 invalidate();
Leon Scroggins5de63892009-10-29 09:48:43 -04002887 mLastFind = find;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 return result;
2889 }
2890
Cary Clark3403eb32010-03-03 10:05:16 -05002891 /**
Leon Scrogginsfe026bd2010-08-24 14:16:09 -04002892 * Start an ActionMode for finding text in this WebView.
2893 * @param text If non-null, will be the initial text to search for.
2894 * Otherwise, the last String searched for in this WebView will
2895 * be used to start.
Cary Clarkde023c12010-03-03 10:05:16 -05002896 */
Leon Scrogginsfe026bd2010-08-24 14:16:09 -04002897 public void showFindDialog(String text) {
2898 mFindCallback = new FindActionModeCallback(mContext);
2899 setFindIsUp(true);
2900 mFindCallback.setWebView(this);
2901 View titleBar = mTitleBar;
Leon Scrogginsfe026bd2010-08-24 14:16:09 -04002902 startActionMode(mFindCallback);
2903 if (text == null) {
2904 text = mLastFind;
2905 }
2906 if (text != null) {
2907 mFindCallback.setText(text);
2908 }
2909 }
2910
2911 /**
2912 * Keep track of the find callback so that we can remove its titlebar if
2913 * necessary.
2914 */
2915 private FindActionModeCallback mFindCallback;
2916
2917 /**
2918 * Toggle whether the find dialog is showing, for both native and Java.
2919 */
2920 private void setFindIsUp(boolean isUp) {
Cary Clarkde023c12010-03-03 10:05:16 -05002921 mFindIsUp = isUp;
Cary Clarkde023c12010-03-03 10:05:16 -05002922 if (0 == mNativeClass) return; // client isn't initialized
2923 nativeSetFindIsUp(isUp);
2924 }
2925
Leon Scroggins III26723fc2010-04-19 13:21:42 -04002926 /**
Leon Scrogginsfe026bd2010-08-24 14:16:09 -04002927 * Return the index of the currently highlighted match.
Leon Scroggins III26723fc2010-04-19 13:21:42 -04002928 */
Leon Scrogginsfe026bd2010-08-24 14:16:09 -04002929 int findIndex() {
Leon Scroggins6a367f52010-05-06 17:37:40 -04002930 if (0 == mNativeClass) return -1;
2931 return nativeFindIndex();
2932 }
2933
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002934 // Used to know whether the find dialog is open. Affects whether
2935 // or not we draw the highlights for matches.
2936 private boolean mFindIsUp;
Cary Clarkde023c12010-03-03 10:05:16 -05002937
Leon Scrogginsfe026bd2010-08-24 14:16:09 -04002938 // Keep track of the last string sent, so we can search again when find is
2939 // reopened.
Leon Scroggins5de63892009-10-29 09:48:43 -04002940 private String mLastFind;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002942 /**
Cary Clarkd6982c92009-05-29 11:02:22 -04002943 * Return the first substring consisting of the address of a physical
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002944 * location. Currently, only addresses in the United States are detected,
2945 * and consist of:
2946 * - a house number
2947 * - a street name
2948 * - a street type (Road, Circle, etc), either spelled out or abbreviated
2949 * - a city name
2950 * - a state or territory, either spelled out or two-letter abbr.
2951 * - an optional 5 digit or 9 digit zip code.
2952 *
2953 * All names must be correctly capitalized, and the zip code, if present,
2954 * must be valid for the state. The street type must be a standard USPS
2955 * spelling or abbreviation. The state or territory must also be spelled
Cary Clarkd6982c92009-05-29 11:02:22 -04002956 * or abbreviated using USPS standards. The house number may not exceed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002957 * five digits.
2958 * @param addr The string to search for addresses.
2959 *
2960 * @return the address, or if no address is found, return null.
2961 */
2962 public static String findAddress(String addr) {
Cary Clark3e399de2009-06-17 10:00:57 -04002963 return findAddress(addr, false);
2964 }
2965
2966 /**
2967 * @hide
2968 * Return the first substring consisting of the address of a physical
2969 * location. Currently, only addresses in the United States are detected,
2970 * and consist of:
2971 * - a house number
2972 * - a street name
2973 * - a street type (Road, Circle, etc), either spelled out or abbreviated
2974 * - a city name
2975 * - a state or territory, either spelled out or two-letter abbr.
2976 * - an optional 5 digit or 9 digit zip code.
2977 *
2978 * Names are optionally capitalized, and the zip code, if present,
2979 * must be valid for the state. The street type must be a standard USPS
2980 * spelling or abbreviation. The state or territory must also be spelled
2981 * or abbreviated using USPS standards. The house number may not exceed
2982 * five digits.
2983 * @param addr The string to search for addresses.
2984 * @param caseInsensitive addr Set to true to make search ignore case.
2985 *
2986 * @return the address, or if no address is found, return null.
2987 */
2988 public static String findAddress(String addr, boolean caseInsensitive) {
2989 return WebViewCore.nativeFindAddress(addr, caseInsensitive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002990 }
2991
2992 /*
2993 * Clear the highlighting surrounding text matches created by findAll.
2994 */
2995 public void clearMatches() {
Cary Clark32847a92009-11-17 16:04:18 -05002996 if (mNativeClass == 0)
2997 return;
Cary Clarkde023c12010-03-03 10:05:16 -05002998 nativeSetFindIsEmpty();
2999 invalidate();
3000 }
3001
3002 /**
Leon Scrogginsfe026bd2010-08-24 14:16:09 -04003003 * Called when the find ActionMode ends.
Cary Clarkde023c12010-03-03 10:05:16 -05003004 */
Leon Scrogginsfe026bd2010-08-24 14:16:09 -04003005 void notifyFindDialogDismissed() {
3006 mFindCallback = null;
Shimeng (Simon) Wang4d8ef422010-03-22 17:06:17 -07003007 if (mWebViewCore == null) {
3008 return;
3009 }
Cary Clarkde023c12010-03-03 10:05:16 -05003010 clearMatches();
3011 setFindIsUp(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003012 // Now that the dialog has been removed, ensure that we scroll to a
3013 // location that is not beyond the end of the page.
3014 pinScrollTo(mScrollX, mScrollY, false, 0);
3015 invalidate();
3016 }
3017
3018 /**
3019 * Query the document to see if it contains any image references. The
3020 * message object will be dispatched with arg1 being set to 1 if images
3021 * were found and 0 if the document does not reference any images.
3022 * @param response The message that will be dispatched with the result.
3023 */
3024 public void documentHasImages(Message response) {
3025 if (response == null) {
3026 return;
3027 }
3028 mWebViewCore.sendMessage(EventHub.DOC_HAS_IMAGES, response);
3029 }
3030
Michael Kolb73980a92010-08-05 16:32:51 -07003031 /**
3032 * Request the scroller to abort any ongoing animation
3033 *
3034 * @hide
3035 */
3036 public void stopScroll() {
3037 mScroller.forceFinished(true);
3038 mLastVelocity = 0;
3039 }
3040
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003041 @Override
3042 public void computeScroll() {
3043 if (mScroller.computeScrollOffset()) {
3044 int oldX = mScrollX;
3045 int oldY = mScrollY;
Adam Powell637d3372010-08-25 14:37:03 -07003046 int x = mScroller.getCurrX();
3047 int y = mScroller.getCurrY();
3048 invalidate(); // So we draw again
3049
3050 if (!mScroller.isFinished()) {
3051 final int rangeX = computeMaxScrollX();
3052 final int rangeY = computeMaxScrollY();
3053 overScrollBy(x - oldX, y - oldY, oldX, oldY,
3054 rangeX, rangeY,
3055 mOverflingDistance, mOverflingDistance, false);
3056
3057 if (mOverScrollGlow != null) {
3058 mOverScrollGlow.absorbGlow(x, y, oldX, oldY, rangeX, rangeY);
3059 }
3060 } else {
3061 mScrollX = x;
3062 mScrollY = y;
Adam Powell4c3ce842010-11-23 17:39:56 -08003063 abortAnimation();
3064 mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY);
3065 WebViewCore.resumePriority();
Cary Clark0df02692010-11-24 11:01:37 -05003066 if (!mSelectingText) {
3067 WebViewCore.resumeUpdatePicture(mWebViewCore);
3068 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003069 }
3070 } else {
3071 super.computeScroll();
3072 }
3073 }
3074
3075 private static int computeDuration(int dx, int dy) {
3076 int distance = Math.max(Math.abs(dx), Math.abs(dy));
3077 int duration = distance * 1000 / STD_SPEED;
3078 return Math.min(duration, MAX_DURATION);
3079 }
3080
3081 // helper to pin the scrollBy parameters (already in view coordinates)
3082 // returns true if the scroll was changed
3083 private boolean pinScrollBy(int dx, int dy, boolean animate, int animationDuration) {
3084 return pinScrollTo(mScrollX + dx, mScrollY + dy, animate, animationDuration);
3085 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003086 // helper to pin the scrollTo parameters (already in view coordinates)
3087 // returns true if the scroll was changed
3088 private boolean pinScrollTo(int x, int y, boolean animate, int animationDuration) {
3089 x = pinLocX(x);
3090 y = pinLocY(y);
3091 int dx = x - mScrollX;
3092 int dy = y - mScrollY;
3093
3094 if ((dx | dy) == 0) {
3095 return false;
3096 }
Cary Clark21a97ef2010-11-16 09:59:40 -05003097 abortAnimation();
Leon Scrogginsd55de402009-09-17 14:19:49 -04003098 if (animate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003099 // Log.d(LOGTAG, "startScroll: " + dx + " " + dy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003100 mScroller.startScroll(mScrollX, mScrollY, dx, dy,
3101 animationDuration > 0 ? animationDuration : computeDuration(dx, dy));
Mike Cleronf116bf82009-09-27 19:14:12 -07003102 awakenScrollBars(mScroller.getDuration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003103 invalidate();
3104 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003105 scrollTo(x, y);
3106 }
3107 return true;
3108 }
3109
3110 // Scale from content to view coordinates, and pin.
3111 // Also called by jni webview.cpp
Leon Scroggins4c943042009-07-31 15:05:42 -04003112 private boolean setContentScrollBy(int cx, int cy, boolean animate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003113 if (mDrawHistory) {
3114 // disallow WebView to change the scroll position as History Picture
3115 // is used in the view system.
3116 // TODO: as we switchOutDrawHistory when trackball or navigation
3117 // keys are hit, this should be safe. Right?
Leon Scroggins4c943042009-07-31 15:05:42 -04003118 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003119 }
Mike Reede8853fc2009-09-04 14:01:48 -04003120 cx = contentToViewDimension(cx);
3121 cy = contentToViewDimension(cy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003122 if (mHeightCanMeasure) {
3123 // move our visible rect according to scroll request
3124 if (cy != 0) {
3125 Rect tempRect = new Rect();
3126 calcOurVisibleRect(tempRect);
3127 tempRect.offset(cx, cy);
3128 requestRectangleOnScreen(tempRect);
3129 }
3130 // FIXME: We scroll horizontally no matter what because currently
3131 // ScrollView and ListView will not scroll horizontally.
3132 // FIXME: Why do we only scroll horizontally if there is no
3133 // vertical scroll?
3134// Log.d(LOGTAG, "setContentScrollBy cy=" + cy);
Leon Scroggins4c943042009-07-31 15:05:42 -04003135 return cy == 0 && cx != 0 && pinScrollBy(cx, 0, animate, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136 } else {
Leon Scroggins4c943042009-07-31 15:05:42 -04003137 return pinScrollBy(cx, cy, animate, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003138 }
3139 }
3140
Leon Scroggins405d7852009-11-02 14:50:54 -08003141 /**
Svetoslav Ganov585f13f8d2010-08-10 07:59:15 -07003142 * Called by CallbackProxy when the page starts loading.
3143 * @param url The URL of the page which has started loading.
3144 */
3145 /* package */ void onPageStarted(String url) {
3146 // every time we start a new page, we want to reset the
3147 // WebView certificate: if the new site is secure, we
3148 // will reload it and get a new certificate set;
3149 // if the new site is not secure, the certificate must be
3150 // null, and that will be the case
3151 setCertificate(null);
3152
3153 // reset the flag since we set to true in if need after
3154 // loading is see onPageFinished(Url)
3155 mAccessibilityScriptInjected = false;
3156 }
3157
3158 /**
Leon Scroggins405d7852009-11-02 14:50:54 -08003159 * Called by CallbackProxy when the page finishes loading.
3160 * @param url The URL of the page which has finished loading.
3161 */
3162 /* package */ void onPageFinished(String url) {
3163 if (mPageThatNeedsToSlideTitleBarOffScreen != null) {
3164 // If the user is now on a different page, or has scrolled the page
3165 // past the point where the title bar is offscreen, ignore the
3166 // scroll request.
3167 if (mPageThatNeedsToSlideTitleBarOffScreen.equals(url)
3168 && mScrollX == 0 && mScrollY == 0) {
3169 pinScrollTo(0, mYDistanceToSlideTitleOffScreen, true,
3170 SLIDE_TITLE_DURATION);
3171 }
3172 mPageThatNeedsToSlideTitleBarOffScreen = null;
3173 }
Svetoslav Ganovda355512010-05-12 22:04:44 -07003174
3175 injectAccessibilityForUrl(url);
3176 }
3177
3178 /**
3179 * This method injects accessibility in the loaded document if accessibility
3180 * is enabled. If JavaScript is enabled we try to inject a URL specific script.
3181 * If no URL specific script is found or JavaScript is disabled we fallback to
3182 * the default {@link AccessibilityInjector} implementation.
Svetoslav Ganov585f13f8d2010-08-10 07:59:15 -07003183 * </p>
3184 * If the URL has the "axs" paramter set to 1 it has already done the
3185 * script injection so we do nothing. If the parameter is set to 0
3186 * the URL opts out accessibility script injection so we fall back to
3187 * the default {@link AccessibilityInjector}.
3188 * </p>
3189 * Note: If the user has not opted-in the accessibility script injection no scripts
3190 * are injected rather the default {@link AccessibilityInjector} implementation
3191 * is used.
Svetoslav Ganovda355512010-05-12 22:04:44 -07003192 *
3193 * @param url The URL loaded by this {@link WebView}.
3194 */
3195 private void injectAccessibilityForUrl(String url) {
Svetoslav Ganov585f13f8d2010-08-10 07:59:15 -07003196 AccessibilityManager accessibilityManager = AccessibilityManager.getInstance(mContext);
3197
3198 if (!accessibilityManager.isEnabled()) {
Svetoslav Ganovda355512010-05-12 22:04:44 -07003199 // it is possible that accessibility was turned off between reloads
Svetoslav Ganov585f13f8d2010-08-10 07:59:15 -07003200 ensureAccessibilityScriptInjectorInstance(false);
3201 return;
3202 }
3203
3204 if (!getSettings().getJavaScriptEnabled()) {
3205 // no JS so we fallback to the basic buil-in support
3206 ensureAccessibilityScriptInjectorInstance(true);
3207 return;
3208 }
3209
3210 // check the URL "axs" parameter to choose appropriate action
3211 int axsParameterValue = getAxsUrlParameterValue(url);
3212 if (axsParameterValue == ACCESSIBILITY_SCRIPT_INJECTION_UNDEFINED) {
3213 boolean onDeviceScriptInjectionEnabled = (Settings.Secure.getInt(mContext
3214 .getContentResolver(), Settings.Secure.ACCESSIBILITY_SCRIPT_INJECTION, 0) == 1);
3215 if (onDeviceScriptInjectionEnabled) {
3216 ensureAccessibilityScriptInjectorInstance(false);
3217 // neither script injected nor script injection opted out => we inject
3218 loadUrl(ACCESSIBILITY_SCRIPT_CHOOSER_JAVASCRIPT);
3219 // TODO: Set this flag after successfull script injection. Maybe upon injection
3220 // the chooser should update the meta tag and we check it to declare success
3221 mAccessibilityScriptInjected = true;
3222 } else {
3223 // injection disabled so we fallback to the basic built-in support
3224 ensureAccessibilityScriptInjectorInstance(true);
3225 }
3226 } else if (axsParameterValue == ACCESSIBILITY_SCRIPT_INJECTION_OPTED_OUT) {
3227 // injection opted out so we fallback to the basic buil-in support
3228 ensureAccessibilityScriptInjectorInstance(true);
3229 } else if (axsParameterValue == ACCESSIBILITY_SCRIPT_INJECTION_PROVIDED) {
3230 ensureAccessibilityScriptInjectorInstance(false);
3231 // the URL provides accessibility but we still need to add our generic script
3232 loadUrl(ACCESSIBILITY_SCRIPT_CHOOSER_JAVASCRIPT);
3233 } else {
3234 Log.e(LOGTAG, "Unknown URL value for the \"axs\" URL parameter: " + axsParameterValue);
3235 }
3236 }
3237
3238 /**
3239 * Ensures the instance of the {@link AccessibilityInjector} to be present ot not.
3240 *
3241 * @param present True to ensure an insance, false to ensure no instance.
3242 */
3243 private void ensureAccessibilityScriptInjectorInstance(boolean present) {
3244 if (present && mAccessibilityInjector == null) {
3245 mAccessibilityInjector = new AccessibilityInjector(this);
3246 } else {
Svetoslav Ganovda355512010-05-12 22:04:44 -07003247 mAccessibilityInjector = null;
3248 }
Leon Scroggins405d7852009-11-02 14:50:54 -08003249 }
3250
3251 /**
Svetoslav Ganov585f13f8d2010-08-10 07:59:15 -07003252 * Gets the "axs" URL parameter value.
3253 *
3254 * @param url A url to fetch the paramter from.
3255 * @return The parameter value if such, -1 otherwise.
3256 */
3257 private int getAxsUrlParameterValue(String url) {
3258 if (mMatchAxsUrlParameterPattern == null) {
3259 mMatchAxsUrlParameterPattern = Pattern.compile(PATTERN_MATCH_AXS_URL_PARAMETER);
3260 }
3261 Matcher matcher = mMatchAxsUrlParameterPattern.matcher(url);
3262 if (matcher.find()) {
3263 String keyValuePair = url.substring(matcher.start(), matcher.end());
3264 return Integer.parseInt(keyValuePair.split("=")[1]);
3265 }
3266 return -1;
3267 }
3268
3269 /**
Leon Scroggins405d7852009-11-02 14:50:54 -08003270 * The URL of a page that sent a message to scroll the title bar off screen.
3271 *
3272 * Many mobile sites tell the page to scroll to (0,1) in order to scroll the
3273 * title bar off the screen. Sometimes, the scroll position is set before
3274 * the page finishes loading. Rather than scrolling while the page is still
3275 * loading, keep track of the URL and new scroll position so we can perform
3276 * the scroll once the page finishes loading.
3277 */
3278 private String mPageThatNeedsToSlideTitleBarOffScreen;
3279
3280 /**
3281 * The destination Y scroll position to be used when the page finishes
3282 * loading. See mPageThatNeedsToSlideTitleBarOffScreen.
3283 */
3284 private int mYDistanceToSlideTitleOffScreen;
3285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003286 // scale from content to view coordinates, and pin
Leon Scroggins83d4ba82009-09-17 17:27:13 -04003287 // return true if pin caused the final x/y different than the request cx/cy,
3288 // and a future scroll may reach the request cx/cy after our size has
3289 // changed
3290 // return false if the view scroll to the exact position as it is requested,
3291 // where negative numbers are taken to mean 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003292 private boolean setContentScrollTo(int cx, int cy) {
3293 if (mDrawHistory) {
3294 // disallow WebView to change the scroll position as History Picture
3295 // is used in the view system.
3296 // One known case where this is called is that WebCore tries to
3297 // restore the scroll position. As history Picture already uses the
3298 // saved scroll position, it is ok to skip this.
3299 return false;
3300 }
Leon Scrogginsd7b95aa2009-09-21 13:27:02 -04003301 int vx;
3302 int vy;
3303 if ((cx | cy) == 0) {
3304 // If the page is being scrolled to (0,0), do not add in the title
3305 // bar's height, and simply scroll to (0,0). (The only other work
3306 // in contentToView_ is to multiply, so this would not change 0.)
3307 vx = 0;
3308 vy = 0;
3309 } else {
3310 vx = contentToViewX(cx);
3311 vy = contentToViewY(cy);
3312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003313// Log.d(LOGTAG, "content scrollTo [" + cx + " " + cy + "] view=[" +
3314// vx + " " + vy + "]");
Leon Scroggins03c87bf2009-09-18 15:05:59 -04003315 // Some mobile sites attempt to scroll the title bar off the page by
Leon Scrogginsd7b95aa2009-09-21 13:27:02 -04003316 // scrolling to (0,1). If we are at the top left corner of the
Leon Scroggins03c87bf2009-09-18 15:05:59 -04003317 // page, assume this is an attempt to scroll off the title bar, and
3318 // animate the title bar off screen slowly enough that the user can see
3319 // it.
Leon Scroggins405d7852009-11-02 14:50:54 -08003320 if (cx == 0 && cy == 1 && mScrollX == 0 && mScrollY == 0
3321 && mTitleBar != null) {
3322 // FIXME: 100 should be defined somewhere as our max progress.
3323 if (getProgress() < 100) {
3324 // Wait to scroll the title bar off screen until the page has
3325 // finished loading. Keep track of the URL and the destination
3326 // Y position
3327 mPageThatNeedsToSlideTitleBarOffScreen = getUrl();
3328 mYDistanceToSlideTitleOffScreen = vy;
3329 } else {
3330 pinScrollTo(vx, vy, true, SLIDE_TITLE_DURATION);
3331 }
Leon Scroggins03c87bf2009-09-18 15:05:59 -04003332 // Since we are animating, we have not yet reached the desired
3333 // scroll position. Do not return true to request another attempt
3334 return false;
3335 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003336 pinScrollTo(vx, vy, false, 0);
Leon Scroggins83d4ba82009-09-17 17:27:13 -04003337 // If the request was to scroll to a negative coordinate, treat it as if
3338 // it was a request to scroll to 0
3339 if ((mScrollX != vx && cx >= 0) || (mScrollY != vy && cy >= 0)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003340 return true;
3341 } else {
3342 return false;
3343 }
3344 }
3345
3346 // scale from content to view coordinates, and pin
3347 private void spawnContentScrollTo(int cx, int cy) {
3348 if (mDrawHistory) {
3349 // disallow WebView to change the scroll position as History Picture
3350 // is used in the view system.
3351 return;
3352 }
Leon Scroggins0236e672009-09-02 21:12:08 -04003353 int vx = contentToViewX(cx);
3354 int vy = contentToViewY(cy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003355 pinScrollTo(vx, vy, true, 0);
3356 }
3357
3358 /**
3359 * These are from webkit, and are in content coordinate system (unzoomed)
3360 */
3361 private void contentSizeChanged(boolean updateLayout) {
3362 // suppress 0,0 since we usually see real dimensions soon after
3363 // this avoids drawing the prev content in a funny place. If we find a
3364 // way to consolidate these notifications, this check may become
3365 // obsolete
3366 if ((mContentWidth | mContentHeight) == 0) {
3367 return;
3368 }
3369
3370 if (mHeightCanMeasure) {
Mike Reede8853fc2009-09-04 14:01:48 -04003371 if (getMeasuredHeight() != contentToViewDimension(mContentHeight)
Grace Kloba3f9faf42009-10-13 14:13:54 -07003372 || updateLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003373 requestLayout();
3374 }
3375 } else if (mWidthCanMeasure) {
Mike Reede8853fc2009-09-04 14:01:48 -04003376 if (getMeasuredWidth() != contentToViewDimension(mContentWidth)
Grace Kloba3f9faf42009-10-13 14:13:54 -07003377 || updateLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003378 requestLayout();
3379 }
3380 } else {
3381 // If we don't request a layout, try to send our view size to the
3382 // native side to ensure that WebCore has the correct dimensions.
Derek Sollenberger03e48912010-05-18 17:03:42 -04003383 sendViewSizeZoom(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003384 }
3385 }
3386
3387 /**
3388 * Set the WebViewClient that will receive various notifications and
3389 * requests. This will replace the current handler.
3390 * @param client An implementation of WebViewClient.
3391 */
3392 public void setWebViewClient(WebViewClient client) {
3393 mCallbackProxy.setWebViewClient(client);
3394 }
3395
3396 /**
Grace Kloba94ab3b62009-10-07 18:00:19 -07003397 * Gets the WebViewClient
3398 * @return the current WebViewClient instance.
3399 *
3400 *@hide pending API council approval.
3401 */
3402 public WebViewClient getWebViewClient() {
3403 return mCallbackProxy.getWebViewClient();
3404 }
3405
3406 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003407 * Register the interface to be used when content can not be handled by
3408 * the rendering engine, and should be downloaded instead. This will replace
3409 * the current handler.
3410 * @param listener An implementation of DownloadListener.
3411 */
3412 public void setDownloadListener(DownloadListener listener) {
3413 mCallbackProxy.setDownloadListener(listener);
3414 }
3415
3416 /**
3417 * Set the chrome handler. This is an implementation of WebChromeClient for
3418 * use in handling Javascript dialogs, favicons, titles, and the progress.
3419 * This will replace the current handler.
3420 * @param client An implementation of WebChromeClient.
3421 */
3422 public void setWebChromeClient(WebChromeClient client) {
3423 mCallbackProxy.setWebChromeClient(client);
3424 }
3425
3426 /**
Andrei Popescu6fa29582009-06-19 14:54:09 +01003427 * Gets the chrome handler.
3428 * @return the current WebChromeClient instance.
3429 *
3430 * @hide API council approval.
3431 */
3432 public WebChromeClient getWebChromeClient() {
3433 return mCallbackProxy.getWebChromeClient();
3434 }
3435
3436 /**
Patrick Scott0b2e84b2010-03-02 08:58:44 -05003437 * Set the back/forward list client. This is an implementation of
3438 * WebBackForwardListClient for handling new items and changes in the
3439 * history index.
3440 * @param client An implementation of WebBackForwardListClient.
3441 * {@hide}
3442 */
3443 public void setWebBackForwardListClient(WebBackForwardListClient client) {
3444 mCallbackProxy.setWebBackForwardListClient(client);
3445 }
3446
3447 /**
3448 * Gets the WebBackForwardListClient.
3449 * {@hide}
3450 */
3451 public WebBackForwardListClient getWebBackForwardListClient() {
3452 return mCallbackProxy.getWebBackForwardListClient();
3453 }
3454
3455 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003456 * Set the Picture listener. This is an interface used to receive
3457 * notifications of a new Picture.
3458 * @param listener An implementation of WebView.PictureListener.
3459 */
3460 public void setPictureListener(PictureListener listener) {
3461 mPictureListener = listener;
3462 }
3463
3464 /**
3465 * {@hide}
3466 */
3467 /* FIXME: Debug only! Remove for SDK! */
3468 public void externalRepresentation(Message callback) {
3469 mWebViewCore.sendMessage(EventHub.REQUEST_EXT_REPRESENTATION, callback);
3470 }
3471
3472 /**
3473 * {@hide}
3474 */
3475 /* FIXME: Debug only! Remove for SDK! */
3476 public void documentAsText(Message callback) {
3477 mWebViewCore.sendMessage(EventHub.REQUEST_DOC_AS_TEXT, callback);
3478 }
3479
3480 /**
3481 * Use this function to bind an object to Javascript so that the
3482 * methods can be accessed from Javascript.
3483 * <p><strong>IMPORTANT:</strong>
3484 * <ul>
3485 * <li> Using addJavascriptInterface() allows JavaScript to control your
3486 * application. This can be a very useful feature or a dangerous security
3487 * issue. When the HTML in the WebView is untrustworthy (for example, part
3488 * or all of the HTML is provided by some person or process), then an
3489 * attacker could inject HTML that will execute your code and possibly any
3490 * code of the attacker's choosing.<br>
3491 * Do not use addJavascriptInterface() unless all of the HTML in this
3492 * WebView was written by you.</li>
3493 * <li> The Java object that is bound runs in another thread and not in
3494 * the thread that it was constructed in.</li>
3495 * </ul></p>
Steve Block544295e2010-12-02 18:40:06 +00003496 * @param obj The class instance to bind to Javascript, null instances are
3497 * ignored.
3498 * @param interfaceName The name to used to expose the class in JavaScript.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003499 */
3500 public void addJavascriptInterface(Object obj, String interfaceName) {
Steve Block544295e2010-12-02 18:40:06 +00003501 if (obj == null) {
3502 return;
3503 }
Cary Clarkded054c2009-06-15 10:26:08 -04003504 WebViewCore.JSInterfaceData arg = new WebViewCore.JSInterfaceData();
3505 arg.mObject = obj;
3506 arg.mInterfaceName = interfaceName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003507 mWebViewCore.sendMessage(EventHub.ADD_JS_INTERFACE, arg);
3508 }
3509
3510 /**
3511 * Return the WebSettings object used to control the settings for this
3512 * WebView.
3513 * @return A WebSettings object that can be used to control this WebView's
3514 * settings.
3515 */
3516 public WebSettings getSettings() {
Derek Sollenberger90b6e482010-05-10 12:38:54 -04003517 return (mWebViewCore != null) ? mWebViewCore.getSettings() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003518 }
3519
3520 /**
3521 * Return the list of currently loaded plugins.
3522 * @return The list of currently loaded plugins.
Andrei Popescu385df692009-08-13 11:59:57 +01003523 *
3524 * @deprecated This was used for Gears, which has been deprecated.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003525 */
Andrei Popescu385df692009-08-13 11:59:57 +01003526 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003527 public static synchronized PluginList getPluginList() {
Grace Klobabb245ea2009-11-10 13:13:24 -08003528 return new PluginList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003529 }
3530
3531 /**
Andrei Popescu385df692009-08-13 11:59:57 +01003532 * @deprecated This was used for Gears, which has been deprecated.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003533 */
Andrei Popescu385df692009-08-13 11:59:57 +01003534 @Deprecated
3535 public void refreshPlugins(boolean reloadOpenPages) { }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003536
3537 //-------------------------------------------------------------------------
3538 // Override View methods
3539 //-------------------------------------------------------------------------
3540
3541 @Override
3542 protected void finalize() throws Throwable {
Cary Clark9a4c0632009-08-10 16:40:08 -04003543 try {
3544 destroy();
3545 } finally {
3546 super.finalize();
3547 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003548 }
Cary Clarkd6982c92009-05-29 11:02:22 -04003549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003550 @Override
Leon Scroggins0236e672009-09-02 21:12:08 -04003551 protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
3552 if (child == mTitleBar) {
3553 // When drawing the title bar, move it horizontally to always show
Adam Powell9d32d242010-03-29 16:02:07 -07003554 // at the top of the WebView.
Leon Scroggins0236e672009-09-02 21:12:08 -04003555 mTitleBar.offsetLeftAndRight(mScrollX - mTitleBar.getLeft());
3556 }
3557 return super.drawChild(canvas, child, drawingTime);
3558 }
3559
Mike Reed19f3f0e2009-11-12 12:50:20 -05003560 private void drawContent(Canvas canvas) {
Grace Kloba04b28682009-09-14 14:38:37 -07003561 // Update the buttons in the picture, so when we draw the picture
3562 // to the screen, they are in the correct state.
3563 // Tell the native side if user is a) touching the screen,
3564 // b) pressing the trackball down, or c) pressing the enter key
3565 // If the cursor is on a button, we need to draw it in the pressed
3566 // state.
3567 // If mNativeClass is 0, we should not reach here, so we do not
3568 // need to check it again.
3569 nativeRecordButtons(hasFocus() && hasWindowFocus(),
Mike Reed19f3f0e2009-11-12 12:50:20 -05003570 mTouchMode == TOUCH_SHORTPRESS_START_MODE
3571 || mTrackballDown || mGotCenterDown, false);
Grace Kloba04b28682009-09-14 14:38:37 -07003572 drawCoreAndCursorRing(canvas, mBackgroundColor, mDrawCursorRing);
Mike Reed19f3f0e2009-11-12 12:50:20 -05003573 }
3574
Adam Powell637d3372010-08-25 14:37:03 -07003575 /**
3576 * Draw the background when beyond bounds
3577 * @param canvas Canvas to draw into
3578 */
3579 private void drawOverScrollBackground(Canvas canvas) {
3580 if (mOverScrollBackground == null) {
3581 mOverScrollBackground = new Paint();
3582 Bitmap bm = BitmapFactory.decodeResource(
3583 mContext.getResources(),
3584 com.android.internal.R.drawable.status_bar_background);
3585 mOverScrollBackground.setShader(new BitmapShader(bm,
3586 Shader.TileMode.REPEAT, Shader.TileMode.REPEAT));
3587 mOverScrollBorder = new Paint();
3588 mOverScrollBorder.setStyle(Paint.Style.STROKE);
3589 mOverScrollBorder.setStrokeWidth(0);
3590 mOverScrollBorder.setColor(0xffbbbbbb);
3591 }
3592
3593 int top = 0;
3594 int right = computeRealHorizontalScrollRange();
3595 int bottom = top + computeRealVerticalScrollRange();
3596 // first draw the background and anchor to the top of the view
3597 canvas.save();
3598 canvas.translate(mScrollX, mScrollY);
3599 canvas.clipRect(-mScrollX, top - mScrollY, right - mScrollX, bottom
3600 - mScrollY, Region.Op.DIFFERENCE);
3601 canvas.drawPaint(mOverScrollBackground);
3602 canvas.restore();
3603 // then draw the border
3604 canvas.drawRect(-1, top - 1, right, bottom, mOverScrollBorder);
3605 // next clip the region for the content
3606 canvas.clipRect(0, top, right, bottom);
3607 }
3608
Mike Reed19f3f0e2009-11-12 12:50:20 -05003609 @Override
3610 protected void onDraw(Canvas canvas) {
3611 // if mNativeClass is 0, the WebView has been destroyed. Do nothing.
3612 if (mNativeClass == 0) {
3613 return;
3614 }
3615
Grace Klobae47ac472010-03-11 14:53:07 -08003616 // if both mContentWidth and mContentHeight are 0, it means there is no
3617 // valid Picture passed to WebView yet. This can happen when WebView
3618 // just starts. Draw the background and return.
3619 if ((mContentWidth | mContentHeight) == 0 && mHistoryPicture == null) {
3620 canvas.drawColor(mBackgroundColor);
3621 return;
3622 }
3623
Mike Reed19f3f0e2009-11-12 12:50:20 -05003624 int saveCount = canvas.save();
Adam Powell637d3372010-08-25 14:37:03 -07003625 if (mInOverScrollMode && !getSettings()
3626 .getUseWebViewBackgroundForOverscrollBackground()) {
3627 drawOverScrollBackground(canvas);
3628 }
Mike Reed19f3f0e2009-11-12 12:50:20 -05003629 if (mTitleBar != null) {
3630 canvas.translate(0, (int) mTitleBar.getHeight());
3631 }
Bjorn Bringertc9332fa2010-10-13 17:24:27 +01003632 drawContent(canvas);
Leon Scroggins0236e672009-09-02 21:12:08 -04003633 canvas.restoreToCount(saveCount);
Cary Clarkd6982c92009-05-29 11:02:22 -04003634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003635 if (AUTO_REDRAW_HACK && mAutoRedraw) {
3636 invalidate();
3637 }
Leon Scroggins56426252010-11-01 15:45:37 -04003638 if (inEditingMode()) {
3639 mWebTextView.onDrawSubstitute();
3640 }
Nicolas Roard38863332010-01-04 19:30:55 +00003641 mWebViewCore.signalRepaintDone();
Grace Kloba178db412010-05-18 22:22:23 -07003642
Adam Powell637d3372010-08-25 14:37:03 -07003643 if (mOverScrollGlow != null && mOverScrollGlow.drawEdgeGlows(canvas)) {
3644 invalidate();
3645 }
3646
Grace Kloba178db412010-05-18 22:22:23 -07003647 // paint the highlight in the end
3648 if (!mTouchHighlightRegion.isEmpty()) {
3649 if (mTouchHightlightPaint == null) {
3650 mTouchHightlightPaint = new Paint();
3651 mTouchHightlightPaint.setColor(mHightlightColor);
3652 mTouchHightlightPaint.setAntiAlias(true);
3653 mTouchHightlightPaint.setPathEffect(new CornerPathEffect(
3654 TOUCH_HIGHLIGHT_ARC));
3655 }
3656 canvas.drawPath(mTouchHighlightRegion.getBoundaryPath(),
3657 mTouchHightlightPaint);
3658 }
3659 if (DEBUG_TOUCH_HIGHLIGHT) {
3660 if (getSettings().getNavDump()) {
3661 if ((mTouchHighlightX | mTouchHighlightY) != 0) {
3662 if (mTouchCrossHairColor == null) {
3663 mTouchCrossHairColor = new Paint();
3664 mTouchCrossHairColor.setColor(Color.RED);
3665 }
3666 canvas.drawLine(mTouchHighlightX - mNavSlop,
3667 mTouchHighlightY - mNavSlop, mTouchHighlightX
3668 + mNavSlop + 1, mTouchHighlightY + mNavSlop
3669 + 1, mTouchCrossHairColor);
3670 canvas.drawLine(mTouchHighlightX + mNavSlop + 1,
3671 mTouchHighlightY - mNavSlop, mTouchHighlightX
3672 - mNavSlop,
3673 mTouchHighlightY + mNavSlop + 1,
3674 mTouchCrossHairColor);
3675 }
3676 }
3677 }
3678 }
3679
3680 private void removeTouchHighlight(boolean removePendingMessage) {
3681 if (removePendingMessage) {
3682 mWebViewCore.removeMessages(EventHub.GET_TOUCH_HIGHLIGHT_RECTS);
3683 }
3684 mWebViewCore.sendMessage(EventHub.REMOVE_TOUCH_HIGHLIGHT_RECTS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003685 }
3686
3687 @Override
3688 public void setLayoutParams(ViewGroup.LayoutParams params) {
3689 if (params.height == LayoutParams.WRAP_CONTENT) {
3690 mWrapContent = true;
3691 }
3692 super.setLayoutParams(params);
3693 }
3694
3695 @Override
3696 public boolean performLongClick() {
Grace Kloba98e6fcf2010-01-27 15:20:30 -08003697 // performLongClick() is the result of a delayed message. If we switch
3698 // to windows overview, the WebView will be temporarily removed from the
3699 // view system. In that case, do nothing.
3700 if (getParent() == null) return false;
Adam Powellbe366682010-09-12 12:47:04 -07003701
3702 // A multi-finger gesture can look like a long press; make sure we don't take
3703 // long press actions if we're scaling.
3704 final ScaleGestureDetector detector = mZoomManager.getMultiTouchGestureDetector();
3705 if (detector != null && detector.isInProgress()) {
3706 return false;
3707 }
3708
Leon Scroggins3ccd3652009-06-26 17:22:50 -04003709 if (mNativeClass != 0 && nativeCursorIsTextInput()) {
3710 // Send the click so that the textfield is in focus
Leon Scroggins1d96ca02009-10-23 11:49:03 -04003711 centerKeyPressOnTextField();
Leon Scroggins3ccd3652009-06-26 17:22:50 -04003712 rebuildWebTextView();
Leon Scroggins2c8e0512010-05-11 15:50:27 -04003713 } else {
Leon Scroggins2aed7762010-08-13 17:11:42 -04003714 clearTextEntry();
Leon Scroggins3ccd3652009-06-26 17:22:50 -04003715 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003716 if (inEditingMode()) {
Leon Scrogginsd3465f62009-06-02 10:57:54 -04003717 return mWebTextView.performLongClick();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003718 }
Cary Clark1e8e10d2010-11-17 13:49:25 -05003719 if (mSelectingText) return false; // long click does nothing on selection
Cary Clark924af702010-06-04 16:37:43 -04003720 /* if long click brings up a context menu, the super function
3721 * returns true and we're done. Otherwise, nothing happened when
3722 * the user clicked. */
3723 if (super.performLongClick()) {
3724 return true;
3725 }
3726 /* In the case where the application hasn't already handled the long
3727 * click action, look for a word under the click. If one is found,
3728 * animate the text selection into view.
3729 * FIXME: no animation code yet */
Cary Clarkfc8bf742010-11-22 11:02:29 -05003730 return selectText();
3731 }
3732
3733 /**
3734 * Select the word at the last click point.
3735 *
3736 * @hide pending API council approval
3737 */
3738 public boolean selectText() {
Cary Clark924af702010-06-04 16:37:43 -04003739 int x = viewToContentX((int) mLastTouchX + mScrollX);
3740 int y = viewToContentY((int) mLastTouchY + mScrollY);
3741 setUpSelect();
3742 if (mNativeClass != 0 && nativeWordSelection(x, y)) {
3743 nativeSetExtendSelection();
Cary Clark4debfcb2010-11-05 14:20:32 -04003744 mDrawSelectionPointer = false;
Cary Clark4a2fe172010-12-01 09:16:29 -05003745 mSelectionStarted = true;
3746 mTouchMode = TOUCH_DRAG_MODE;
Cary Clark924af702010-06-04 16:37:43 -04003747 return true;
3748 }
Leon Scrogginsfe026bd2010-08-24 14:16:09 -04003749 selectionDone();
Cary Clark924af702010-06-04 16:37:43 -04003750 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003751 }
3752
Cary Clarkc5cd5e92010-11-22 15:20:02 -05003753 private int mOrientation = Configuration.ORIENTATION_UNDEFINED;
3754
3755 @Override
3756 protected void onConfigurationChanged(Configuration newConfig) {
3757 if (mSelectingText && mOrientation != newConfig.orientation) {
3758 selectionDone();
3759 }
3760 mOrientation = newConfig.orientation;
3761 }
3762
Leon Scrogginsfe026bd2010-08-24 14:16:09 -04003763 /**
3764 * Keep track of the Callback so we can end its ActionMode or remove its
3765 * titlebar.
3766 */
3767 private SelectActionModeCallback mSelectCallback;
3768
Leon Scrogginsc35f4ac2010-11-10 08:59:05 -05003769 /**
3770 * Check to see if the focused textfield/textarea is still on screen. If it
3771 * is, update the the dimensions and location of WebTextView. Otherwise,
3772 * remove the WebTextView. Should be called when the zoom level changes.
3773 * @param allowIntersect Whether to consider the textfield/textarea on
3774 * screen if it only intersects the screen (as opposed to being
3775 * completely on screen).
3776 * @return boolean True if the textfield/textarea is still on screen and the
3777 * dimensions/location of WebTextView have been updated.
3778 */
3779 private boolean didUpdateWebTextViewDimensions(boolean allowIntersect) {
Cary Clark5da9aeb2009-10-06 17:40:53 -04003780 Rect contentBounds = nativeFocusCandidateNodeBounds();
3781 Rect vBox = contentToViewRect(contentBounds);
3782 Rect visibleRect = new Rect();
3783 calcOurVisibleRect(visibleRect);
Leon Scrogginsbcbf5642010-02-17 17:56:51 -05003784 // If the textfield is on screen, place the WebTextView in
3785 // its new place, accounting for our new scroll/zoom values,
3786 // and adjust its textsize.
3787 if (allowIntersect ? Rect.intersects(visibleRect, vBox)
3788 : visibleRect.contains(vBox)) {
Cary Clark5da9aeb2009-10-06 17:40:53 -04003789 mWebTextView.setRect(vBox.left, vBox.top, vBox.width(),
3790 vBox.height());
Leon Scrogginsc35f4ac2010-11-10 08:59:05 -05003791 mWebTextView.updateTextSize();
3792 updateWebTextViewPadding();
Cary Clark5da9aeb2009-10-06 17:40:53 -04003793 return true;
3794 } else {
Leon Scrogginsecfc0eb2009-11-19 13:47:46 -05003795 // The textfield is now off screen. The user probably
3796 // was not zooming to see the textfield better. Remove
3797 // the WebTextView. If the user types a key, and the
3798 // textfield is still in focus, we will reconstruct
3799 // the WebTextView and scroll it back on screen.
3800 mWebTextView.remove();
Cary Clark5da9aeb2009-10-06 17:40:53 -04003801 return false;
3802 }
3803 }
3804
Nicolas Roard67a9f2a2010-09-07 14:49:06 -07003805 void setBaseLayer(int layer, Rect invalRect) {
3806 if (mNativeClass == 0)
3807 return;
3808 if (invalRect == null) {
3809 Rect rect = new Rect(0, 0, mContentWidth, mContentHeight);
3810 nativeSetBaseLayer(layer, rect);
3811 } else {
3812 nativeSetBaseLayer(layer, invalRect);
3813 }
3814 }
3815
Derek Sollenberger293c3602010-06-04 10:44:48 -04003816 private void onZoomAnimationStart() {
3817 // If it is in password mode, turn it off so it does not draw misplaced.
3818 if (inEditingMode() && nativeFocusCandidateIsPassword()) {
3819 mWebTextView.setInPassword(false);
3820 }
3821 }
3822
3823 private void onZoomAnimationEnd() {
3824 // adjust the edit text view if needed
Leon Scrogginsc35f4ac2010-11-10 08:59:05 -05003825 if (inEditingMode() && didUpdateWebTextViewDimensions(false)
3826 && nativeFocusCandidateIsPassword()) {
Derek Sollenberger293c3602010-06-04 10:44:48 -04003827 // If it is a password field, start drawing the WebTextView once
3828 // again.
3829 mWebTextView.setInPassword(true);
3830 }
3831 }
3832
3833 void onFixedLengthZoomAnimationStart() {
3834 WebViewCore.pauseUpdatePicture(getWebViewCore());
3835 onZoomAnimationStart();
3836 }
3837
3838 void onFixedLengthZoomAnimationEnd() {
Cary Clark0df02692010-11-24 11:01:37 -05003839 if (!mSelectingText) {
3840 WebViewCore.resumeUpdatePicture(mWebViewCore);
3841 }
Derek Sollenberger293c3602010-06-04 10:44:48 -04003842 onZoomAnimationEnd();
3843 }
3844
Grace Kloba8abd50b2010-07-08 15:02:14 -07003845 private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG |
3846 Paint.DITHER_FLAG |
3847 Paint.SUBPIXEL_TEXT_FLAG;
3848 private static final int SCROLL_BITS = Paint.FILTER_BITMAP_FLAG |
3849 Paint.DITHER_FLAG;
3850
3851 private final DrawFilter mZoomFilter =
3852 new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG);
3853 // If we need to trade better quality for speed, set mScrollFilter to null
3854 private final DrawFilter mScrollFilter =
3855 new PaintFlagsDrawFilter(SCROLL_BITS, 0);
3856
Cary Clarkd6982c92009-05-29 11:02:22 -04003857 private void drawCoreAndCursorRing(Canvas canvas, int color,
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04003858 boolean drawCursorRing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003859 if (mDrawHistory) {
Derek Sollenbergerbffa8512010-06-10 14:24:03 -04003860 canvas.scale(mZoomManager.getScale(), mZoomManager.getScale());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003861 canvas.drawPicture(mHistoryPicture);
3862 return;
3863 }
Grace Kloba8abd50b2010-07-08 15:02:14 -07003864 if (mNativeClass == 0) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003865
Derek Sollenberger293c3602010-06-04 10:44:48 -04003866 boolean animateZoom = mZoomManager.isFixedLengthAnimationInProgress();
Grace Klobac2242f22010-03-05 14:00:26 -08003867 boolean animateScroll = ((!mScroller.isFinished()
Cary Clark25415e22009-10-12 13:41:28 -04003868 || mVelocityTracker != null)
3869 && (mTouchMode != TOUCH_DRAG_MODE ||
Grace Klobac2242f22010-03-05 14:00:26 -08003870 mHeldMotionless != MOTIONLESS_TRUE))
3871 || mDeferTouchMode == TOUCH_DRAG_MODE;
Cary Clark25415e22009-10-12 13:41:28 -04003872 if (mTouchMode == TOUCH_DRAG_MODE) {
3873 if (mHeldMotionless == MOTIONLESS_PENDING) {
3874 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
3875 mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
3876 mHeldMotionless = MOTIONLESS_FALSE;
3877 }
3878 if (mHeldMotionless == MOTIONLESS_FALSE) {
3879 mPrivateHandler.sendMessageDelayed(mPrivateHandler
3880 .obtainMessage(DRAG_HELD_MOTIONLESS), MOTIONLESS_TIME);
3881 mHeldMotionless = MOTIONLESS_PENDING;
3882 }
3883 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003884 if (animateZoom) {
Derek Sollenberger293c3602010-06-04 10:44:48 -04003885 mZoomManager.animateZoom(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003886 } else {
Derek Sollenbergerbffa8512010-06-10 14:24:03 -04003887 canvas.scale(mZoomManager.getScale(), mZoomManager.getScale());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 }
3889
Nicolas Roardcc2c8422010-04-19 19:08:55 -07003890 boolean UIAnimationsRunning = false;
3891 // Currently for each draw we compute the animation values;
3892 // We may in the future decide to do that independently.
3893 if (mNativeClass != 0 && nativeEvaluateLayersAnimations()) {
3894 UIAnimationsRunning = true;
3895 // If we have unfinished (or unstarted) animations,
3896 // we ask for a repaint.
3897 invalidate();
3898 }
Grace Kloba8abd50b2010-07-08 15:02:14 -07003899
Cary Clark2ec30692010-02-23 10:50:38 -05003900 // decide which adornments to draw
3901 int extras = DRAW_EXTRAS_NONE;
3902 if (mFindIsUp) {
Cary Clark924af702010-06-04 16:37:43 -04003903 extras = DRAW_EXTRAS_FIND;
3904 } else if (mSelectingText) {
3905 extras = DRAW_EXTRAS_SELECTION;
3906 nativeSetSelectionPointer(mDrawSelectionPointer,
3907 mZoomManager.getInvScale(),
3908 mSelectX, mSelectY - getTitleHeight());
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04003909 } else if (drawCursorRing) {
Cary Clark2ec30692010-02-23 10:50:38 -05003910 extras = DRAW_EXTRAS_CURSOR_RING;
3911 }
Cary Clark6f5dfc62010-11-11 13:09:20 -05003912 if (DebugFlags.WEB_VIEW) {
3913 Log.v(LOGTAG, "mFindIsUp=" + mFindIsUp
3914 + " mSelectingText=" + mSelectingText
3915 + " nativePageShouldHandleShiftAndArrows()="
3916 + nativePageShouldHandleShiftAndArrows()
3917 + " animateZoom=" + animateZoom
3918 + " extras=" + extras);
3919 }
Nicolas Roard67a9f2a2010-09-07 14:49:06 -07003920
3921 if (canvas.isHardwareAccelerated()) {
3922 try {
3923 if (canvas.acquireContext()) {
Nicolas Roard12c18e62010-10-13 20:14:31 -07003924 Rect rect = new Rect(mGLRectViewport.left,
3925 mGLRectViewport.top,
3926 mGLRectViewport.right,
3927 mGLRectViewport.bottom
3928 - getVisibleTitleHeight());
Nicolas Roard67a9f2a2010-09-07 14:49:06 -07003929 if (nativeDrawGL(rect, getScale(), extras)) {
3930 invalidate();
3931 }
3932 }
3933 } finally {
3934 canvas.releaseContext();
3935 }
3936 } else {
3937 DrawFilter df = null;
3938 if (mZoomManager.isZoomAnimating() || UIAnimationsRunning) {
3939 df = mZoomFilter;
3940 } else if (animateScroll) {
3941 df = mScrollFilter;
3942 }
3943 canvas.setDrawFilter(df);
3944 int content = nativeDraw(canvas, color, extras, true);
3945 canvas.setDrawFilter(null);
3946 if (content != 0) {
3947 mWebViewCore.sendMessage(EventHub.SPLIT_PICTURE_SET, content, 0);
3948 }
Grace Kloba8abd50b2010-07-08 15:02:14 -07003949 }
Cary Clark2ec30692010-02-23 10:50:38 -05003950
3951 if (extras == DRAW_EXTRAS_CURSOR_RING) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003952 if (mTouchMode == TOUCH_SHORTPRESS_START_MODE) {
3953 mTouchMode = TOUCH_SHORTPRESS_MODE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003954 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003955 }
Cary Clark5da9aeb2009-10-06 17:40:53 -04003956 if (mFocusSizeChanged) {
3957 mFocusSizeChanged = false;
Leon Scrogginsecfc0eb2009-11-19 13:47:46 -05003958 // If we are zooming, this will get handled above, when the zoom
3959 // finishes. We also do not need to do this unless the WebTextView
3960 // is showing.
3961 if (!animateZoom && inEditingMode()) {
Leon Scrogginsc35f4ac2010-11-10 08:59:05 -05003962 didUpdateWebTextViewDimensions(true);
Leon Scrogginsecfc0eb2009-11-19 13:47:46 -05003963 }
Cary Clark5da9aeb2009-10-06 17:40:53 -04003964 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003965 }
3966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003967 // draw history
3968 private boolean mDrawHistory = false;
3969 private Picture mHistoryPicture = null;
3970 private int mHistoryWidth = 0;
3971 private int mHistoryHeight = 0;
3972
3973 // Only check the flag, can be called from WebCore thread
3974 boolean drawHistory() {
3975 return mDrawHistory;
3976 }
3977
Derek Sollenberger341e22f2010-06-02 12:34:34 -04003978 int getHistoryPictureWidth() {
3979 return (mHistoryPicture != null) ? mHistoryPicture.getWidth() : 0;
3980 }
3981
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003982 // Should only be called in UI thread
3983 void switchOutDrawHistory() {
3984 if (null == mWebViewCore) return; // CallbackProxy may trigger this
Grace Kloba8abd50b2010-07-08 15:02:14 -07003985 if (mDrawHistory && (getProgress() == 100 || nativeHasContent())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003986 mDrawHistory = false;
Patrick Scottda9a22b2010-04-08 08:32:52 -04003987 mHistoryPicture = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003988 invalidate();
3989 int oldScrollX = mScrollX;
3990 int oldScrollY = mScrollY;
3991 mScrollX = pinLocX(mScrollX);
3992 mScrollY = pinLocY(mScrollY);
3993 if (oldScrollX != mScrollX || oldScrollY != mScrollY) {
3994 mUserScroll = false;
3995 mWebViewCore.sendMessage(EventHub.SYNC_SCROLL, oldScrollX,
3996 oldScrollY);
Grace Kloba327dce92010-04-02 15:38:55 -07003997 onScrollChanged(mScrollX, mScrollY, oldScrollX, oldScrollY);
3998 } else {
3999 sendOurVisibleRect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004000 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004001 }
4002 }
4003
Cary Clarkd6982c92009-05-29 11:02:22 -04004004 WebViewCore.CursorData cursorData() {
4005 WebViewCore.CursorData result = new WebViewCore.CursorData();
4006 result.mMoveGeneration = nativeMoveGeneration();
4007 result.mFrame = nativeCursorFramePointer();
Cary Clarked56eda2009-06-18 09:48:47 -04004008 Point position = nativeCursorPosition();
4009 result.mX = position.x;
4010 result.mY = position.y;
Cary Clarkd6982c92009-05-29 11:02:22 -04004011 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004012 }
Cary Clarkd6982c92009-05-29 11:02:22 -04004013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004014 /**
4015 * Delete text from start to end in the focused textfield. If there is no
Cary Clarkd6982c92009-05-29 11:02:22 -04004016 * focus, or if start == end, silently fail. If start and end are out of
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004017 * order, swap them.
4018 * @param start Beginning of selection to delete.
4019 * @param end End of selection to delete.
4020 */
4021 /* package */ void deleteSelection(int start, int end) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07004022 mTextGeneration++;
Leon Scroggins6679f2f2009-08-12 18:48:10 -04004023 WebViewCore.TextSelectionData data
4024 = new WebViewCore.TextSelectionData(start, end);
4025 mWebViewCore.sendMessage(EventHub.DELETE_SELECTION, mTextGeneration, 0,
4026 data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004027 }
4028
4029 /**
4030 * Set the selection to (start, end) in the focused textfield. If start and
4031 * end are out of order, swap them.
4032 * @param start Beginning of selection.
4033 * @param end End of selection.
4034 */
4035 /* package */ void setSelection(int start, int end) {
Leon Scrogginsacea08d2010-05-27 15:09:32 -04004036 if (mWebViewCore != null) {
4037 mWebViewCore.sendMessage(EventHub.SET_SELECTION, start, end);
4038 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004039 }
4040
Derek Sollenberger7cabb032010-01-21 10:37:38 -05004041 @Override
4042 public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4043 InputConnection connection = super.onCreateInputConnection(outAttrs);
4044 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_FULLSCREEN;
4045 return connection;
4046 }
4047
Leon Scroggins04e0a102010-01-08 16:19:27 -05004048 /**
4049 * Called in response to a message from webkit telling us that the soft
4050 * keyboard should be launched.
4051 */
Derek Sollenberger4c41e8d2009-06-29 13:49:27 -04004052 private void displaySoftKeyboard(boolean isTextView) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004053 InputMethodManager imm = (InputMethodManager)
4054 getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
Derek Sollenberger4c41e8d2009-06-29 13:49:27 -04004055
Shimeng (Simon) Wang7924a4a2010-09-14 13:20:46 -07004056 // bring it back to the default level scale so that user can enter text
Shimeng (Simon) Wang6c09ef02010-09-09 13:56:34 -07004057 boolean zoom = mZoomManager.getScale() < mZoomManager.getDefaultScale();
Leon Scrogginse3844ee2010-02-23 15:15:16 -05004058 if (zoom) {
Derek Sollenberger03e48912010-05-18 17:03:42 -04004059 mZoomManager.setZoomCenter(mLastTouchX, mLastTouchY);
Shimeng (Simon) Wang6c09ef02010-09-09 13:56:34 -07004060 mZoomManager.setZoomScale(mZoomManager.getDefaultScale(), false);
Leon Scrogginse3844ee2010-02-23 15:15:16 -05004061 }
Derek Sollenberger4c41e8d2009-06-29 13:49:27 -04004062 if (isTextView) {
Leon Scroggins04e0a102010-01-08 16:19:27 -05004063 rebuildWebTextView();
Leon Scrogginse3844ee2010-02-23 15:15:16 -05004064 if (inEditingMode()) {
4065 imm.showSoftInput(mWebTextView, 0);
4066 if (zoom) {
Leon Scrogginsc35f4ac2010-11-10 08:59:05 -05004067 didUpdateWebTextViewDimensions(true);
Leon Scrogginse3844ee2010-02-23 15:15:16 -05004068 }
4069 return;
Grace Kloba8b97e4b2009-07-28 13:11:38 -07004070 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004071 }
Leon Scroggins200c13d2010-05-14 15:35:42 -04004072 // Used by plugins and contentEditable.
Leon Scrogginse3844ee2010-02-23 15:15:16 -05004073 // Also used if the navigation cache is out of date, and
4074 // does not recognize that a textfield is in focus. In that
4075 // case, use WebView as the targeted view.
4076 // see http://b/issue?id=2457459
4077 imm.showSoftInput(this, 0);
Derek Sollenberger4c41e8d2009-06-29 13:49:27 -04004078 }
4079
4080 // Called by WebKit to instruct the UI to hide the keyboard
4081 private void hideSoftKeyboard() {
Leon Scrogginsf2e17a82010-09-24 15:58:50 -04004082 InputMethodManager imm = InputMethodManager.peekInstance();
4083 if (imm != null && (imm.isActive(this)
4084 || (inEditingMode() && imm.isActive(mWebTextView)))) {
Leon Scroggins III71d17e42010-09-02 12:53:08 -04004085 imm.hideSoftInputFromWindow(this.getWindowToken(), 0);
4086 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004087 }
4088
Leon Scrogginsd3465f62009-06-02 10:57:54 -04004089 /*
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04004090 * This method checks the current focus and cursor and potentially rebuilds
Leon Scrogginsd3465f62009-06-02 10:57:54 -04004091 * mWebTextView to have the appropriate properties, such as password,
4092 * multiline, and what text it contains. It also removes it if necessary.
4093 */
Leon Scroggins01058282009-07-30 16:33:56 -04004094 /* package */ void rebuildWebTextView() {
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04004095 // If the WebView does not have focus, do nothing until it gains focus.
Grace Kloba04b28682009-09-14 14:38:37 -07004096 if (!hasFocus() && (null == mWebTextView || !mWebTextView.hasFocus())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004097 return;
4098 }
4099 boolean alreadyThere = inEditingMode();
Leon Scrogginsd3465f62009-06-02 10:57:54 -04004100 // inEditingMode can only return true if mWebTextView is non-null,
Leon Scroggins2ca912e2009-04-28 16:51:55 -04004101 // so we can safely call remove() if (alreadyThere)
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04004102 if (0 == mNativeClass || !nativeFocusCandidateIsTextInput()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004103 if (alreadyThere) {
Leon Scrogginsd3465f62009-06-02 10:57:54 -04004104 mWebTextView.remove();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004105 }
4106 return;
4107 }
Leon Scroggins2ca912e2009-04-28 16:51:55 -04004108 // At this point, we know we have found an input field, so go ahead
Leon Scrogginsd3465f62009-06-02 10:57:54 -04004109 // and create the WebTextView if necessary.
4110 if (mWebTextView == null) {
Ben Murdochdb8d19c2010-10-29 11:44:17 +01004111 mWebTextView = new WebTextView(mContext, WebView.this, mAutoFillData.getQueryId());
Leon Scroggins2ca912e2009-04-28 16:51:55 -04004112 // Initialize our generation number.
4113 mTextGeneration = 0;
4114 }
Leon Scrogginsc35f4ac2010-11-10 08:59:05 -05004115 mWebTextView.updateTextSize();
Cary Clark3524be92009-06-22 13:09:11 -04004116 Rect visibleRect = new Rect();
4117 calcOurContentVisibleRect(visibleRect);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004118 // Note that sendOurVisibleRect calls viewToContent, so the coordinates
4119 // should be in content coordinates.
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04004120 Rect bounds = nativeFocusCandidateNodeBounds();
Leon Scroggins6be3bf22009-12-08 13:43:47 -05004121 Rect vBox = contentToViewRect(bounds);
4122 mWebTextView.setRect(vBox.left, vBox.top, vBox.width(), vBox.height());
Cary Clarkd6982c92009-05-29 11:02:22 -04004123 if (!Rect.intersects(bounds, visibleRect)) {
Leon Scroggins40981262009-07-01 10:57:47 -04004124 mWebTextView.bringIntoView();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004125 }
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04004126 String text = nativeFocusCandidateText();
4127 int nodePointer = nativeFocusCandidatePointer();
Leon Scrogginsd3465f62009-06-02 10:57:54 -04004128 if (alreadyThere && mWebTextView.isSameTextField(nodePointer)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004129 // It is possible that we have the same textfield, but it has moved,
4130 // i.e. In the case of opening/closing the screen.
4131 // In that case, we need to set the dimensions, but not the other
4132 // aspects.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004133 // If the text has been changed by webkit, update it. However, if
4134 // there has been more UI text input, ignore it. We will receive
4135 // another update when that text is recognized.
Leon Scroggins6be3bf22009-12-08 13:43:47 -05004136 if (text != null && !text.equals(mWebTextView.getText().toString())
Cary Clarkd6982c92009-05-29 11:02:22 -04004137 && nativeTextGeneration() == mTextGeneration) {
Leon Scrogginsd3465f62009-06-02 10:57:54 -04004138 mWebTextView.setTextAndKeepSelection(text);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004139 }
4140 } else {
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04004141 mWebTextView.setGravity(nativeFocusCandidateIsRtlText() ?
4142 Gravity.RIGHT : Gravity.NO_GRAVITY);
Leon Scrogginsaa7b9d72009-12-07 13:38:07 -05004143 // This needs to be called before setType, which may call
4144 // requestFormData, and it needs to have the correct nodePointer.
Leon Scrogginsd3465f62009-06-02 10:57:54 -04004145 mWebTextView.setNodePointer(nodePointer);
Leon Scrogginsaa7b9d72009-12-07 13:38:07 -05004146 mWebTextView.setType(nativeFocusCandidateType());
Leon Scrogginsc35f4ac2010-11-10 08:59:05 -05004147 updateWebTextViewPadding();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004148 if (null == text) {
Cary Clark243ea062009-06-25 10:49:32 -04004149 if (DebugFlags.WEB_VIEW) {
4150 Log.v(LOGTAG, "rebuildWebTextView null == text");
4151 }
Leon Scrogginsbb107bd2009-10-23 16:18:42 -04004152 text = "";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004153 }
Leon Scrogginsbb107bd2009-10-23 16:18:42 -04004154 mWebTextView.setTextAndKeepSelection(text);
Leon Scroggins5c84bf02010-02-09 17:03:44 -05004155 InputMethodManager imm = InputMethodManager.peekInstance();
4156 if (imm != null && imm.isActive(mWebTextView)) {
4157 imm.restartInput(mWebTextView);
4158 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004159 }
Leon Scrogginsf8ca2d72010-10-21 17:14:42 -04004160 if (isFocused()) {
4161 mWebTextView.requestFocus();
4162 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004163 }
4164
Leon Scrogginsaa7b9d72009-12-07 13:38:07 -05004165 /**
Leon Scrogginsc35f4ac2010-11-10 08:59:05 -05004166 * Update the padding of mWebTextView based on the native textfield/textarea
4167 */
4168 void updateWebTextViewPadding() {
4169 Rect paddingRect = nativeFocusCandidatePaddingRect();
4170 if (paddingRect != null) {
4171 // Use contentToViewDimension since these are the dimensions of
4172 // the padding.
4173 mWebTextView.setPadding(
4174 contentToViewDimension(paddingRect.left),
4175 contentToViewDimension(paddingRect.top),
4176 contentToViewDimension(paddingRect.right),
4177 contentToViewDimension(paddingRect.bottom));
4178 }
4179 }
4180
4181 /**
Leon Scroggins200c13d2010-05-14 15:35:42 -04004182 * Tell webkit to put the cursor on screen.
4183 */
4184 /* package */ void revealSelection() {
4185 if (mWebViewCore != null) {
4186 mWebViewCore.sendMessage(EventHub.REVEAL_SELECTION);
4187 }
4188 }
4189
4190 /**
Leon Scrogginsaa7b9d72009-12-07 13:38:07 -05004191 * Called by WebTextView to find saved form data associated with the
4192 * textfield
4193 * @param name Name of the textfield.
4194 * @param nodePointer Pointer to the node of the textfield, so it can be
4195 * compared to the currently focused textfield when the data is
4196 * retrieved.
Ben Murdoch62275a42010-09-07 11:27:28 +01004197 * @param autoFillable true if WebKit has determined this field is part of
4198 * a form that can be auto filled.
Leon Scrogginsaa7b9d72009-12-07 13:38:07 -05004199 */
Ben Murdoch62275a42010-09-07 11:27:28 +01004200 /* package */ void requestFormData(String name, int nodePointer, boolean autoFillable) {
Leon Scrogginsaa7b9d72009-12-07 13:38:07 -05004201 if (mWebViewCore.getSettings().getSaveFormData()) {
4202 Message update = mPrivateHandler.obtainMessage(REQUEST_FORM_DATA);
4203 update.arg1 = nodePointer;
4204 RequestFormData updater = new RequestFormData(name, getUrl(),
Ben Murdoch62275a42010-09-07 11:27:28 +01004205 update, autoFillable);
Leon Scrogginsaa7b9d72009-12-07 13:38:07 -05004206 Thread t = new Thread(updater);
4207 t.start();
4208 }
4209 }
4210
Leon Scroggins3a503392010-01-06 17:04:38 -05004211 /**
4212 * Pass a message to find out the <label> associated with the <input>
4213 * identified by nodePointer
4214 * @param framePointer Pointer to the frame containing the <input> node
4215 * @param nodePointer Pointer to the node for which a <label> is desired.
4216 */
4217 /* package */ void requestLabel(int framePointer, int nodePointer) {
4218 mWebViewCore.sendMessage(EventHub.REQUEST_LABEL, framePointer,
4219 nodePointer);
4220 }
4221
Leon Scrogginsd3465f62009-06-02 10:57:54 -04004222 /*
4223 * This class requests an Adapter for the WebTextView which shows past
4224 * entries stored in the database. It is a Runnable so that it can be done
4225 * in its own thread, without slowing down the UI.
4226 */
4227 private class RequestFormData implements Runnable {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004228 private String mName;
4229 private String mUrl;
4230 private Message mUpdateMessage;
Ben Murdoch62275a42010-09-07 11:27:28 +01004231 private boolean mAutoFillable;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004232
Ben Murdoch62275a42010-09-07 11:27:28 +01004233 public RequestFormData(String name, String url, Message msg, boolean autoFillable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004234 mName = name;
4235 mUrl = url;
4236 mUpdateMessage = msg;
Ben Murdoch62275a42010-09-07 11:27:28 +01004237 mAutoFillable = autoFillable;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004238 }
4239
4240 public void run() {
Ben Murdoch62275a42010-09-07 11:27:28 +01004241 ArrayList<String> pastEntries = new ArrayList();
4242
4243 if (mAutoFillable) {
4244 // Note that code inside the adapter click handler in WebTextView depends
4245 // on the AutoFill item being at the top of the drop down list. If you change
4246 // the order, make sure to do it there too!
Ben Murdoch57914382010-11-16 11:50:39 +00004247 WebSettings settings = getSettings();
4248 if (settings != null && settings.getAutoFillProfile() != null) {
4249 pastEntries.add(getResources().getText(
4250 com.android.internal.R.string.autofill_this_form).toString() +
4251 " " +
4252 mAutoFillData.getPreviewString());
4253 mWebTextView.setAutoFillProfileIsSet(true);
4254 } else {
4255 // There is no autofill profile set up yet, so add an option that
4256 // will invite the user to set their profile up.
4257 pastEntries.add(getResources().getText(
4258 com.android.internal.R.string.setup_autofill).toString());
4259 mWebTextView.setAutoFillProfileIsSet(false);
4260 }
Ben Murdoch62275a42010-09-07 11:27:28 +01004261 }
4262
4263 pastEntries.addAll(mDatabase.getFormData(mUrl, mName));
4264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004265 if (pastEntries.size() > 0) {
4266 AutoCompleteAdapter adapter = new
4267 AutoCompleteAdapter(mContext, pastEntries);
Cary Clarkded054c2009-06-15 10:26:08 -04004268 mUpdateMessage.obj = adapter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004269 mUpdateMessage.sendToTarget();
4270 }
4271 }
4272 }
4273
Grace Kloba8ae1b412009-11-23 10:35:34 -08004274 /**
4275 * Dump the display tree to "/sdcard/displayTree.txt"
4276 *
4277 * @hide debug only
4278 */
4279 public void dumpDisplayTree() {
4280 nativeDumpDisplayTree(getUrl());
4281 }
4282
4283 /**
4284 * Dump the dom tree to adb shell if "toFile" is False, otherwise dump it to
4285 * "/sdcard/domTree.txt"
4286 *
4287 * @hide debug only
4288 */
4289 public void dumpDomTree(boolean toFile) {
4290 mWebViewCore.sendMessage(EventHub.DUMP_DOMTREE, toFile ? 1 : 0, 0);
4291 }
4292
4293 /**
4294 * Dump the render tree to adb shell if "toFile" is False, otherwise dump it
4295 * to "/sdcard/renderTree.txt"
4296 *
4297 * @hide debug only
4298 */
4299 public void dumpRenderTree(boolean toFile) {
4300 mWebViewCore.sendMessage(EventHub.DUMP_RENDERTREE, toFile ? 1 : 0, 0);
4301 }
4302
Andrei Popescu5e7bb0a2010-02-01 22:32:16 +00004303 /**
Steve Block68dede32010-08-04 10:28:46 +01004304 * Called by DRT on UI thread, need to proxy to WebCore thread.
4305 *
4306 * @hide debug only
4307 */
4308 public void useMockDeviceOrientation() {
4309 mWebViewCore.sendMessage(EventHub.USE_MOCK_DEVICE_ORIENTATION);
4310 }
4311
4312 /**
4313 * Called by DRT on WebCore thread.
4314 *
4315 * @hide debug only
4316 */
4317 public void setMockDeviceOrientation(boolean canProvideAlpha, double alpha,
4318 boolean canProvideBeta, double beta, boolean canProvideGamma, double gamma) {
Steve Blockf4a705f2010-08-11 13:08:24 +01004319 mWebViewCore.setMockDeviceOrientation(canProvideAlpha, alpha, canProvideBeta, beta,
4320 canProvideGamma, gamma);
Steve Block68dede32010-08-04 10:28:46 +01004321 }
4322
4323 /**
Andrei Popescu5e7bb0a2010-02-01 22:32:16 +00004324 * Dump the V8 counters to standard output.
4325 * Note that you need a build with V8 and WEBCORE_INSTRUMENTATION set to
4326 * true. Otherwise, this will do nothing.
4327 *
4328 * @hide debug only
4329 */
4330 public void dumpV8Counters() {
4331 mWebViewCore.sendMessage(EventHub.DUMP_V8COUNTERS);
4332 }
4333
Leon Scrogginse3225672009-06-03 15:53:13 -04004334 // This is used to determine long press with the center key. Does not
4335 // affect long press with the trackball/touch.
4336 private boolean mGotCenterDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004337
4338 @Override
Derek Sollenbergerff0f9732010-08-06 11:50:49 -04004339 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4340 // send complex characters to webkit for use by JS and plugins
4341 if (keyCode == KeyEvent.KEYCODE_UNKNOWN && event.getCharacters() != null) {
4342 // pass the key to DOM
4343 mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
4344 mWebViewCore.sendMessage(EventHub.KEY_UP, event);
4345 // return true as DOM handles the key
4346 return true;
4347 }
4348 return false;
4349 }
4350
4351 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004352 public boolean onKeyDown(int keyCode, KeyEvent event) {
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04004353 if (DebugFlags.WEB_VIEW) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004354 Log.v(LOGTAG, "keyDown at " + System.currentTimeMillis()
Cary Clark215b72c2009-06-26 14:38:43 -04004355 + ", " + event + ", unicode=" + event.getUnicodeChar());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004356 }
4357
4358 if (mNativeClass == 0) {
4359 return false;
4360 }
4361
4362 // do this hack up front, so it always works, regardless of touch-mode
4363 if (AUTO_REDRAW_HACK && (keyCode == KeyEvent.KEYCODE_CALL)) {
4364 mAutoRedraw = !mAutoRedraw;
4365 if (mAutoRedraw) {
4366 invalidate();
4367 }
4368 return true;
4369 }
4370
4371 // Bubble up the key event if
4372 // 1. it is a system key; or
Grace Kloba04b28682009-09-14 14:38:37 -07004373 // 2. the host application wants to handle it;
Svetoslav Ganovda355512010-05-12 22:04:44 -07004374 // 3. the accessibility injector is present and wants to handle it;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004375 if (event.isSystem()
Svetoslav Ganovda355512010-05-12 22:04:44 -07004376 || mCallbackProxy.uiOverrideKeyEvent(event)
4377 || (mAccessibilityInjector != null && mAccessibilityInjector.onKeyEvent(event))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004378 return false;
4379 }
4380
Leon Scroggins7a375872010-03-09 14:26:07 -05004381 if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
4382 || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) {
Svetoslav Ganov9b756ac2010-11-05 15:42:22 -07004383 if (!pageShouldHandleShiftAndArrows() && !nativeCursorWantsKeyEvents()
4384 && !mSelectingText) {
Cary Clark924af702010-06-04 16:37:43 -04004385 setUpSelect();
Leon Scroggins7a375872010-03-09 14:26:07 -05004386 }
Cary Clark09e383c2009-10-26 16:43:58 -04004387 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004388
Chih-Wei Huang4e916ad2010-06-10 09:56:47 +08004389 if (keyCode == KeyEvent.KEYCODE_PAGE_UP) {
4390 pageUp(false);
4391 return true;
4392 }
4393
4394 if (keyCode == KeyEvent.KEYCODE_PAGE_DOWN) {
4395 pageDown(false);
4396 return true;
4397 }
4398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004399 if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
4400 && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004401 switchOutDrawHistory();
Svetoslav Ganov585f13f8d2010-08-10 07:59:15 -07004402 if (pageShouldHandleShiftAndArrows()) {
Svetoslav Ganov9b756ac2010-11-05 15:42:22 -07004403 letPageHandleNavKey(keyCode, event.getEventTime(), true, event.getMetaState());
Leon Scrogginsb127c8f2010-03-05 15:42:17 -05004404 return true;
4405 }
Cary Clark924af702010-06-04 16:37:43 -04004406 if (mSelectingText) {
Cary Clarkc05af372009-10-16 10:52:27 -04004407 int xRate = keyCode == KeyEvent.KEYCODE_DPAD_LEFT
4408 ? -1 : keyCode == KeyEvent.KEYCODE_DPAD_RIGHT ? 1 : 0;
4409 int yRate = keyCode == KeyEvent.KEYCODE_DPAD_UP ?
4410 -1 : keyCode == KeyEvent.KEYCODE_DPAD_DOWN ? 1 : 0;
4411 int multiplier = event.getRepeatCount() + 1;
4412 moveSelection(xRate * multiplier, yRate * multiplier);
4413 return true;
4414 }
Leon Scrogginsb127c8f2010-03-05 15:42:17 -05004415 if (navHandledKey(keyCode, 1, false, event.getEventTime())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004416 playSoundEffect(keyCodeToSoundsEffect(keyCode));
4417 return true;
4418 }
4419 // Bubble up the key event as WebView doesn't handle it
4420 return false;
4421 }
4422
Leon Scrogginse3225672009-06-03 15:53:13 -04004423 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004424 switchOutDrawHistory();
4425 if (event.getRepeatCount() == 0) {
Cary Clark924af702010-06-04 16:37:43 -04004426 if (mSelectingText) {
Cary Clarkc05af372009-10-16 10:52:27 -04004427 return true; // discard press if copy in progress
4428 }
Leon Scrogginse3225672009-06-03 15:53:13 -04004429 mGotCenterDown = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004430 mPrivateHandler.sendMessageDelayed(mPrivateHandler
Leon Scrogginse3225672009-06-03 15:53:13 -04004431 .obtainMessage(LONG_PRESS_CENTER), LONG_PRESS_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004432 // Already checked mNativeClass, so we do not need to check it
4433 // again.
4434 nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true);
4435 return true;
4436 }
4437 // Bubble up the key event as WebView doesn't handle it
4438 return false;
4439 }
4440
Cary Clark843bbb82009-04-20 16:03:31 -04004441 if (keyCode != KeyEvent.KEYCODE_SHIFT_LEFT
4442 && keyCode != KeyEvent.KEYCODE_SHIFT_RIGHT) {
4443 // turn off copy select if a shift-key combo is pressed
Cary Clark924af702010-06-04 16:37:43 -04004444 selectionDone();
Cary Clark843bbb82009-04-20 16:03:31 -04004445 }
4446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004447 if (getSettings().getNavDump()) {
4448 switch (keyCode) {
4449 case KeyEvent.KEYCODE_4:
Grace Kloba8ae1b412009-11-23 10:35:34 -08004450 dumpDisplayTree();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004451 break;
4452 case KeyEvent.KEYCODE_5:
4453 case KeyEvent.KEYCODE_6:
Grace Kloba8ae1b412009-11-23 10:35:34 -08004454 dumpDomTree(keyCode == KeyEvent.KEYCODE_5);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004455 break;
4456 case KeyEvent.KEYCODE_7:
4457 case KeyEvent.KEYCODE_8:
Grace Kloba8ae1b412009-11-23 10:35:34 -08004458 dumpRenderTree(keyCode == KeyEvent.KEYCODE_7);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004459 break;
4460 case KeyEvent.KEYCODE_9:
4461 nativeInstrumentReport();
4462 return true;
4463 }
4464 }
4465
Derek Sollenberger718d69f2009-10-19 15:56:43 -04004466 if (nativeCursorIsTextInput()) {
Leon Scroggins1cc24202009-06-16 10:10:28 -04004467 // This message will put the node in focus, for the DOM's notion
Leon Scroggins0658e8f2009-06-26 14:09:09 -04004468 // of focus, and make the focuscontroller active
Leon Scroggins01058282009-07-30 16:33:56 -04004469 mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(),
4470 nativeCursorNodePointer());
Leon Scroggins0658e8f2009-06-26 14:09:09 -04004471 // This will bring up the WebTextView and put it in focus, for
4472 // our view system's notion of focus
4473 rebuildWebTextView();
4474 // Now we need to pass the event to it
Leon Scrogginsc66f68a2009-10-02 15:12:30 -04004475 if (inEditingMode()) {
Leon Scrogginsbb107bd2009-10-23 16:18:42 -04004476 mWebTextView.setDefaultSelection();
Leon Scrogginsbb107bd2009-10-23 16:18:42 -04004477 return mWebTextView.dispatchKeyEvent(event);
Leon Scrogginsc66f68a2009-10-02 15:12:30 -04004478 }
Leon Scroggins40981262009-07-01 10:57:47 -04004479 } else if (nativeHasFocusNode()) {
4480 // In this case, the cursor is not on a text input, but the focus
4481 // might be. Check it, and if so, hand over to the WebTextView.
4482 rebuildWebTextView();
4483 if (inEditingMode()) {
Leon Scroggins0aa341f2010-02-24 16:49:35 -05004484 mWebTextView.setDefaultSelection();
Leon Scrogginsbb107bd2009-10-23 16:18:42 -04004485 return mWebTextView.dispatchKeyEvent(event);
Leon Scroggins40981262009-07-01 10:57:47 -04004486 }
Cary Clark19436562009-06-04 16:25:07 -04004487 }
4488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004489 // TODO: should we pass all the keys to DOM or check the meta tag
Cary Clark2f1d60c2009-06-03 08:05:53 -04004490 if (nativeCursorWantsKeyEvents() || true) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004491 // pass the key to DOM
4492 mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
4493 // return true as DOM handles the key
4494 return true;
4495 }
4496
4497 // Bubble up the key event as WebView doesn't handle it
4498 return false;
4499 }
4500
4501 @Override
4502 public boolean onKeyUp(int keyCode, KeyEvent event) {
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04004503 if (DebugFlags.WEB_VIEW) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004504 Log.v(LOGTAG, "keyUp at " + System.currentTimeMillis()
Cary Clark215b72c2009-06-26 14:38:43 -04004505 + ", " + event + ", unicode=" + event.getUnicodeChar());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004506 }
4507
4508 if (mNativeClass == 0) {
4509 return false;
4510 }
4511
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04004512 // special CALL handling when cursor node's href is "tel:XXX"
Cary Clarkd6982c92009-05-29 11:02:22 -04004513 if (keyCode == KeyEvent.KEYCODE_CALL && nativeHasCursorNode()) {
4514 String text = nativeCursorText();
4515 if (!nativeCursorIsTextInput() && text != null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004516 && text.startsWith(SCHEME_TEL)) {
4517 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(text));
4518 getContext().startActivity(intent);
4519 return true;
4520 }
4521 }
4522
4523 // Bubble up the key event if
4524 // 1. it is a system key; or
4525 // 2. the host application wants to handle it;
Svetoslav Ganovda355512010-05-12 22:04:44 -07004526 // 3. the accessibility injector is present and wants to handle it;
4527 if (event.isSystem()
4528 || mCallbackProxy.uiOverrideKeyEvent(event)
4529 || (mAccessibilityInjector != null && mAccessibilityInjector.onKeyEvent(event))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004530 return false;
4531 }
4532
Cary Clarkd6982c92009-05-29 11:02:22 -04004533 if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004534 || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) {
Svetoslav Ganov9b756ac2010-11-05 15:42:22 -07004535 if (!pageShouldHandleShiftAndArrows() && copySelection()) {
Cary Clark924af702010-06-04 16:37:43 -04004536 selectionDone();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004537 return true;
4538 }
4539 }
4540
4541 if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
4542 && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
Svetoslav Ganov585f13f8d2010-08-10 07:59:15 -07004543 if (pageShouldHandleShiftAndArrows()) {
Svetoslav Ganov9b756ac2010-11-05 15:42:22 -07004544 letPageHandleNavKey(keyCode, event.getEventTime(), false, event.getMetaState());
Leon Scrogginsb127c8f2010-03-05 15:42:17 -05004545 return true;
4546 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004547 // always handle the navigation keys in the UI thread
4548 // Bubble up the key event as WebView doesn't handle it
4549 return false;
4550 }
4551
Leon Scrogginse3225672009-06-03 15:53:13 -04004552 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004553 // remove the long press message first
Leon Scrogginse3225672009-06-03 15:53:13 -04004554 mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
4555 mGotCenterDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004556
Cary Clark924af702010-06-04 16:37:43 -04004557 if (mSelectingText) {
Cary Clarkc05af372009-10-16 10:52:27 -04004558 if (mExtendSelection) {
Cary Clark924af702010-06-04 16:37:43 -04004559 copySelection();
4560 selectionDone();
Cary Clarkc05af372009-10-16 10:52:27 -04004561 } else {
4562 mExtendSelection = true;
Cary Clark924af702010-06-04 16:37:43 -04004563 nativeSetExtendSelection();
Cary Clark09e383c2009-10-26 16:43:58 -04004564 invalidate(); // draw the i-beam instead of the arrow
Cary Clarkc05af372009-10-16 10:52:27 -04004565 }
4566 return true; // discard press if copy in progress
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004567 }
Grace Klobadd817492009-09-14 10:17:06 -07004568
4569 // perform the single click
4570 Rect visibleRect = sendOurVisibleRect();
4571 // Note that sendOurVisibleRect calls viewToContent, so the
4572 // coordinates should be in content coordinates.
4573 if (!nativeCursorIntersects(visibleRect)) {
4574 return false;
4575 }
Grace Klobadd817492009-09-14 10:17:06 -07004576 WebViewCore.CursorData data = cursorData();
4577 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, data);
4578 playSoundEffect(SoundEffectConstants.CLICK);
Leon Scroggins1d60c5c2009-10-23 10:16:51 -04004579 if (nativeCursorIsTextInput()) {
4580 rebuildWebTextView();
Leon Scroggins1d96ca02009-10-23 11:49:03 -04004581 centerKeyPressOnTextField();
Leon Scrogginsbb107bd2009-10-23 16:18:42 -04004582 if (inEditingMode()) {
4583 mWebTextView.setDefaultSelection();
Leon Scrogginsbb107bd2009-10-23 16:18:42 -04004584 }
Leon Scroggins1d60c5c2009-10-23 10:16:51 -04004585 return true;
4586 }
Leon Scroggins2aed7762010-08-13 17:11:42 -04004587 clearTextEntry();
Cary Clarke60cb7f2010-08-25 14:56:00 -04004588 nativeShowCursorTimed();
Leon Scroggins1d60c5c2009-10-23 10:16:51 -04004589 if (!mCallbackProxy.uiOverrideUrlLoading(nativeCursorText())) {
Grace Klobadd817492009-09-14 10:17:06 -07004590 mWebViewCore.sendMessage(EventHub.CLICK, data.mFrame,
4591 nativeCursorNodePointer());
4592 }
Leon Scrogginse3225672009-06-03 15:53:13 -04004593 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004594 }
4595
4596 // TODO: should we pass all the keys to DOM or check the meta tag
Cary Clark2f1d60c2009-06-03 08:05:53 -04004597 if (nativeCursorWantsKeyEvents() || true) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004598 // pass the key to DOM
4599 mWebViewCore.sendMessage(EventHub.KEY_UP, event);
4600 // return true as DOM handles the key
4601 return true;
4602 }
4603
4604 // Bubble up the key event as WebView doesn't handle it
4605 return false;
4606 }
Cary Clarkd6982c92009-05-29 11:02:22 -04004607
Leon Scrogginsfe026bd2010-08-24 14:16:09 -04004608 private void setUpSelect() {
Cary Clark924af702010-06-04 16:37:43 -04004609 if (0 == mNativeClass) return; // client isn't initialized
4610 if (inFullScreenMode()) return;
4611 if (mSelectingText) return;
Cary Clark09e383c2009-10-26 16:43:58 -04004612 mExtendSelection = false;
Cary Clark924af702010-06-04 16:37:43 -04004613 mSelectingText = mDrawSelectionPointer = true;
4614 // don't let the picture change during text selection
4615 WebViewCore.pauseUpdatePicture(mWebViewCore);
4616 nativeResetSelection();
Cary Clark09e383c2009-10-26 16:43:58 -04004617 if (nativeHasCursorNode()) {
4618 Rect rect = nativeCursorNodeBounds();
4619 mSelectX = contentToViewX(rect.left);
4620 mSelectY = contentToViewY(rect.top);
4621 } else if (mLastTouchY > getVisibleTitleHeight()) {
4622 mSelectX = mScrollX + (int) mLastTouchX;
4623 mSelectY = mScrollY + (int) mLastTouchY;
4624 } else {
4625 mSelectX = mScrollX + getViewWidth() / 2;
4626 mSelectY = mScrollY + getViewHeightWithTitle() / 2;
4627 }
4628 nativeHideCursor();
Leon Scrogginsfe026bd2010-08-24 14:16:09 -04004629 mSelectCallback = new SelectActionModeCallback();
4630 mSelectCallback.setWebView(this);
Leon Scrogginsfe026bd2010-08-24 14:16:09 -04004631 startActionMode(mSelectCallback);
Cary Clark09e383c2009-10-26 16:43:58 -04004632 }
4633
Cary Clark966641a2010-03-04 08:41:56 -05004634 /**
4635 * Use this method to put the WebView into text selection mode.
4636 * Do not rely on this functionality; it will be deprecated in the future.
4637 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004638 public void emulateShiftHeld() {
Cary Clark924af702010-06-04 16:37:43 -04004639 setUpSelect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004640 }
4641
Cary Clark924af702010-06-04 16:37:43 -04004642 /**
Leon Scrogginsfe026bd2010-08-24 14:16:09 -04004643 * Select all of the text in this WebView.
Cary Clark924af702010-06-04 16:37:43 -04004644 */
Leon Scrogginsfe026bd2010-08-24 14:16:09 -04004645 void selectAll() {
Cary Clark924af702010-06-04 16:37:43 -04004646 if (0 == mNativeClass) return; // client isn't initialized
4647 if (inFullScreenMode()) return;
4648 if (!mSelectingText) setUpSelect();
4649 nativeSelectAll();
4650 mDrawSelectionPointer = false;
4651 mExtendSelection = true;
4652 invalidate();
4653 }
4654
4655 /**
Leon Scrogginsfe026bd2010-08-24 14:16:09 -04004656 * Called when the selection has been removed.
Cary Clark924af702010-06-04 16:37:43 -04004657 */
Leon Scrogginsfe026bd2010-08-24 14:16:09 -04004658 void selectionDone() {
Cary Clark924af702010-06-04 16:37:43 -04004659 if (mSelectingText) {
Leon Scrogginsfe026bd2010-08-24 14:16:09 -04004660 mSelectingText = false;
4661 // finish is idempotent, so this is fine even if selectionDone was
4662 // called by mSelectCallback.onDestroyActionMode
4663 mSelectCallback.finish();
4664 mSelectCallback = null;
Cary Clark0df02692010-11-24 11:01:37 -05004665 WebViewCore.resumePriority();
Leon Scrogginsfe026bd2010-08-24 14:16:09 -04004666 WebViewCore.resumeUpdatePicture(mWebViewCore);
Cary Clark924af702010-06-04 16:37:43 -04004667 invalidate(); // redraw without selection
Cary Clark6f5dfc62010-11-11 13:09:20 -05004668 mAutoScrollX = 0;
4669 mAutoScrollY = 0;
4670 mSentAutoScrollMessage = false;
Cary Clark924af702010-06-04 16:37:43 -04004671 }
4672 }
4673
4674 /**
Leon Scrogginsfe026bd2010-08-24 14:16:09 -04004675 * Copy the selection to the clipboard
Cary Clark924af702010-06-04 16:37:43 -04004676 */
Leon Scrogginsfe026bd2010-08-24 14:16:09 -04004677 boolean copySelection() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004678 boolean copiedSomething = false;
Cary Clark924af702010-06-04 16:37:43 -04004679 String selection = getSelection();
4680 if (selection != "") {
4681 if (DebugFlags.WEB_VIEW) {
4682 Log.v(LOGTAG, "copySelection \"" + selection + "\"");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004683 }
Cary Clark924af702010-06-04 16:37:43 -04004684 Toast.makeText(mContext
4685 , com.android.internal.R.string.text_copied
4686 , Toast.LENGTH_SHORT).show();
4687 copiedSomething = true;
Dianne Hackborn90d5e8c2010-08-05 13:47:55 -07004688 ClipboardManager cm = (ClipboardManager)getContext()
4689 .getSystemService(Context.CLIPBOARD_SERVICE);
4690 cm.setText(selection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004691 }
Cary Clark09e383c2009-10-26 16:43:58 -04004692 invalidate(); // remove selection region and pointer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004693 return copiedSomething;
4694 }
4695
Cary Clark924af702010-06-04 16:37:43 -04004696 /**
Leon Scrogginsfe026bd2010-08-24 14:16:09 -04004697 * Returns the currently highlighted text as a string.
Cary Clark924af702010-06-04 16:37:43 -04004698 */
Leon Scrogginsfe026bd2010-08-24 14:16:09 -04004699 String getSelection() {
Cary Clark924af702010-06-04 16:37:43 -04004700 if (mNativeClass == 0) return "";
4701 return nativeGetSelection();
4702 }
4703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004704 @Override
4705 protected void onAttachedToWindow() {
4706 super.onAttachedToWindow();
Grace Kloba9b95ab12010-04-01 16:07:30 -07004707 if (hasWindowFocus()) setActive(true);
Teng-Hui Zhua7f76872010-11-29 11:15:32 -08004708 final ViewTreeObserver treeObserver = getViewTreeObserver();
4709 if (treeObserver != null && mListener == null) {
4710 mListener = new InnerGlobalLayoutListener();
4711 treeObserver.addOnGlobalLayoutListener(mListener);
4712 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004713 }
4714
4715 @Override
4716 protected void onDetachedFromWindow() {
Leon Scroggins05919f22010-09-14 17:22:36 -04004717 clearHelpers();
Derek Sollenberger90b6e482010-05-10 12:38:54 -04004718 mZoomManager.dismissZoomPicker();
Grace Kloba9b95ab12010-04-01 16:07:30 -07004719 if (hasWindowFocus()) setActive(false);
Teng-Hui Zhua7f76872010-11-29 11:15:32 -08004720
4721 final ViewTreeObserver treeObserver = getViewTreeObserver();
4722 if (treeObserver != null && mListener != null) {
4723 treeObserver.removeGlobalOnLayoutListener(mListener);
4724 mListener = null;
4725 }
4726
Grace Kloba378f0282010-03-26 15:01:30 -07004727 super.onDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004728 }
Cary Clarkd6982c92009-05-29 11:02:22 -04004729
Steve Howard16bd9372010-04-12 14:46:09 -07004730 @Override
4731 protected void onVisibilityChanged(View changedView, int visibility) {
4732 super.onVisibilityChanged(changedView, visibility);
Derek Sollenbergerf39d2662010-06-24 16:41:04 -04004733 // The zoomManager may be null if the webview is created from XML that
4734 // specifies the view's visibility param as not visible (see http://b/2794841)
4735 if (visibility != View.VISIBLE && mZoomManager != null) {
Derek Sollenberger90b6e482010-05-10 12:38:54 -04004736 mZoomManager.dismissZoomPicker();
Steve Howard16bd9372010-04-12 14:46:09 -07004737 }
4738 }
4739
Leon Scrogginsa57632f2009-11-16 10:51:12 -05004740 /**
4741 * @deprecated WebView no longer needs to implement
4742 * ViewGroup.OnHierarchyChangeListener. This method does nothing now.
4743 */
4744 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004745 public void onChildViewAdded(View parent, View child) {}
Cary Clarkd6982c92009-05-29 11:02:22 -04004746
Leon Scrogginsa57632f2009-11-16 10:51:12 -05004747 /**
4748 * @deprecated WebView no longer needs to implement
4749 * ViewGroup.OnHierarchyChangeListener. This method does nothing now.
4750 */
4751 @Deprecated
4752 public void onChildViewRemoved(View p, View child) {}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004753
4754 /**
4755 * @deprecated WebView should not have implemented
4756 * ViewTreeObserver.OnGlobalFocusChangeListener. This method
4757 * does nothing now.
4758 */
4759 @Deprecated
4760 public void onGlobalFocusChanged(View oldFocus, View newFocus) {
4761 }
4762
Grace Kloba9b95ab12010-04-01 16:07:30 -07004763 private void setActive(boolean active) {
4764 if (active) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004765 if (hasFocus()) {
4766 // If our window regained focus, and we have focus, then begin
Leon Scrogginsfa03cde2009-06-15 15:48:46 -04004767 // drawing the cursor ring
Cary Clarkd6982c92009-05-29 11:02:22 -04004768 mDrawCursorRing = true;
Leon Scroggins2aed7762010-08-13 17:11:42 -04004769 setFocusControllerActive(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004770 if (mNativeClass != 0) {
4771 nativeRecordButtons(true, false, true);
4772 }
4773 } else {
Leon Scroggins2aed7762010-08-13 17:11:42 -04004774 if (!inEditingMode()) {
4775 // If our window gained focus, but we do not have it, do not
4776 // draw the cursor ring.
4777 mDrawCursorRing = false;
4778 setFocusControllerActive(false);
4779 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004780 // We do not call nativeRecordButtons here because we assume
4781 // that when we lost focus, or window focus, it got called with
4782 // false for the first parameter
4783 }
4784 } else {
Derek Sollenberger90b6e482010-05-10 12:38:54 -04004785 if (!mZoomManager.isZoomPickerVisible()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004786 /*
Derek Sollenberger90b6e482010-05-10 12:38:54 -04004787 * The external zoom controls come in their own window, so our
4788 * window loses focus. Our policy is to not draw the cursor ring
4789 * if our window is not focused, but this is an exception since
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004790 * the user can still navigate the web page with the zoom
4791 * controls showing.
4792 */
Cary Clarkd6982c92009-05-29 11:02:22 -04004793 mDrawCursorRing = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004794 }
4795 mGotKeyDown = false;
Grace Kloba378f0282010-03-26 15:01:30 -07004796 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
4797 mTouchMode = TOUCH_DONE_MODE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004798 if (mNativeClass != 0) {
4799 nativeRecordButtons(false, false, true);
4800 }
Leon Scroggins2aed7762010-08-13 17:11:42 -04004801 setFocusControllerActive(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004802 }
4803 invalidate();
Grace Kloba9b95ab12010-04-01 16:07:30 -07004804 }
4805
4806 // To avoid drawing the cursor ring, and remove the TextView when our window
4807 // loses focus.
4808 @Override
4809 public void onWindowFocusChanged(boolean hasWindowFocus) {
4810 setActive(hasWindowFocus);
4811 if (hasWindowFocus) {
Patrick Scott8a5d3352010-08-18 11:00:42 -04004812 JWebCoreJavaBridge.setActiveWebView(this);
Grace Kloba9b95ab12010-04-01 16:07:30 -07004813 } else {
Patrick Scott8a5d3352010-08-18 11:00:42 -04004814 JWebCoreJavaBridge.removeActiveWebView(this);
Grace Kloba9b95ab12010-04-01 16:07:30 -07004815 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004816 super.onWindowFocusChanged(hasWindowFocus);
4817 }
4818
Leon Scroggins63dda1c2009-04-15 13:25:00 -04004819 /*
Leon Scrogginsfa03cde2009-06-15 15:48:46 -04004820 * Pass a message to WebCore Thread, telling the WebCore::Page's
4821 * FocusController to be "inactive" so that it will
4822 * not draw the blinking cursor. It gets set to "active" to draw the cursor
4823 * in WebViewCore.cpp, when the WebCore thread receives key events/clicks.
Leon Scroggins63dda1c2009-04-15 13:25:00 -04004824 */
Leon Scroggins2aed7762010-08-13 17:11:42 -04004825 /* package */ void setFocusControllerActive(boolean active) {
4826 if (mWebViewCore == null) return;
4827 mWebViewCore.sendMessage(EventHub.SET_ACTIVE, active ? 1 : 0, 0);
Leon Scroggins63dda1c2009-04-15 13:25:00 -04004828 }
4829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004830 @Override
4831 protected void onFocusChanged(boolean focused, int direction,
4832 Rect previouslyFocusedRect) {
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04004833 if (DebugFlags.WEB_VIEW) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004834 Log.v(LOGTAG, "MT focusChanged " + focused + ", " + direction);
4835 }
4836 if (focused) {
4837 // When we regain focus, if we have window focus, resume drawing
Leon Scrogginsfa03cde2009-06-15 15:48:46 -04004838 // the cursor ring
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004839 if (hasWindowFocus()) {
Cary Clarkd6982c92009-05-29 11:02:22 -04004840 mDrawCursorRing = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004841 if (mNativeClass != 0) {
4842 nativeRecordButtons(true, false, true);
4843 }
Leon Scroggins2aed7762010-08-13 17:11:42 -04004844 setFocusControllerActive(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004845 //} else {
4846 // The WebView has gained focus while we do not have
4847 // windowfocus. When our window lost focus, we should have
4848 // called nativeRecordButtons(false...)
4849 }
4850 } else {
4851 // When we lost focus, unless focus went to the TextView (which is
Cary Clarkd6982c92009-05-29 11:02:22 -04004852 // true if we are in editing mode), stop drawing the cursor ring.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004853 if (!inEditingMode()) {
Cary Clarkd6982c92009-05-29 11:02:22 -04004854 mDrawCursorRing = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004855 if (mNativeClass != 0) {
4856 nativeRecordButtons(false, false, true);
4857 }
Leon Scroggins2aed7762010-08-13 17:11:42 -04004858 setFocusControllerActive(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004859 }
4860 mGotKeyDown = false;
4861 }
4862
4863 super.onFocusChanged(focused, direction, previouslyFocusedRect);
4864 }
4865
Nicolas Roard12c18e62010-10-13 20:14:31 -07004866 void setGLRectViewport() {
Teng-Hui Zhue6fb0f12010-11-23 16:37:45 -08004867 // Use the getGlobalVisibleRect() to get the intersection among the parents
4868 Rect webViewRect = new Rect();
4869 boolean visible = getGlobalVisibleRect(webViewRect);
4870
4871 // Then need to invert the Y axis, just for GL
4872 View rootView = getRootView();
4873 int rootViewHeight = rootView.getHeight();
4874 int savedWebViewBottom = webViewRect.bottom;
4875 webViewRect.bottom = rootViewHeight - webViewRect.top;
4876 webViewRect.top = rootViewHeight - savedWebViewBottom;
4877
4878 // Store the viewport
4879 mGLRectViewport = webViewRect;
Nicolas Roard12c18e62010-10-13 20:14:31 -07004880 }
4881
Grace Kloba3f9faf42009-10-13 14:13:54 -07004882 /**
4883 * @hide
4884 */
4885 @Override
4886 protected boolean setFrame(int left, int top, int right, int bottom) {
4887 boolean changed = super.setFrame(left, top, right, bottom);
4888 if (!changed && mHeightCanMeasure) {
4889 // When mHeightCanMeasure is true, we will set mLastHeightSent to 0
4890 // in WebViewCore after we get the first layout. We do call
4891 // requestLayout() when we get contentSizeChanged(). But the View
4892 // system won't call onSizeChanged if the dimension is not changed.
4893 // In this case, we need to call sendViewSizeZoom() explicitly to
4894 // notify the WebKit about the new dimensions.
Derek Sollenberger03e48912010-05-18 17:03:42 -04004895 sendViewSizeZoom(false);
Grace Kloba3f9faf42009-10-13 14:13:54 -07004896 }
Nicolas Roard12c18e62010-10-13 20:14:31 -07004897 setGLRectViewport();
Grace Kloba3f9faf42009-10-13 14:13:54 -07004898 return changed;
4899 }
4900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004901 @Override
4902 protected void onSizeChanged(int w, int h, int ow, int oh) {
4903 super.onSizeChanged(w, h, ow, oh);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004904
Grace Klobaa4fa1072009-11-09 12:01:50 -08004905 // adjust the max viewport width depending on the view dimensions. This
4906 // is to ensure the scaling is not going insane. So do not shrink it if
4907 // the view size is temporarily smaller, e.g. when soft keyboard is up.
Derek Sollenberger4aef6972010-06-24 15:03:43 -04004908 int newMaxViewportWidth = (int) (Math.max(w, h) / mZoomManager.getDefaultMinZoomScale());
Grace Klobaa4fa1072009-11-09 12:01:50 -08004909 if (newMaxViewportWidth > sMaxViewportWidth) {
4910 sMaxViewportWidth = newMaxViewportWidth;
4911 }
4912
Derek Sollenberger341e22f2010-06-02 12:34:34 -04004913 mZoomManager.onSizeChanged(w, h, ow, oh);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004914 }
4915
4916 @Override
4917 protected void onScrollChanged(int l, int t, int oldl, int oldt) {
4918 super.onScrollChanged(l, t, oldl, oldt);
Adam Powell637d3372010-08-25 14:37:03 -07004919 if (!mInOverScrollMode) {
4920 sendOurVisibleRect();
4921 // update WebKit if visible title bar height changed. The logic is same
4922 // as getVisibleTitleHeight.
4923 int titleHeight = getTitleHeight();
4924 if (Math.max(titleHeight - t, 0) != Math.max(titleHeight - oldt, 0)) {
4925 sendViewSizeZoom(false);
4926 }
Mike Reedb64f6f82010-03-23 10:29:37 -04004927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004928 }
Cary Clarkd6982c92009-05-29 11:02:22 -04004929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004930 @Override
4931 public boolean dispatchKeyEvent(KeyEvent event) {
4932 boolean dispatch = true;
4933
Leon Scroggins9ab32b62010-05-03 14:19:50 +01004934 // Textfields, plugins, and contentEditable nodes need to receive the
4935 // shift up key even if another key was released while the shift key
4936 // was held down.
4937 if (!inEditingMode() && (mNativeClass == 0
4938 || !nativePageShouldHandleShiftAndArrows())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004939 if (event.getAction() == KeyEvent.ACTION_DOWN) {
4940 mGotKeyDown = true;
4941 } else {
4942 if (!mGotKeyDown) {
4943 /*
4944 * We got a key up for which we were not the recipient of
4945 * the original key down. Don't give it to the view.
4946 */
4947 dispatch = false;
4948 }
4949 mGotKeyDown = false;
4950 }
4951 }
4952
4953 if (dispatch) {
4954 return super.dispatchKeyEvent(event);
4955 } else {
4956 // We didn't dispatch, so let something else handle the key
4957 return false;
4958 }
4959 }
4960
4961 // Here are the snap align logic:
4962 // 1. If it starts nearly horizontally or vertically, snap align;
4963 // 2. If there is a dramitic direction change, let it go;
4964 // 3. If there is a same direction back and forth, lock it.
4965
4966 // adjustable parameters
4967 private int mMinLockSnapReverseDistance;
4968 private static final float MAX_SLOPE_FOR_DIAG = 1.5f;
4969 private static final int MIN_BREAK_SNAP_CROSS_DISTANCE = 80;
4970
Grace Klobac2242f22010-03-05 14:00:26 -08004971 private boolean hitFocusedPlugin(int contentX, int contentY) {
Cary Clarke84a0db2010-03-17 15:58:20 -04004972 if (DebugFlags.WEB_VIEW) {
4973 Log.v(LOGTAG, "nativeFocusIsPlugin()=" + nativeFocusIsPlugin());
4974 Rect r = nativeFocusNodeBounds();
4975 Log.v(LOGTAG, "nativeFocusNodeBounds()=(" + r.left + ", " + r.top
4976 + ", " + r.right + ", " + r.bottom + ")");
4977 }
Grace Klobac2242f22010-03-05 14:00:26 -08004978 return nativeFocusIsPlugin()
Cary Clarke84a0db2010-03-17 15:58:20 -04004979 && nativeFocusNodeBounds().contains(contentX, contentY);
Grace Klobac2242f22010-03-05 14:00:26 -08004980 }
4981
4982 private boolean shouldForwardTouchEvent() {
4983 return mFullScreenHolder != null || (mForwardTouchEvents
Cary Clark924af702010-06-04 16:37:43 -04004984 && !mSelectingText
Grace Klobac2242f22010-03-05 14:00:26 -08004985 && mPreventDefault != PREVENT_DEFAULT_IGNORE);
4986 }
4987
4988 private boolean inFullScreenMode() {
4989 return mFullScreenHolder != null;
4990 }
4991
Derek Sollenbergerfa89c502010-10-01 11:19:36 -04004992 private void dismissFullScreenMode() {
4993 if (inFullScreenMode()) {
4994 mFullScreenHolder.dismiss();
4995 mFullScreenHolder = null;
4996 }
4997 }
4998
Derek Sollenberger293c3602010-06-04 10:44:48 -04004999 void onPinchToZoomAnimationStart() {
5000 // cancel the single touch handling
5001 cancelTouch();
5002 onZoomAnimationStart();
5003 }
5004
5005 void onPinchToZoomAnimationEnd(ScaleGestureDetector detector) {
5006 onZoomAnimationEnd();
5007 // start a drag, TOUCH_PINCH_DRAG, can't use TOUCH_INIT_MODE as
5008 // it may trigger the unwanted click, can't use TOUCH_DRAG_MODE
5009 // as it may trigger the unwanted fling.
5010 mTouchMode = TOUCH_PINCH_DRAG;
5011 mConfirmMove = true;
5012 startTouch(detector.getFocusX(), detector.getFocusY(), mLastTouchTime);
5013 }
5014
Patrick Scott4b903782010-11-30 08:14:05 -05005015 private void startScrollingLayer(float x, float y) {
Patrick Scotta3ebcc92010-07-16 11:52:22 -04005016 if (mTouchMode != TOUCH_DRAG_LAYER_MODE) {
Patrick Scott4b903782010-11-30 08:14:05 -05005017 int contentX = viewToContentX((int) x + mScrollX);
5018 int contentY = viewToContentY((int) y + mScrollY);
Patrick Scotta3ebcc92010-07-16 11:52:22 -04005019 mScrollingLayer = nativeScrollableLayer(contentX, contentY);
5020 if (mScrollingLayer != 0) {
5021 mTouchMode = TOUCH_DRAG_LAYER_MODE;
5022 }
5023 }
5024 }
5025
5026 // 1/(density * density) used to compute the distance between points.
5027 // Computed in init().
5028 private float DRAG_LAYER_INVERSE_DENSITY_SQUARED;
5029
5030 // The distance between two points reported in onTouchEvent scaled by the
5031 // density of the screen.
5032 private static final int DRAG_LAYER_FINGER_DISTANCE = 20000;
5033
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005034 @Override
5035 public boolean onTouchEvent(MotionEvent ev) {
Andy Stadlerb34fd1ff2010-09-27 15:51:09 -07005036 if (mNativeClass == 0 || (!isClickable() && !isLongClickable())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005037 return false;
5038 }
5039
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04005040 if (DebugFlags.WEB_VIEW) {
Huahui Wu41865f42010-09-02 13:41:41 -07005041 Log.v(LOGTAG, ev + " at " + ev.getEventTime()
5042 + " mTouchMode=" + mTouchMode
5043 + " numPointers=" + ev.getPointerCount());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005044 }
5045
Patrick Scotta3ebcc92010-07-16 11:52:22 -04005046 int action = ev.getAction();
5047 float x = ev.getX();
5048 float y = ev.getY();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005049 long eventTime = ev.getEventTime();
5050
Huahui Wu3ebb51d2010-11-11 16:02:17 -08005051 // mDeferMultitouch is a hack for layout tests, where it is used to
5052 // force passing multi-touch events to webkit.
5053 // FIXME: always pass multi-touch events to webkit and remove everything
5054 // related to mDeferMultitouch.
5055 if (ev.getPointerCount() > 1 &&
Patrick Scott4b903782010-11-30 08:14:05 -05005056 (mDeferMultitouch || mZoomManager.isZoomScaleFixed())) {
Huahui Wu41865f42010-09-02 13:41:41 -07005057 if (DebugFlags.WEB_VIEW) {
5058 Log.v(LOGTAG, "passing " + ev.getPointerCount() + " points to webkit");
5059 }
5060 passMultiTouchToWebKit(ev);
5061 return true;
5062 }
5063
Patrick Scott4b903782010-11-30 08:14:05 -05005064 final ScaleGestureDetector detector =
5065 mZoomManager.getMultiTouchGestureDetector();
5066
Patrick Scotta3ebcc92010-07-16 11:52:22 -04005067 if (mZoomManager.supportsMultiTouchZoom() && ev.getPointerCount() > 1 &&
Patrick Scott4b903782010-11-30 08:14:05 -05005068 mTouchMode != TOUCH_DRAG_LAYER_MODE) {
Patrick Scotta3ebcc92010-07-16 11:52:22 -04005069 if (!detector.isInProgress() &&
5070 ev.getActionMasked() != MotionEvent.ACTION_POINTER_DOWN) {
5071 // Insert a fake pointer down event in order to start
5072 // the zoom scale detector.
5073 MotionEvent temp = MotionEvent.obtain(ev);
5074 // Clear the original event and set it to
5075 // ACTION_POINTER_DOWN.
Adam Powellbe366682010-09-12 12:47:04 -07005076 try {
5077 temp.setAction(temp.getAction() &
5078 ~MotionEvent.ACTION_MASK |
5079 MotionEvent.ACTION_POINTER_DOWN);
5080 detector.onTouchEvent(temp);
5081 } finally {
5082 temp.recycle();
5083 }
Patrick Scotta3ebcc92010-07-16 11:52:22 -04005084 }
5085
Derek Sollenberger293c3602010-06-04 10:44:48 -04005086 detector.onTouchEvent(ev);
5087
5088 if (detector.isInProgress()) {
5089 mLastTouchTime = eventTime;
Adam Powellbe366682010-09-12 12:47:04 -07005090 cancelLongPress();
Adam Powell0a8bf862010-09-12 14:17:46 -07005091 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
Adam Powellbe366682010-09-12 12:47:04 -07005092 if (!mZoomManager.supportsPanDuringZoom()) {
5093 return true;
5094 }
5095 mTouchMode = TOUCH_DRAG_MODE;
5096 if (mVelocityTracker == null) {
5097 mVelocityTracker = VelocityTracker.obtain();
5098 }
Derek Sollenberger293c3602010-06-04 10:44:48 -04005099 }
5100
5101 x = detector.getFocusX();
5102 y = detector.getFocusY();
5103 action = ev.getAction() & MotionEvent.ACTION_MASK;
5104 if (action == MotionEvent.ACTION_POINTER_DOWN) {
5105 cancelTouch();
5106 action = MotionEvent.ACTION_DOWN;
5107 } else if (action == MotionEvent.ACTION_POINTER_UP) {
5108 // set mLastTouchX/Y to the remaining point
5109 mLastTouchX = x;
5110 mLastTouchY = y;
5111 } else if (action == MotionEvent.ACTION_MOVE) {
5112 // negative x or y indicate it is on the edge, skip it.
5113 if (x < 0 || y < 0) {
Grace Kloba3a0def22010-01-23 21:11:54 -08005114 return true;
5115 }
Grace Kloba3a0def22010-01-23 21:11:54 -08005116 }
Grace Kloba3a0def22010-01-23 21:11:54 -08005117 }
5118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005119 // Due to the touch screen edge effect, a touch closer to the edge
5120 // always snapped to the edge. As getViewWidth() can be different from
5121 // getWidth() due to the scrollbar, adjusting the point to match
5122 // getViewWidth(). Same applied to the height.
Patrick Scotta3ebcc92010-07-16 11:52:22 -04005123 x = Math.min(x, getViewWidth() - 1);
5124 y = Math.min(y, getViewHeightWithTitle() - 1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005125
Cary Clark25415e22009-10-12 13:41:28 -04005126 float fDeltaX = mLastTouchX - x;
5127 float fDeltaY = mLastTouchY - y;
5128 int deltaX = (int) fDeltaX;
5129 int deltaY = (int) fDeltaY;
Grace Klobac2242f22010-03-05 14:00:26 -08005130 int contentX = viewToContentX((int) x + mScrollX);
5131 int contentY = viewToContentY((int) y + mScrollY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005132
5133 switch (action) {
5134 case MotionEvent.ACTION_DOWN: {
Grace Klobac2242f22010-03-05 14:00:26 -08005135 mPreventDefault = PREVENT_DEFAULT_NO;
5136 mConfirmMove = false;
Cary Clarkb8491342010-11-29 16:23:19 -05005137 mInitialHitTestResult = null;
Grace Kloba04b28682009-09-14 14:38:37 -07005138 if (!mScroller.isFinished()) {
Cary Clark278ce052009-08-31 16:08:42 -04005139 // stop the current scroll animation, but if this is
5140 // the start of a fling, allow it to add to the current
5141 // fling's velocity
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005142 mScroller.abortAnimation();
5143 mTouchMode = TOUCH_DRAG_START_MODE;
Grace Klobac2242f22010-03-05 14:00:26 -08005144 mConfirmMove = true;
Grace Kloba96949ef2010-01-25 09:53:01 -08005145 mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY);
Grace Kloba8b97e4b2009-07-28 13:11:38 -07005146 } else if (mPrivateHandler.hasMessages(RELEASE_SINGLE_TAP)) {
5147 mPrivateHandler.removeMessages(RELEASE_SINGLE_TAP);
Grace Kloba178db412010-05-18 22:22:23 -07005148 if (getSettings().supportTouchOnly()) {
5149 removeTouchHighlight(true);
5150 }
Grace Kloba8b97e4b2009-07-28 13:11:38 -07005151 if (deltaX * deltaX + deltaY * deltaY < mDoubleTapSlopSquare) {
5152 mTouchMode = TOUCH_DOUBLE_TAP_MODE;
5153 } else {
5154 // commit the short press action for the previous tap
5155 doShortPress();
Grace Klobac2242f22010-03-05 14:00:26 -08005156 mTouchMode = TOUCH_INIT_MODE;
5157 mDeferTouchProcess = (!inFullScreenMode()
5158 && mForwardTouchEvents) ? hitFocusedPlugin(
5159 contentX, contentY) : false;
Grace Kloba8b97e4b2009-07-28 13:11:38 -07005160 }
Grace Klobac2242f22010-03-05 14:00:26 -08005161 } else { // the normal case
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005162 mTouchMode = TOUCH_INIT_MODE;
Grace Klobac2242f22010-03-05 14:00:26 -08005163 mDeferTouchProcess = (!inFullScreenMode()
5164 && mForwardTouchEvents) ? hitFocusedPlugin(
5165 contentX, contentY) : false;
Cary Clark77d98f42009-07-31 09:40:38 -04005166 mWebViewCore.sendMessage(
5167 EventHub.UPDATE_FRAME_CACHE_IF_LOADING);
Grace Kloba178db412010-05-18 22:22:23 -07005168 if (getSettings().supportTouchOnly()) {
5169 TouchHighlightData data = new TouchHighlightData();
5170 data.mX = contentX;
5171 data.mY = contentY;
5172 data.mSlop = viewToContentDimension(mNavSlop);
5173 mWebViewCore.sendMessageDelayed(
5174 EventHub.GET_TOUCH_HIGHLIGHT_RECTS, data,
5175 ViewConfiguration.getTapTimeout());
5176 if (DEBUG_TOUCH_HIGHLIGHT) {
5177 if (getSettings().getNavDump()) {
5178 mTouchHighlightX = (int) x + mScrollX;
5179 mTouchHighlightY = (int) y + mScrollY;
5180 mPrivateHandler.postDelayed(new Runnable() {
5181 public void run() {
5182 mTouchHighlightX = mTouchHighlightY = 0;
5183 invalidate();
5184 }
5185 }, TOUCH_HIGHLIGHT_ELAPSE_TIME);
5186 }
5187 }
5188 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005189 if (mLogEvent && eventTime - mLastTouchUpTime < 1000) {
Dan Egnor18e93962010-02-10 19:27:58 -08005190 EventLog.writeEvent(EventLogTags.BROWSER_DOUBLE_TAP_DURATION,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005191 (eventTime - mLastTouchUpTime), eventTime);
5192 }
Cary Clark924af702010-06-04 16:37:43 -04005193 if (mSelectingText) {
5194 mDrawSelectionPointer = false;
5195 mSelectionStarted = nativeStartSelection(contentX, contentY);
5196 if (DebugFlags.WEB_VIEW) {
5197 Log.v(LOGTAG, "select=" + contentX + "," + contentY);
5198 }
5199 invalidate();
5200 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005201 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07005202 // Trigger the link
Grace Kloba8b97e4b2009-07-28 13:11:38 -07005203 if (mTouchMode == TOUCH_INIT_MODE
5204 || mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
Grace Klobac2242f22010-03-05 14:00:26 -08005205 mPrivateHandler.sendEmptyMessageDelayed(
5206 SWITCH_TO_SHORTPRESS, TAP_TIMEOUT);
5207 mPrivateHandler.sendEmptyMessageDelayed(
5208 SWITCH_TO_LONGPRESS, LONG_PRESS_TIMEOUT);
5209 if (inFullScreenMode() || mDeferTouchProcess) {
5210 mPreventDefault = PREVENT_DEFAULT_YES;
5211 } else if (mForwardTouchEvents) {
5212 mPreventDefault = PREVENT_DEFAULT_MAYBE_YES;
5213 } else {
5214 mPreventDefault = PREVENT_DEFAULT_NO;
5215 }
5216 // pass the touch events from UI thread to WebCore thread
5217 if (shouldForwardTouchEvent()) {
5218 TouchEventData ted = new TouchEventData();
5219 ted.mAction = action;
Huahui Wu41865f42010-09-02 13:41:41 -07005220 ted.mPoints = new Point[1];
5221 ted.mPoints[0] = new Point(contentX, contentY);
Grace Klobac2242f22010-03-05 14:00:26 -08005222 ted.mMetaState = ev.getMetaState();
5223 ted.mReprocess = mDeferTouchProcess;
5224 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5225 if (mDeferTouchProcess) {
5226 // still needs to set them for compute deltaX/Y
5227 mLastTouchX = x;
5228 mLastTouchY = y;
5229 break;
5230 }
5231 if (!inFullScreenMode()) {
Ben Murdocha3f055e2010-05-26 18:46:56 +01005232 mPrivateHandler.removeMessages(PREVENT_DEFAULT_TIMEOUT);
Grace Klobac2242f22010-03-05 14:00:26 -08005233 mPrivateHandler.sendMessageDelayed(mPrivateHandler
5234 .obtainMessage(PREVENT_DEFAULT_TIMEOUT,
5235 action, 0), TAP_TIMEOUT);
5236 }
5237 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005238 }
Grace Kloba3a0def22010-01-23 21:11:54 -08005239 startTouch(x, y, eventTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005240 break;
5241 }
5242 case MotionEvent.ACTION_MOVE: {
Grace Klobac2242f22010-03-05 14:00:26 -08005243 boolean firstMove = false;
5244 if (!mConfirmMove && (deltaX * deltaX + deltaY * deltaY)
5245 >= mTouchSlopSquare) {
5246 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
5247 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5248 mConfirmMove = true;
5249 firstMove = true;
5250 if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
5251 mTouchMode = TOUCH_INIT_MODE;
5252 }
Grace Kloba178db412010-05-18 22:22:23 -07005253 if (getSettings().supportTouchOnly()) {
5254 removeTouchHighlight(true);
5255 }
Grace Klobac2242f22010-03-05 14:00:26 -08005256 }
5257 // pass the touch events from UI thread to WebCore thread
5258 if (shouldForwardTouchEvent() && mConfirmMove && (firstMove
5259 || eventTime - mLastSentTouchTime > mCurrentTouchInterval)) {
5260 TouchEventData ted = new TouchEventData();
5261 ted.mAction = action;
Huahui Wu41865f42010-09-02 13:41:41 -07005262 ted.mPoints = new Point[1];
5263 ted.mPoints[0] = new Point(contentX, contentY);
Grace Klobac2242f22010-03-05 14:00:26 -08005264 ted.mMetaState = ev.getMetaState();
5265 ted.mReprocess = mDeferTouchProcess;
5266 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5267 mLastSentTouchTime = eventTime;
5268 if (mDeferTouchProcess) {
5269 break;
5270 }
5271 if (firstMove && !inFullScreenMode()) {
5272 mPrivateHandler.sendMessageDelayed(mPrivateHandler
5273 .obtainMessage(PREVENT_DEFAULT_TIMEOUT,
5274 action, 0), TAP_TIMEOUT);
5275 }
5276 }
5277 if (mTouchMode == TOUCH_DONE_MODE
5278 || mPreventDefault == PREVENT_DEFAULT_YES) {
5279 // no dragging during scroll zoom animation, or when prevent
5280 // default is yes
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005281 break;
5282 }
Grace Klobac2242f22010-03-05 14:00:26 -08005283 if (mVelocityTracker == null) {
5284 Log.e(LOGTAG, "Got null mVelocityTracker when "
5285 + "mPreventDefault = " + mPreventDefault
5286 + " mDeferTouchProcess = " + mDeferTouchProcess
5287 + " mTouchMode = " + mTouchMode);
5288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005289 mVelocityTracker.addMovement(ev);
Cary Clark924af702010-06-04 16:37:43 -04005290 if (mSelectingText && mSelectionStarted) {
5291 if (DebugFlags.WEB_VIEW) {
5292 Log.v(LOGTAG, "extend=" + contentX + "," + contentY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005293 }
Leon Scroggins7f7bd522010-11-05 11:23:31 -04005294 ViewParent parent = getParent();
5295 if (parent != null) {
5296 parent.requestDisallowInterceptTouchEvent(true);
5297 }
Cary Clark6f5dfc62010-11-11 13:09:20 -05005298 int layer = nativeScrollableLayer(contentX, contentY);
5299 if (layer == 0) {
5300 mAutoScrollX = x <= SELECT_SCROLL ? -SELECT_SCROLL
5301 : x >= getViewWidth() - SELECT_SCROLL
5302 ? SELECT_SCROLL : 0;
5303 mAutoScrollY = y <= SELECT_SCROLL ? -SELECT_SCROLL
5304 : y >= getViewHeightWithTitle() - SELECT_SCROLL
5305 ? SELECT_SCROLL : 0;
5306 if (!mSentAutoScrollMessage) {
5307 mSentAutoScrollMessage = true;
5308 mPrivateHandler.sendEmptyMessageDelayed(
5309 SCROLL_SELECT_TEXT, SELECT_SCROLL_INTERVAL);
5310 }
5311 } else {
5312 // TODO: allow scrollable overflow div to autoscroll
5313 }
Cary Clark924af702010-06-04 16:37:43 -04005314 nativeExtendSelection(contentX, contentY);
5315 invalidate();
5316 break;
5317 }
Patrick Scotta3ebcc92010-07-16 11:52:22 -04005318
5319 if (mTouchMode != TOUCH_DRAG_MODE &&
5320 mTouchMode != TOUCH_DRAG_LAYER_MODE) {
Ben Murdochfc0bcdd2010-04-23 10:55:29 -07005321
Grace Klobac2242f22010-03-05 14:00:26 -08005322 if (!mConfirmMove) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005323 break;
5324 }
Ben Murdochfc0bcdd2010-04-23 10:55:29 -07005325
Grace Klobac2242f22010-03-05 14:00:26 -08005326 if (mPreventDefault == PREVENT_DEFAULT_MAYBE_YES
5327 || mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) {
Grace Klobaf58af622009-09-24 17:41:23 -07005328 // track mLastTouchTime as we may need to do fling at
5329 // ACTION_UP
5330 mLastTouchTime = eventTime;
5331 break;
5332 }
Adam Powell048a3a52010-09-08 23:59:37 -07005333
5334 // Only lock dragging to one axis if we don't have a scale in progress.
Adam Powellbe366682010-09-12 12:47:04 -07005335 // Scaling implies free-roaming movement. Note this is only ever a question
5336 // if mZoomManager.supportsPanDuringZoom() is true.
5337 if (detector != null && !detector.isInProgress()) {
Adam Powell048a3a52010-09-08 23:59:37 -07005338 // if it starts nearly horizontal or vertical, enforce it
5339 int ax = Math.abs(deltaX);
5340 int ay = Math.abs(deltaY);
5341 if (ax > MAX_SLOPE_FOR_DIAG * ay) {
5342 mSnapScrollMode = SNAP_X;
5343 mSnapPositive = deltaX > 0;
5344 } else if (ay > MAX_SLOPE_FOR_DIAG * ax) {
5345 mSnapScrollMode = SNAP_Y;
5346 mSnapPositive = deltaY > 0;
5347 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005348 }
5349
5350 mTouchMode = TOUCH_DRAG_MODE;
Romain Guyf7b4acc2009-12-01 16:24:45 -08005351 mLastTouchX = x;
5352 mLastTouchY = y;
5353 fDeltaX = 0.0f;
5354 fDeltaY = 0.0f;
5355 deltaX = 0;
5356 deltaY = 0;
5357
Grace Klobac2242f22010-03-05 14:00:26 -08005358 startDrag();
5359 }
5360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005361 // do pan
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005362 boolean done = false;
Cary Clark25415e22009-10-12 13:41:28 -04005363 boolean keepScrollBarsVisible = false;
5364 if (Math.abs(fDeltaX) < 1.0f && Math.abs(fDeltaY) < 1.0f) {
Adam Powell7bcf5172010-04-27 11:45:38 -07005365 mLastTouchX = x;
5366 mLastTouchY = y;
Cary Clark25415e22009-10-12 13:41:28 -04005367 keepScrollBarsVisible = done = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005368 } else {
5369 if (mSnapScrollMode == SNAP_X || mSnapScrollMode == SNAP_Y) {
5370 int ax = Math.abs(deltaX);
5371 int ay = Math.abs(deltaY);
5372 if (mSnapScrollMode == SNAP_X) {
5373 // radical change means getting out of snap mode
5374 if (ay > MAX_SLOPE_FOR_DIAG * ax
5375 && ay > MIN_BREAK_SNAP_CROSS_DISTANCE) {
5376 mSnapScrollMode = SNAP_NONE;
5377 }
5378 // reverse direction means lock in the snap mode
Cary Clarkac492e12009-10-14 14:53:37 -04005379 if (ax > MAX_SLOPE_FOR_DIAG * ay &&
5380 (mSnapPositive
5381 ? deltaX < -mMinLockSnapReverseDistance
5382 : deltaX > mMinLockSnapReverseDistance)) {
5383 mSnapScrollMode |= SNAP_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005384 }
5385 } else {
5386 // radical change means getting out of snap mode
Cary Clarkac492e12009-10-14 14:53:37 -04005387 if (ax > MAX_SLOPE_FOR_DIAG * ay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005388 && ax > MIN_BREAK_SNAP_CROSS_DISTANCE) {
5389 mSnapScrollMode = SNAP_NONE;
5390 }
5391 // reverse direction means lock in the snap mode
Cary Clarkac492e12009-10-14 14:53:37 -04005392 if (ay > MAX_SLOPE_FOR_DIAG * ax &&
5393 (mSnapPositive
5394 ? deltaY < -mMinLockSnapReverseDistance
5395 : deltaY > mMinLockSnapReverseDistance)) {
5396 mSnapScrollMode |= SNAP_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005397 }
5398 }
5399 }
Cary Clarkac492e12009-10-14 14:53:37 -04005400 if (mSnapScrollMode != SNAP_NONE) {
5401 if ((mSnapScrollMode & SNAP_X) == SNAP_X) {
5402 deltaY = 0;
Grace Kloba5b2c0562009-09-30 10:17:13 -07005403 } else {
Cary Clarkac492e12009-10-14 14:53:37 -04005404 deltaX = 0;
Grace Kloba5b2c0562009-09-30 10:17:13 -07005405 }
Cary Clarkac492e12009-10-14 14:53:37 -04005406 }
5407 if ((deltaX | deltaY) != 0) {
Cary Clarkac492e12009-10-14 14:53:37 -04005408 if (deltaX != 0) {
5409 mLastTouchX = x;
5410 }
5411 if (deltaY != 0) {
5412 mLastTouchY = y;
5413 }
5414 mHeldMotionless = MOTIONLESS_FALSE;
5415 } else {
5416 // keep the scrollbar on the screen even there is no
5417 // scroll
Adam Powell7bcf5172010-04-27 11:45:38 -07005418 mLastTouchX = x;
5419 mLastTouchY = y;
Cary Clarkac492e12009-10-14 14:53:37 -04005420 keepScrollBarsVisible = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005421 }
5422 mLastTouchTime = eventTime;
5423 mUserScroll = true;
5424 }
The Android Open Source Project10592532009-03-18 17:39:46 -07005425
Patrick Scott2f492272010-12-03 09:52:35 -05005426 startScrollingLayer(x, y);
Grace Klobac2242f22010-03-05 14:00:26 -08005427 doDrag(deltaX, deltaY);
Mike Reed19f3f0e2009-11-12 12:50:20 -05005428
Patrick Scotta3ebcc92010-07-16 11:52:22 -04005429 // Turn off scrollbars when dragging a layer.
5430 if (keepScrollBarsVisible &&
5431 mTouchMode != TOUCH_DRAG_LAYER_MODE) {
Cary Clark25415e22009-10-12 13:41:28 -04005432 if (mHeldMotionless != MOTIONLESS_TRUE) {
5433 mHeldMotionless = MOTIONLESS_TRUE;
5434 invalidate();
5435 }
Grace Kloba5b2c0562009-09-30 10:17:13 -07005436 // keep the scrollbar on the screen even there is no scroll
5437 awakenScrollBars(ViewConfiguration.getScrollDefaultDelay(),
5438 false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005439 // return false to indicate that we can't pan out of the
5440 // view space
Cary Clark25415e22009-10-12 13:41:28 -04005441 return !done;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005442 }
5443 break;
5444 }
5445 case MotionEvent.ACTION_UP: {
Leon Scroggins IIIae9f8e42010-04-14 16:06:06 -04005446 if (!isFocused()) requestFocus();
Grace Klobac2242f22010-03-05 14:00:26 -08005447 // pass the touch events from UI thread to WebCore thread
5448 if (shouldForwardTouchEvent()) {
5449 TouchEventData ted = new TouchEventData();
5450 ted.mAction = action;
Huahui Wu41865f42010-09-02 13:41:41 -07005451 ted.mPoints = new Point[1];
5452 ted.mPoints[0] = new Point(contentX, contentY);
Grace Klobac2242f22010-03-05 14:00:26 -08005453 ted.mMetaState = ev.getMetaState();
5454 ted.mReprocess = mDeferTouchProcess;
5455 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
Mike Reed19f3f0e2009-11-12 12:50:20 -05005456 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005457 mLastTouchUpTime = eventTime;
5458 switch (mTouchMode) {
Grace Kloba8b97e4b2009-07-28 13:11:38 -07005459 case TOUCH_DOUBLE_TAP_MODE: // double tap
5460 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
Grace Klobac2242f22010-03-05 14:00:26 -08005461 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5462 if (inFullScreenMode() || mDeferTouchProcess) {
5463 TouchEventData ted = new TouchEventData();
Grace Kloba5f68d6f2009-12-08 18:42:54 -08005464 ted.mAction = WebViewCore.ACTION_DOUBLETAP;
Huahui Wu41865f42010-09-02 13:41:41 -07005465 ted.mPoints = new Point[1];
5466 ted.mPoints[0] = new Point(contentX, contentY);
Ben Murdoch8a032a32010-02-02 18:20:11 +00005467 ted.mMetaState = ev.getMetaState();
Grace Klobac2242f22010-03-05 14:00:26 -08005468 ted.mReprocess = mDeferTouchProcess;
Grace Kloba5f68d6f2009-12-08 18:42:54 -08005469 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
Grace Klobac2242f22010-03-05 14:00:26 -08005470 } else if (mPreventDefault != PREVENT_DEFAULT_YES){
Derek Sollenberger15c5ddb2010-06-10 12:31:29 -04005471 mZoomManager.handleDoubleTap(mLastTouchX, mLastTouchY);
Grace Klobac2242f22010-03-05 14:00:26 -08005472 mTouchMode = TOUCH_DONE_MODE;
Grace Kloba5f68d6f2009-12-08 18:42:54 -08005473 }
Grace Kloba8b97e4b2009-07-28 13:11:38 -07005474 break;
Grace Klobaf58af622009-09-24 17:41:23 -07005475 case TOUCH_INIT_MODE: // tap
Grace Klobad66d84f2009-09-27 14:48:07 -07005476 case TOUCH_SHORTPRESS_START_MODE:
5477 case TOUCH_SHORTPRESS_MODE:
Grace Klobaf58af622009-09-24 17:41:23 -07005478 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
Grace Klobad66d84f2009-09-27 14:48:07 -07005479 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
Grace Klobac2242f22010-03-05 14:00:26 -08005480 if (mConfirmMove) {
Grace Klobaf58af622009-09-24 17:41:23 -07005481 Log.w(LOGTAG, "Miss a drag as we are waiting for" +
5482 " WebCore's response for touch down.");
Grace Klobac2242f22010-03-05 14:00:26 -08005483 if (mPreventDefault != PREVENT_DEFAULT_YES
Grace Klobad7625dd2010-03-04 11:46:12 -08005484 && (computeMaxScrollX() > 0
5485 || computeMaxScrollY() > 0)) {
Ben Murdochfc0bcdd2010-04-23 10:55:29 -07005486 // If the user has performed a very quick touch
5487 // sequence it is possible that we may get here
5488 // before WebCore has had a chance to process the events.
5489 // In this case, any call to preventDefault in the
5490 // JS touch handler will not have been executed yet.
5491 // Hence we will see both the UI (now) and WebCore
5492 // (when context switches) handling the event,
5493 // regardless of whether the web developer actually
5494 // doeses preventDefault in their touch handler. This
5495 // is the nature of our asynchronous touch model.
5496
Grace Klobaf58af622009-09-24 17:41:23 -07005497 // we will not rewrite drag code here, but we
5498 // will try fling if it applies.
Grace Klobaa7bc87c2010-01-29 14:56:25 -08005499 WebViewCore.reducePriority();
Grace Kloba524aab572010-04-07 11:12:52 -07005500 // to get better performance, pause updating the
5501 // picture
5502 WebViewCore.pauseUpdatePicture(mWebViewCore);
Grace Klobaf58af622009-09-24 17:41:23 -07005503 // fall through to TOUCH_DRAG_MODE
5504 } else {
Grace Klobac36862d52010-04-19 10:16:42 -07005505 // WebKit may consume the touch event and modify
5506 // DOM. drawContentPicture() will be called with
5507 // animateSroll as true for better performance.
5508 // Force redraw in high-quality.
5509 invalidate();
Grace Klobaf58af622009-09-24 17:41:23 -07005510 break;
5511 }
5512 } else {
Cary Clark924af702010-06-04 16:37:43 -04005513 if (mSelectingText) {
5514 // tapping on selection or controls does nothing
5515 if (!nativeHitSelection(contentX, contentY)) {
5516 selectionDone();
5517 }
5518 break;
5519 }
Grace Klobaec9a1042010-06-01 19:00:23 -07005520 // only trigger double tap if the WebView is
5521 // scalable
5522 if (mTouchMode == TOUCH_INIT_MODE
5523 && (canZoomIn() || canZoomOut())) {
Grace Klobac2242f22010-03-05 14:00:26 -08005524 mPrivateHandler.sendEmptyMessageDelayed(
5525 RELEASE_SINGLE_TAP, ViewConfiguration
5526 .getDoubleTapTimeout());
5527 } else {
5528 doShortPress();
Grace Klobaf58af622009-09-24 17:41:23 -07005529 }
5530 break;
5531 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005532 case TOUCH_DRAG_MODE:
Patrick Scott2f492272010-12-03 09:52:35 -05005533 case TOUCH_DRAG_LAYER_MODE:
Cary Clark25415e22009-10-12 13:41:28 -04005534 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
5535 mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005536 // if the user waits a while w/o moving before the
5537 // up, we don't want to do a fling
5538 if (eventTime - mLastTouchTime <= MIN_FLING_TIME) {
Grace Klobac2242f22010-03-05 14:00:26 -08005539 if (mVelocityTracker == null) {
5540 Log.e(LOGTAG, "Got null mVelocityTracker when "
5541 + "mPreventDefault = "
5542 + mPreventDefault
5543 + " mDeferTouchProcess = "
5544 + mDeferTouchProcess);
5545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005546 mVelocityTracker.addMovement(ev);
Grace Kloba9b657802010-04-08 13:46:23 -07005547 // set to MOTIONLESS_IGNORE so that it won't keep
5548 // removing and sending message in
5549 // drawCoreAndCursorRing()
5550 mHeldMotionless = MOTIONLESS_IGNORE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005551 doFling();
5552 break;
Adam Powell637d3372010-08-25 14:37:03 -07005553 } else {
5554 if (mScroller.springBack(mScrollX, mScrollY, 0,
5555 computeMaxScrollX(), 0,
5556 computeMaxScrollY())) {
5557 invalidate();
5558 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005559 }
Grace Kloba9b657802010-04-08 13:46:23 -07005560 // redraw in high-quality, as we're done dragging
5561 mHeldMotionless = MOTIONLESS_TRUE;
5562 invalidate();
Grace Kloba524aab572010-04-07 11:12:52 -07005563 // fall through
5564 case TOUCH_DRAG_START_MODE:
5565 // TOUCH_DRAG_START_MODE should not happen for the real
5566 // device as we almost certain will get a MOVE. But this
5567 // is possible on emulator.
Cary Clark278ce052009-08-31 16:08:42 -04005568 mLastVelocity = 0;
Grace Klobaa7bc87c2010-01-29 14:56:25 -08005569 WebViewCore.resumePriority();
Cary Clark0df02692010-11-24 11:01:37 -05005570 if (!mSelectingText) {
5571 WebViewCore.resumeUpdatePicture(mWebViewCore);
5572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005573 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005574 }
Grace Klobac2242f22010-03-05 14:00:26 -08005575 stopTouch();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005576 break;
5577 }
5578 case MotionEvent.ACTION_CANCEL: {
Grace Klobad7625dd2010-03-04 11:46:12 -08005579 if (mTouchMode == TOUCH_DRAG_MODE) {
Adam Powell637d3372010-08-25 14:37:03 -07005580 mScroller.springBack(mScrollX, mScrollY, 0,
5581 computeMaxScrollX(), 0, computeMaxScrollY());
Grace Klobac2242f22010-03-05 14:00:26 -08005582 invalidate();
Grace Klobad7625dd2010-03-04 11:46:12 -08005583 }
Grace Klobac2242f22010-03-05 14:00:26 -08005584 cancelWebCoreTouchEvent(contentX, contentY, false);
5585 cancelTouch();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005586 break;
5587 }
5588 }
5589 return true;
5590 }
Cary Clarkd6982c92009-05-29 11:02:22 -04005591
Huahui Wu41865f42010-09-02 13:41:41 -07005592 private void passMultiTouchToWebKit(MotionEvent ev) {
5593 TouchEventData ted = new TouchEventData();
5594 ted.mAction = ev.getAction() & MotionEvent.ACTION_MASK;
5595 final int count = ev.getPointerCount();
5596 ted.mPoints = new Point[count];
5597 for (int c = 0; c < count; c++) {
5598 int x = viewToContentX((int) ev.getX(c) + mScrollX);
5599 int y = viewToContentY((int) ev.getY(c) + mScrollY);
5600 ted.mPoints[c] = new Point(x, y);
5601 }
5602 ted.mMetaState = ev.getMetaState();
5603 ted.mReprocess = mDeferTouchProcess;
5604 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5605 cancelLongPress();
5606 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5607 mPreventDefault = PREVENT_DEFAULT_IGNORE;
5608 }
5609
Grace Klobac2242f22010-03-05 14:00:26 -08005610 private void cancelWebCoreTouchEvent(int x, int y, boolean removeEvents) {
5611 if (shouldForwardTouchEvent()) {
5612 if (removeEvents) {
5613 mWebViewCore.removeMessages(EventHub.TOUCH_EVENT);
5614 }
5615 TouchEventData ted = new TouchEventData();
Huahui Wu41865f42010-09-02 13:41:41 -07005616 ted.mPoints = new Point[1];
5617 ted.mPoints[0] = new Point(x, y);
Grace Klobac2242f22010-03-05 14:00:26 -08005618 ted.mAction = MotionEvent.ACTION_CANCEL;
5619 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5620 mPreventDefault = PREVENT_DEFAULT_IGNORE;
5621 }
5622 }
5623
Grace Kloba3a0def22010-01-23 21:11:54 -08005624 private void startTouch(float x, float y, long eventTime) {
5625 // Remember where the motion event started
5626 mLastTouchX = x;
5627 mLastTouchY = y;
5628 mLastTouchTime = eventTime;
5629 mVelocityTracker = VelocityTracker.obtain();
5630 mSnapScrollMode = SNAP_NONE;
Grace Kloba3a0def22010-01-23 21:11:54 -08005631 }
5632
Grace Klobac2242f22010-03-05 14:00:26 -08005633 private void startDrag() {
5634 WebViewCore.reducePriority();
Grace Kloba524aab572010-04-07 11:12:52 -07005635 // to get better performance, pause updating the picture
5636 WebViewCore.pauseUpdatePicture(mWebViewCore);
Grace Klobac2242f22010-03-05 14:00:26 -08005637 if (!mDragFromTextInput) {
5638 nativeHideCursor();
5639 }
Derek Sollenberger90b6e482010-05-10 12:38:54 -04005640
5641 if (mHorizontalScrollBarMode != SCROLLBAR_ALWAYSOFF
5642 || mVerticalScrollBarMode != SCROLLBAR_ALWAYSOFF) {
5643 mZoomManager.invokeZoomPicker();
Grace Klobac2242f22010-03-05 14:00:26 -08005644 }
5645 }
5646
5647 private void doDrag(int deltaX, int deltaY) {
5648 if ((deltaX | deltaY) != 0) {
Patrick Scotta3ebcc92010-07-16 11:52:22 -04005649 if (mTouchMode == TOUCH_DRAG_LAYER_MODE) {
5650 deltaX = viewToContentDimension(deltaX);
5651 deltaY = viewToContentDimension(deltaY);
5652 if (nativeScrollLayer(mScrollingLayer, deltaX, deltaY)) {
5653 invalidate();
Patrick Scott4b903782010-11-30 08:14:05 -05005654 return;
Patrick Scotta3ebcc92010-07-16 11:52:22 -04005655 }
Patrick Scott4b903782010-11-30 08:14:05 -05005656 // Switch to drag mode and fall through.
5657 mTouchMode = TOUCH_DRAG_MODE;
Patrick Scotta3ebcc92010-07-16 11:52:22 -04005658 }
Adam Powell637d3372010-08-25 14:37:03 -07005659
5660 final int oldX = mScrollX;
5661 final int oldY = mScrollY;
5662 final int rangeX = computeMaxScrollX();
5663 final int rangeY = computeMaxScrollY();
5664
5665 if (mOverScrollGlow != null) {
5666 mOverScrollGlow.setOverScrollDeltas(deltaX, deltaY);
5667 }
5668
5669 overScrollBy(deltaX, deltaY, oldX, oldY,
5670 rangeX, rangeY,
5671 mOverscrollDistance, mOverscrollDistance, true);
5672 if (mOverScrollGlow != null && mOverScrollGlow.isAnimating()) {
5673 invalidate();
5674 }
Grace Klobac2242f22010-03-05 14:00:26 -08005675 }
Derek Sollenberger90b6e482010-05-10 12:38:54 -04005676 mZoomManager.keepZoomPickerVisible();
Grace Klobac2242f22010-03-05 14:00:26 -08005677 }
5678
5679 private void stopTouch() {
Grace Klobac2242f22010-03-05 14:00:26 -08005680 // we also use mVelocityTracker == null to tell us that we are
5681 // not "moving around", so we can take the slower/prettier
5682 // mode in the drawing code
5683 if (mVelocityTracker != null) {
5684 mVelocityTracker.recycle();
5685 mVelocityTracker = null;
5686 }
Adam Powell637d3372010-08-25 14:37:03 -07005687
5688 // Release any pulled glows
5689 if (mOverScrollGlow != null) {
5690 mOverScrollGlow.releaseAll();
5691 }
Grace Klobac2242f22010-03-05 14:00:26 -08005692 }
5693
Grace Kloba3a0def22010-01-23 21:11:54 -08005694 private void cancelTouch() {
Grace Kloba3a0def22010-01-23 21:11:54 -08005695 // we also use mVelocityTracker == null to tell us that we are
5696 // not "moving around", so we can take the slower/prettier
5697 // mode in the drawing code
5698 if (mVelocityTracker != null) {
5699 mVelocityTracker.recycle();
5700 mVelocityTracker = null;
5701 }
Adam Powell637d3372010-08-25 14:37:03 -07005702
Cary Clark0df02692010-11-24 11:01:37 -05005703 if ((mTouchMode == TOUCH_DRAG_MODE
5704 || mTouchMode == TOUCH_DRAG_LAYER_MODE) && !mSelectingText) {
Grace Klobaa7bc87c2010-01-29 14:56:25 -08005705 WebViewCore.resumePriority();
Grace Kloba524aab572010-04-07 11:12:52 -07005706 WebViewCore.resumeUpdatePicture(mWebViewCore);
Grace Kloba3a0def22010-01-23 21:11:54 -08005707 }
5708 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
5709 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5710 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
5711 mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
Grace Kloba178db412010-05-18 22:22:23 -07005712 if (getSettings().supportTouchOnly()) {
5713 removeTouchHighlight(true);
5714 }
Grace Kloba3a0def22010-01-23 21:11:54 -08005715 mHeldMotionless = MOTIONLESS_TRUE;
5716 mTouchMode = TOUCH_DONE_MODE;
5717 nativeHideCursor();
5718 }
5719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005720 private long mTrackballFirstTime = 0;
5721 private long mTrackballLastTime = 0;
5722 private float mTrackballRemainsX = 0.0f;
5723 private float mTrackballRemainsY = 0.0f;
5724 private int mTrackballXMove = 0;
5725 private int mTrackballYMove = 0;
Cary Clark924af702010-06-04 16:37:43 -04005726 private boolean mSelectingText = false;
5727 private boolean mSelectionStarted = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005728 private boolean mExtendSelection = false;
Cary Clark924af702010-06-04 16:37:43 -04005729 private boolean mDrawSelectionPointer = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005730 private static final int TRACKBALL_KEY_TIMEOUT = 1000;
5731 private static final int TRACKBALL_TIMEOUT = 200;
5732 private static final int TRACKBALL_WAIT = 100;
5733 private static final int TRACKBALL_SCALE = 400;
5734 private static final int TRACKBALL_SCROLL_COUNT = 5;
5735 private static final int TRACKBALL_MOVE_COUNT = 10;
5736 private static final int TRACKBALL_MULTIPLIER = 3;
5737 private static final int SELECT_CURSOR_OFFSET = 16;
Cary Clark6f5dfc62010-11-11 13:09:20 -05005738 private static final int SELECT_SCROLL = 5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005739 private int mSelectX = 0;
5740 private int mSelectY = 0;
Cary Clark5da9aeb2009-10-06 17:40:53 -04005741 private boolean mFocusSizeChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005742 private boolean mTrackballDown = false;
5743 private long mTrackballUpTime = 0;
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04005744 private long mLastCursorTime = 0;
5745 private Rect mLastCursorBounds;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005746
5747 // Set by default; BrowserActivity clears to interpret trackball data
Cary Clarkd6982c92009-05-29 11:02:22 -04005748 // directly for movement. Currently, the framework only passes
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005749 // arrow key events, not trackball events, from one child to the next
5750 private boolean mMapTrackballToArrowKeys = true;
Cary Clarkd6982c92009-05-29 11:02:22 -04005751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005752 public void setMapTrackballToArrowKeys(boolean setMap) {
5753 mMapTrackballToArrowKeys = setMap;
5754 }
5755
5756 void resetTrackballTime() {
5757 mTrackballLastTime = 0;
5758 }
5759
5760 @Override
5761 public boolean onTrackballEvent(MotionEvent ev) {
5762 long time = ev.getEventTime();
5763 if ((ev.getMetaState() & KeyEvent.META_ALT_ON) != 0) {
5764 if (ev.getY() > 0) pageDown(true);
5765 if (ev.getY() < 0) pageUp(true);
5766 return true;
5767 }
5768 if (ev.getAction() == MotionEvent.ACTION_DOWN) {
Cary Clark924af702010-06-04 16:37:43 -04005769 if (mSelectingText) {
Cary Clarkbadd8392009-10-15 13:32:08 -04005770 return true; // discard press if copy in progress
5771 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005772 mTrackballDown = true;
Leon Scroggins3ccd3652009-06-26 17:22:50 -04005773 if (mNativeClass == 0) {
5774 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005775 }
Leon Scroggins3ccd3652009-06-26 17:22:50 -04005776 nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true);
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04005777 if (time - mLastCursorTime <= TRACKBALL_TIMEOUT
5778 && !mLastCursorBounds.equals(nativeGetCursorRingBounds())) {
5779 nativeSelectBestAt(mLastCursorBounds);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005780 }
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04005781 if (DebugFlags.WEB_VIEW) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005782 Log.v(LOGTAG, "onTrackballEvent down ev=" + ev
Cary Clarkd6982c92009-05-29 11:02:22 -04005783 + " time=" + time
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04005784 + " mLastCursorTime=" + mLastCursorTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005785 }
5786 if (isInTouchMode()) requestFocusFromTouch();
5787 return false; // let common code in onKeyDown at it
Cary Clarkd6982c92009-05-29 11:02:22 -04005788 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005789 if (ev.getAction() == MotionEvent.ACTION_UP) {
Leon Scrogginse3225672009-06-03 15:53:13 -04005790 // LONG_PRESS_CENTER is set in common onKeyDown
5791 mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005792 mTrackballDown = false;
5793 mTrackballUpTime = time;
Cary Clark924af702010-06-04 16:37:43 -04005794 if (mSelectingText) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005795 if (mExtendSelection) {
Cary Clark924af702010-06-04 16:37:43 -04005796 copySelection();
5797 selectionDone();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005798 } else {
5799 mExtendSelection = true;
Cary Clark924af702010-06-04 16:37:43 -04005800 nativeSetExtendSelection();
Cary Clark09e383c2009-10-26 16:43:58 -04005801 invalidate(); // draw the i-beam instead of the arrow
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005802 }
Cary Clarkbadd8392009-10-15 13:32:08 -04005803 return true; // discard press if copy in progress
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005804 }
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04005805 if (DebugFlags.WEB_VIEW) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005806 Log.v(LOGTAG, "onTrackballEvent up ev=" + ev
Cary Clarkd6982c92009-05-29 11:02:22 -04005807 + " time=" + time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005808 );
5809 }
5810 return false; // let common code in onKeyUp at it
5811 }
Svetoslav Ganov9b756ac2010-11-05 15:42:22 -07005812 if ((mMapTrackballToArrowKeys && (ev.getMetaState() & KeyEvent.META_SHIFT_ON) == 0) ||
Svetoslav Ganov585f13f8d2010-08-10 07:59:15 -07005813 (mAccessibilityInjector != null || mAccessibilityScriptInjected)) {
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04005814 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent gmail quit");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005815 return false;
5816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005817 if (mTrackballDown) {
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04005818 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent down quit");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005819 return true; // discard move if trackball is down
5820 }
5821 if (time - mTrackballUpTime < TRACKBALL_TIMEOUT) {
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04005822 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent up timeout quit");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005823 return true;
5824 }
5825 // TODO: alternatively we can do panning as touch does
5826 switchOutDrawHistory();
5827 if (time - mTrackballLastTime > TRACKBALL_TIMEOUT) {
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04005828 if (DebugFlags.WEB_VIEW) {
Cary Clarkd6982c92009-05-29 11:02:22 -04005829 Log.v(LOGTAG, "onTrackballEvent time="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005830 + time + " last=" + mTrackballLastTime);
5831 }
5832 mTrackballFirstTime = time;
5833 mTrackballXMove = mTrackballYMove = 0;
5834 }
5835 mTrackballLastTime = time;
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04005836 if (DebugFlags.WEB_VIEW) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005837 Log.v(LOGTAG, "onTrackballEvent ev=" + ev + " time=" + time);
5838 }
5839 mTrackballRemainsX += ev.getX();
5840 mTrackballRemainsY += ev.getY();
Svetoslav Ganov9b756ac2010-11-05 15:42:22 -07005841 doTrackball(time, ev.getMetaState());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005842 return true;
5843 }
Cary Clarkd6982c92009-05-29 11:02:22 -04005844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005845 void moveSelection(float xRate, float yRate) {
5846 if (mNativeClass == 0)
5847 return;
5848 int width = getViewWidth();
5849 int height = getViewHeight();
Cary Clarkc05af372009-10-16 10:52:27 -04005850 mSelectX += xRate;
5851 mSelectY += yRate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005852 int maxX = width + mScrollX;
5853 int maxY = height + mScrollY;
5854 mSelectX = Math.min(maxX, Math.max(mScrollX - SELECT_CURSOR_OFFSET
5855 , mSelectX));
5856 mSelectY = Math.min(maxY, Math.max(mScrollY - SELECT_CURSOR_OFFSET
5857 , mSelectY));
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04005858 if (DebugFlags.WEB_VIEW) {
Cary Clarkd6982c92009-05-29 11:02:22 -04005859 Log.v(LOGTAG, "moveSelection"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005860 + " mSelectX=" + mSelectX
5861 + " mSelectY=" + mSelectY
5862 + " mScrollX=" + mScrollX
5863 + " mScrollY=" + mScrollY
5864 + " xRate=" + xRate
5865 + " yRate=" + yRate
5866 );
5867 }
Cary Clark924af702010-06-04 16:37:43 -04005868 nativeMoveSelection(viewToContentX(mSelectX), viewToContentY(mSelectY));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005869 int scrollX = mSelectX < mScrollX ? -SELECT_CURSOR_OFFSET
Cary Clarkd6982c92009-05-29 11:02:22 -04005870 : mSelectX > maxX - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005871 : 0;
5872 int scrollY = mSelectY < mScrollY ? -SELECT_CURSOR_OFFSET
Cary Clarkd6982c92009-05-29 11:02:22 -04005873 : mSelectY > maxY - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005874 : 0;
5875 pinScrollBy(scrollX, scrollY, true, 0);
5876 Rect select = new Rect(mSelectX, mSelectY, mSelectX + 1, mSelectY + 1);
5877 requestRectangleOnScreen(select);
5878 invalidate();
5879 }
5880
5881 private int scaleTrackballX(float xRate, int width) {
5882 int xMove = (int) (xRate / TRACKBALL_SCALE * width);
5883 int nextXMove = xMove;
5884 if (xMove > 0) {
5885 if (xMove > mTrackballXMove) {
5886 xMove -= mTrackballXMove;
5887 }
5888 } else if (xMove < mTrackballXMove) {
5889 xMove -= mTrackballXMove;
5890 }
5891 mTrackballXMove = nextXMove;
5892 return xMove;
5893 }
5894
5895 private int scaleTrackballY(float yRate, int height) {
5896 int yMove = (int) (yRate / TRACKBALL_SCALE * height);
5897 int nextYMove = yMove;
5898 if (yMove > 0) {
5899 if (yMove > mTrackballYMove) {
5900 yMove -= mTrackballYMove;
5901 }
5902 } else if (yMove < mTrackballYMove) {
5903 yMove -= mTrackballYMove;
5904 }
5905 mTrackballYMove = nextYMove;
5906 return yMove;
5907 }
5908
5909 private int keyCodeToSoundsEffect(int keyCode) {
5910 switch(keyCode) {
5911 case KeyEvent.KEYCODE_DPAD_UP:
5912 return SoundEffectConstants.NAVIGATION_UP;
5913 case KeyEvent.KEYCODE_DPAD_RIGHT:
5914 return SoundEffectConstants.NAVIGATION_RIGHT;
5915 case KeyEvent.KEYCODE_DPAD_DOWN:
5916 return SoundEffectConstants.NAVIGATION_DOWN;
5917 case KeyEvent.KEYCODE_DPAD_LEFT:
5918 return SoundEffectConstants.NAVIGATION_LEFT;
5919 }
5920 throw new IllegalArgumentException("keyCode must be one of " +
5921 "{KEYCODE_DPAD_UP, KEYCODE_DPAD_RIGHT, KEYCODE_DPAD_DOWN, " +
5922 "KEYCODE_DPAD_LEFT}.");
5923 }
5924
Svetoslav Ganov9b756ac2010-11-05 15:42:22 -07005925 private void doTrackball(long time, int metaState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005926 int elapsed = (int) (mTrackballLastTime - mTrackballFirstTime);
5927 if (elapsed == 0) {
5928 elapsed = TRACKBALL_TIMEOUT;
5929 }
Cary Clarkd6982c92009-05-29 11:02:22 -04005930 float xRate = mTrackballRemainsX * 1000 / elapsed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005931 float yRate = mTrackballRemainsY * 1000 / elapsed;
Cary Clarkc05af372009-10-16 10:52:27 -04005932 int viewWidth = getViewWidth();
5933 int viewHeight = getViewHeight();
Cary Clark924af702010-06-04 16:37:43 -04005934 if (mSelectingText) {
5935 if (!mDrawSelectionPointer) {
5936 // The last selection was made by touch, disabling drawing the
5937 // selection pointer. Allow the trackball to adjust the
5938 // position of the touch control.
5939 mSelectX = contentToViewX(nativeSelectionX());
5940 mSelectY = contentToViewY(nativeSelectionY());
5941 mDrawSelectionPointer = mExtendSelection = true;
5942 nativeSetExtendSelection();
5943 }
Cary Clarkc05af372009-10-16 10:52:27 -04005944 moveSelection(scaleTrackballX(xRate, viewWidth),
5945 scaleTrackballY(yRate, viewHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005946 mTrackballRemainsX = mTrackballRemainsY = 0;
5947 return;
5948 }
5949 float ax = Math.abs(xRate);
5950 float ay = Math.abs(yRate);
5951 float maxA = Math.max(ax, ay);
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04005952 if (DebugFlags.WEB_VIEW) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005953 Log.v(LOGTAG, "doTrackball elapsed=" + elapsed
5954 + " xRate=" + xRate
5955 + " yRate=" + yRate
5956 + " mTrackballRemainsX=" + mTrackballRemainsX
5957 + " mTrackballRemainsY=" + mTrackballRemainsY);
5958 }
Cary Clarkc05af372009-10-16 10:52:27 -04005959 int width = mContentWidth - viewWidth;
5960 int height = mContentHeight - viewHeight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005961 if (width < 0) width = 0;
5962 if (height < 0) height = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005963 ax = Math.abs(mTrackballRemainsX * TRACKBALL_MULTIPLIER);
5964 ay = Math.abs(mTrackballRemainsY * TRACKBALL_MULTIPLIER);
5965 maxA = Math.max(ax, ay);
5966 int count = Math.max(0, (int) maxA);
5967 int oldScrollX = mScrollX;
5968 int oldScrollY = mScrollY;
5969 if (count > 0) {
Cary Clarkd6982c92009-05-29 11:02:22 -04005970 int selectKeyCode = ax < ay ? mTrackballRemainsY < 0 ?
5971 KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN :
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005972 mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT :
5973 KeyEvent.KEYCODE_DPAD_RIGHT;
5974 count = Math.min(count, TRACKBALL_MOVE_COUNT);
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04005975 if (DebugFlags.WEB_VIEW) {
Cary Clarkd6982c92009-05-29 11:02:22 -04005976 Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005977 + " count=" + count
5978 + " mTrackballRemainsX=" + mTrackballRemainsX
5979 + " mTrackballRemainsY=" + mTrackballRemainsY);
5980 }
Leon Scroggins9ab32b62010-05-03 14:19:50 +01005981 if (mNativeClass != 0 && nativePageShouldHandleShiftAndArrows()) {
Leon Scrogginsb127c8f2010-03-05 15:42:17 -05005982 for (int i = 0; i < count; i++) {
Svetoslav Ganov9b756ac2010-11-05 15:42:22 -07005983 letPageHandleNavKey(selectKeyCode, time, true, metaState);
Leon Scrogginsb127c8f2010-03-05 15:42:17 -05005984 }
Svetoslav Ganov9b756ac2010-11-05 15:42:22 -07005985 letPageHandleNavKey(selectKeyCode, time, false, metaState);
Leon Scrogginsb127c8f2010-03-05 15:42:17 -05005986 } else if (navHandledKey(selectKeyCode, count, false, time)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005987 playSoundEffect(keyCodeToSoundsEffect(selectKeyCode));
5988 }
5989 mTrackballRemainsX = mTrackballRemainsY = 0;
5990 }
5991 if (count >= TRACKBALL_SCROLL_COUNT) {
5992 int xMove = scaleTrackballX(xRate, width);
5993 int yMove = scaleTrackballY(yRate, height);
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04005994 if (DebugFlags.WEB_VIEW) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005995 Log.v(LOGTAG, "doTrackball pinScrollBy"
5996 + " count=" + count
5997 + " xMove=" + xMove + " yMove=" + yMove
Cary Clarkd6982c92009-05-29 11:02:22 -04005998 + " mScrollX-oldScrollX=" + (mScrollX-oldScrollX)
5999 + " mScrollY-oldScrollY=" + (mScrollY-oldScrollY)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006000 );
6001 }
6002 if (Math.abs(mScrollX - oldScrollX) > Math.abs(xMove)) {
6003 xMove = 0;
6004 }
6005 if (Math.abs(mScrollY - oldScrollY) > Math.abs(yMove)) {
6006 yMove = 0;
6007 }
6008 if (xMove != 0 || yMove != 0) {
6009 pinScrollBy(xMove, yMove, true, 0);
6010 }
6011 mUserScroll = true;
Cary Clarkd6982c92009-05-29 11:02:22 -04006012 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006013 }
6014
Adam Powell637d3372010-08-25 14:37:03 -07006015 /**
6016 * Compute the maximum horizontal scroll position. Used by {@link OverScrollGlow}.
6017 * @return Maximum horizontal scroll position within real content
6018 */
6019 int computeMaxScrollX() {
6020 return Math.max(computeRealHorizontalScrollRange() - getViewWidth(), 0);
Grace Klobad7625dd2010-03-04 11:46:12 -08006021 }
6022
Adam Powell637d3372010-08-25 14:37:03 -07006023 /**
6024 * Compute the maximum vertical scroll position. Used by {@link OverScrollGlow}.
6025 * @return Maximum vertical scroll position within real content
6026 */
6027 int computeMaxScrollY() {
6028 return Math.max(computeRealVerticalScrollRange() + getTitleHeight()
Mike Reede5e63f42010-03-19 14:38:23 -04006029 - getViewHeightWithTitle(), 0);
Mike Reede8853fc2009-09-04 14:01:48 -04006030 }
6031
Derek Sollenberger03e48912010-05-18 17:03:42 -04006032 boolean updateScrollCoordinates(int x, int y) {
6033 int oldX = mScrollX;
6034 int oldY = mScrollY;
6035 mScrollX = x;
6036 mScrollY = y;
6037 if (oldX != mScrollX || oldY != mScrollY) {
6038 onScrollChanged(mScrollX, mScrollY, oldX, oldY);
6039 return true;
6040 } else {
6041 return false;
6042 }
6043 }
6044
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006045 public void flingScroll(int vx, int vy) {
Grace Klobad7625dd2010-03-04 11:46:12 -08006046 mScroller.fling(mScrollX, mScrollY, vx, vy, 0, computeMaxScrollX(), 0,
Adam Powell637d3372010-08-25 14:37:03 -07006047 computeMaxScrollY(), mOverflingDistance, mOverflingDistance);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006048 invalidate();
6049 }
Cary Clarkd6982c92009-05-29 11:02:22 -04006050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006051 private void doFling() {
6052 if (mVelocityTracker == null) {
6053 return;
6054 }
Grace Klobad7625dd2010-03-04 11:46:12 -08006055 int maxX = computeMaxScrollX();
Mike Reede8853fc2009-09-04 14:01:48 -04006056 int maxY = computeMaxScrollY();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006057
Romain Guy4296fc42009-07-06 11:48:52 -07006058 mVelocityTracker.computeCurrentVelocity(1000, mMaximumFling);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006059 int vx = (int) mVelocityTracker.getXVelocity();
6060 int vy = (int) mVelocityTracker.getYVelocity();
6061
6062 if (mSnapScrollMode != SNAP_NONE) {
Cary Clarkac492e12009-10-14 14:53:37 -04006063 if ((mSnapScrollMode & SNAP_X) == SNAP_X) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006064 vy = 0;
6065 } else {
6066 vx = 0;
6067 }
6068 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006069 if (true /* EMG release: make our fling more like Maps' */) {
6070 // maps cuts their velocity in half
6071 vx = vx * 3 / 4;
6072 vy = vy * 3 / 4;
6073 }
Cary Clarkaa7caa62009-09-08 14:15:07 -04006074 if ((maxX == 0 && vy == 0) || (maxY == 0 && vx == 0)) {
Grace Klobaa7bc87c2010-01-29 14:56:25 -08006075 WebViewCore.resumePriority();
Cary Clark0df02692010-11-24 11:01:37 -05006076 if (!mSelectingText) {
6077 WebViewCore.resumeUpdatePicture(mWebViewCore);
6078 }
Adam Powell637d3372010-08-25 14:37:03 -07006079 if (mScroller.springBack(mScrollX, mScrollY, 0, computeMaxScrollX(),
6080 0, computeMaxScrollY())) {
6081 invalidate();
6082 }
Cary Clarkaa7caa62009-09-08 14:15:07 -04006083 return;
6084 }
Cary Clark278ce052009-08-31 16:08:42 -04006085 float currentVelocity = mScroller.getCurrVelocity();
Grace Kloba3c19d992010-05-17 19:19:06 -07006086 float velocity = (float) Math.hypot(vx, vy);
6087 if (mLastVelocity > 0 && currentVelocity > 0 && velocity
6088 > mLastVelocity * MINIMUM_VELOCITY_RATIO_FOR_ACCELERATION) {
Cary Clark278ce052009-08-31 16:08:42 -04006089 float deltaR = (float) (Math.abs(Math.atan2(mLastVelY, mLastVelX)
6090 - Math.atan2(vy, vx)));
6091 final float circle = (float) (Math.PI) * 2.0f;
6092 if (deltaR > circle * 0.9f || deltaR < circle * 0.1f) {
6093 vx += currentVelocity * mLastVelX / mLastVelocity;
6094 vy += currentVelocity * mLastVelY / mLastVelocity;
Grace Kloba3c19d992010-05-17 19:19:06 -07006095 velocity = (float) Math.hypot(vx, vy);
Cary Clark278ce052009-08-31 16:08:42 -04006096 if (DebugFlags.WEB_VIEW) {
6097 Log.v(LOGTAG, "doFling vx= " + vx + " vy=" + vy);
6098 }
6099 } else if (DebugFlags.WEB_VIEW) {
6100 Log.v(LOGTAG, "doFling missed " + deltaR / circle);
6101 }
6102 } else if (DebugFlags.WEB_VIEW) {
6103 Log.v(LOGTAG, "doFling start last=" + mLastVelocity
Cary Clarkaa7caa62009-09-08 14:15:07 -04006104 + " current=" + currentVelocity
6105 + " vx=" + vx + " vy=" + vy
6106 + " maxX=" + maxX + " maxY=" + maxY
6107 + " mScrollX=" + mScrollX + " mScrollY=" + mScrollY);
Cary Clark278ce052009-08-31 16:08:42 -04006108 }
Adam Powell637d3372010-08-25 14:37:03 -07006109
6110 // Allow sloppy flings without overscrolling at the edges.
6111 if ((mScrollX == 0 || mScrollX == maxX) && Math.abs(vx) < Math.abs(vy)) {
6112 vx = 0;
6113 }
6114 if ((mScrollY == 0 || mScrollY == maxY) && Math.abs(vy) < Math.abs(vx)) {
6115 vy = 0;
6116 }
6117
6118 if (mOverscrollDistance < mOverflingDistance) {
Patrick Scott2f492272010-12-03 09:52:35 -05006119 if ((vx > 0 && mScrollX == -mOverscrollDistance) ||
6120 (vx < 0 && mScrollX == maxX + mOverscrollDistance)) {
Adam Powell637d3372010-08-25 14:37:03 -07006121 vx = 0;
6122 }
Patrick Scott2f492272010-12-03 09:52:35 -05006123 if ((vy > 0 && mScrollY == -mOverscrollDistance) ||
6124 (vy < 0 && mScrollY == maxY + mOverscrollDistance)) {
Adam Powell637d3372010-08-25 14:37:03 -07006125 vy = 0;
6126 }
6127 }
6128
Cary Clark278ce052009-08-31 16:08:42 -04006129 mLastVelX = vx;
6130 mLastVelY = vy;
Grace Kloba3c19d992010-05-17 19:19:06 -07006131 mLastVelocity = velocity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006132
Adam Powell637d3372010-08-25 14:37:03 -07006133 // no horizontal overscroll if the content just fits
6134 mScroller.fling(mScrollX, mScrollY, -vx, -vy, 0, maxX, 0, maxY,
6135 maxX == 0 ? 0 : mOverflingDistance, mOverflingDistance);
6136 // Duration is calculated based on velocity. With range boundaries and overscroll
6137 // we may not know how long the final animation will take. (Hence the deprecation
6138 // warning on the call below.) It's not a big deal for scroll bars but if webcore
6139 // resumes during this effect we will take a performance hit. See computeScroll;
6140 // we resume webcore there when the animation is finished.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006141 final int time = mScroller.getDuration();
Mike Cleronf116bf82009-09-27 19:14:12 -07006142 awakenScrollBars(time);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006143 invalidate();
6144 }
6145
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07006146 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006147 * Returns a view containing zoom controls i.e. +/- buttons. The caller is
6148 * in charge of installing this view to the view hierarchy. This view will
6149 * become visible when the user starts scrolling via touch and fade away if
6150 * the user does not interact with it.
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07006151 * <p/>
The Android Open Source Project10592532009-03-18 17:39:46 -07006152 * API version 3 introduces a built-in zoom mechanism that is shown
6153 * automatically by the MapView. This is the preferred approach for
6154 * showing the zoom UI.
6155 *
6156 * @deprecated The built-in zoom mechanism is preferred, see
6157 * {@link WebSettings#setBuiltInZoomControls(boolean)}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006158 */
The Android Open Source Project10592532009-03-18 17:39:46 -07006159 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006160 public View getZoomControls() {
The Android Open Source Project10592532009-03-18 17:39:46 -07006161 if (!getSettings().supportZoom()) {
6162 Log.w(LOGTAG, "This WebView doesn't support zoom.");
6163 return null;
6164 }
Derek Sollenberger90b6e482010-05-10 12:38:54 -04006165 return mZoomManager.getExternalZoomPicker();
The Android Open Source Project10592532009-03-18 17:39:46 -07006166 }
6167
Derek Sollenberger90b6e482010-05-10 12:38:54 -04006168 void dismissZoomControl() {
6169 mZoomManager.dismissZoomPicker();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006170 }
6171
Derek Sollenberger03e48912010-05-18 17:03:42 -04006172 float getDefaultZoomScale() {
Derek Sollenberger341e22f2010-06-02 12:34:34 -04006173 return mZoomManager.getDefaultScale();
Derek Sollenberger03e48912010-05-18 17:03:42 -04006174 }
6175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006176 /**
Grace Kloba6164ef12010-06-01 15:59:13 -07006177 * @return TRUE if the WebView can be zoomed in.
6178 */
6179 public boolean canZoomIn() {
6180 return mZoomManager.canZoomIn();
6181 }
6182
6183 /**
6184 * @return TRUE if the WebView can be zoomed out.
6185 */
6186 public boolean canZoomOut() {
6187 return mZoomManager.canZoomOut();
6188 }
6189
6190 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006191 * Perform zoom in in the webview
6192 * @return TRUE if zoom in succeeds. FALSE if no zoom changes.
6193 */
6194 public boolean zoomIn() {
Derek Sollenberger03e48912010-05-18 17:03:42 -04006195 return mZoomManager.zoomIn();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006196 }
6197
6198 /**
6199 * Perform zoom out in the webview
6200 * @return TRUE if zoom out succeeds. FALSE if no zoom changes.
6201 */
6202 public boolean zoomOut() {
Derek Sollenberger03e48912010-05-18 17:03:42 -04006203 return mZoomManager.zoomOut();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006204 }
6205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006206 private void updateSelection() {
6207 if (mNativeClass == 0) {
6208 return;
6209 }
6210 // mLastTouchX and mLastTouchY are the point in the current viewport
Leon Scroggins0236e672009-09-02 21:12:08 -04006211 int contentX = viewToContentX((int) mLastTouchX + mScrollX);
6212 int contentY = viewToContentY((int) mLastTouchY + mScrollY);
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07006213 Rect rect = new Rect(contentX - mNavSlop, contentY - mNavSlop,
6214 contentX + mNavSlop, contentY + mNavSlop);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006215 nativeSelectBestAt(rect);
Cary Clarkb8491342010-11-29 16:23:19 -05006216 mInitialHitTestResult = hitTestResult(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006217 }
6218
Leon Scroggins0f5ad842009-07-17 15:08:34 -04006219 /**
Leon Scroggins72543e12009-07-23 15:29:45 -04006220 * Scroll the focused text field/area to match the WebTextView
Cary Clarkeaa18de2009-09-28 12:50:42 -04006221 * @param xPercent New x position of the WebTextView from 0 to 1.
Leon Scroggins72543e12009-07-23 15:29:45 -04006222 * @param y New y position of the WebTextView in view coordinates
6223 */
Cary Clarkeaa18de2009-09-28 12:50:42 -04006224 /*package*/ void scrollFocusedTextInput(float xPercent, int y) {
Leon Scroggins72543e12009-07-23 15:29:45 -04006225 if (!inEditingMode() || mWebViewCore == null) {
6226 return;
6227 }
Cary Clarkeaa18de2009-09-28 12:50:42 -04006228 mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT,
Leon Scrogginsd3997e52009-09-21 14:15:18 -04006229 // Since this position is relative to the top of the text input
6230 // field, we do not need to take the title bar's height into
6231 // consideration.
Cary Clarkeaa18de2009-09-28 12:50:42 -04006232 viewToContentDimension(y),
6233 new Float(xPercent));
Leon Scroggins72543e12009-07-23 15:29:45 -04006234 }
6235
6236 /**
Leon Scroggins0f5ad842009-07-17 15:08:34 -04006237 * Set our starting point and time for a drag from the WebTextView.
6238 */
6239 /*package*/ void initiateTextFieldDrag(float x, float y, long eventTime) {
6240 if (!inEditingMode()) {
6241 return;
6242 }
6243 mLastTouchX = x + (float) (mWebTextView.getLeft() - mScrollX);
6244 mLastTouchY = y + (float) (mWebTextView.getTop() - mScrollY);
6245 mLastTouchTime = eventTime;
6246 if (!mScroller.isFinished()) {
Cary Clark278ce052009-08-31 16:08:42 -04006247 abortAnimation();
Grace Kloba96949ef2010-01-25 09:53:01 -08006248 mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY);
Leon Scroggins0f5ad842009-07-17 15:08:34 -04006249 }
6250 mSnapScrollMode = SNAP_NONE;
6251 mVelocityTracker = VelocityTracker.obtain();
6252 mTouchMode = TOUCH_DRAG_START_MODE;
6253 }
6254
6255 /**
6256 * Given a motion event from the WebTextView, set its location to our
6257 * coordinates, and handle the event.
6258 */
6259 /*package*/ boolean textFieldDrag(MotionEvent event) {
6260 if (!inEditingMode()) {
6261 return false;
6262 }
Leon Scroggins72543e12009-07-23 15:29:45 -04006263 mDragFromTextInput = true;
Leon Scroggins0f5ad842009-07-17 15:08:34 -04006264 event.offsetLocation((float) (mWebTextView.getLeft() - mScrollX),
6265 (float) (mWebTextView.getTop() - mScrollY));
Leon Scroggins72543e12009-07-23 15:29:45 -04006266 boolean result = onTouchEvent(event);
6267 mDragFromTextInput = false;
6268 return result;
Leon Scroggins0f5ad842009-07-17 15:08:34 -04006269 }
6270
Leon Scroggins6679f2f2009-08-12 18:48:10 -04006271 /**
Leon Scrogginsf90b1262009-11-24 14:49:21 -05006272 * Due a touch up from a WebTextView. This will be handled by webkit to
Leon Scroggins6679f2f2009-08-12 18:48:10 -04006273 * change the selection.
6274 * @param event MotionEvent in the WebTextView's coordinates.
6275 */
6276 /*package*/ void touchUpOnTextField(MotionEvent event) {
6277 if (!inEditingMode()) {
6278 return;
6279 }
Leon Scroggins0236e672009-09-02 21:12:08 -04006280 int x = viewToContentX((int) event.getX() + mWebTextView.getLeft());
6281 int y = viewToContentY((int) event.getY() + mWebTextView.getTop());
Leon Scrogginsf90b1262009-11-24 14:49:21 -05006282 nativeMotionUp(x, y, mNavSlop);
Leon Scroggins6679f2f2009-08-12 18:48:10 -04006283 }
6284
Leon Scroggins1d96ca02009-10-23 11:49:03 -04006285 /**
6286 * Called when pressing the center key or trackball on a textfield.
6287 */
6288 /*package*/ void centerKeyPressOnTextField() {
6289 mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(),
6290 nativeCursorNodePointer());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006291 }
6292
6293 private void doShortPress() {
6294 if (mNativeClass == 0) {
6295 return;
6296 }
Grace Klobac2242f22010-03-05 14:00:26 -08006297 if (mPreventDefault == PREVENT_DEFAULT_YES) {
6298 return;
6299 }
6300 mTouchMode = TOUCH_DONE_MODE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006301 switchOutDrawHistory();
6302 // mLastTouchX and mLastTouchY are the point in the current viewport
Leon Scroggins0236e672009-09-02 21:12:08 -04006303 int contentX = viewToContentX((int) mLastTouchX + mScrollX);
6304 int contentY = viewToContentY((int) mLastTouchY + mScrollY);
Grace Kloba178db412010-05-18 22:22:23 -07006305 if (getSettings().supportTouchOnly()) {
6306 removeTouchHighlight(false);
6307 WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData();
6308 // use "0" as generation id to inform WebKit to use the same x/y as
6309 // it used when processing GET_TOUCH_HIGHLIGHT_RECTS
6310 touchUpData.mMoveGeneration = 0;
6311 mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData);
6312 } else if (nativePointInNavCache(contentX, contentY, mNavSlop)) {
Cary Clark1cb97ee2009-12-11 12:10:36 -05006313 WebViewCore.MotionUpData motionUpData = new WebViewCore
6314 .MotionUpData();
6315 motionUpData.mFrame = nativeCacheHitFramePointer();
6316 motionUpData.mNode = nativeCacheHitNodePointer();
6317 motionUpData.mBounds = nativeCacheHitNodeBounds();
6318 motionUpData.mX = contentX;
6319 motionUpData.mY = contentY;
6320 mWebViewCore.sendMessageAtFrontOfQueue(EventHub.VALID_NODE_BOUNDS,
6321 motionUpData);
6322 } else {
Cary Clarkbad0c542010-01-11 14:58:21 -05006323 doMotionUp(contentX, contentY);
Cary Clark1cb97ee2009-12-11 12:10:36 -05006324 }
6325 }
6326
Cary Clarkbad0c542010-01-11 14:58:21 -05006327 private void doMotionUp(int contentX, int contentY) {
Leon Scroggins81bd7882010-10-26 16:35:57 -04006328 if (nativeMotionUp(contentX, contentY, mNavSlop) && mLogEvent) {
Dan Egnor18e93962010-02-10 19:27:58 -08006329 EventLog.writeEvent(EventLogTags.BROWSER_SNAP_CENTER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006330 }
Cary Clarkd6982c92009-05-29 11:02:22 -04006331 if (nativeHasCursorNode() && !nativeCursorIsTextInput()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006332 playSoundEffect(SoundEffectConstants.CLICK);
6333 }
6334 }
6335
Grace Klobac6f95fe2010-03-10 13:25:34 -08006336 /*
6337 * Return true if the view (Plugin) is fully visible and maximized inside
6338 * the WebView.
6339 */
Derek Sollenberger15c5ddb2010-06-10 12:31:29 -04006340 boolean isPluginFitOnScreen(ViewManager.ChildView view) {
6341 final int viewWidth = getViewWidth();
6342 final int viewHeight = getViewHeightWithTitle();
6343 float scale = Math.min((float) viewWidth / view.width, (float) viewHeight / view.height);
Derek Sollenberger369aca22010-06-09 14:11:59 -04006344 scale = mZoomManager.computeScaleWithLimits(scale);
Derek Sollenberger15c5ddb2010-06-10 12:31:29 -04006345 return !mZoomManager.willScaleTriggerZoom(scale)
6346 && contentToViewX(view.x) >= mScrollX
6347 && contentToViewX(view.x + view.width) <= mScrollX + viewWidth
6348 && contentToViewY(view.y) >= mScrollY
6349 && contentToViewY(view.y + view.height) <= mScrollY + viewHeight;
Grace Klobac6f95fe2010-03-10 13:25:34 -08006350 }
6351
6352 /*
Grace Klobae8300a12010-03-12 13:32:55 -08006353 * Maximize and center the rectangle, specified in the document coordinate
6354 * space, inside the WebView. If the zoom doesn't need to be changed, do an
6355 * animated scroll to center it. If the zoom needs to be changed, find the
6356 * zoom center and do a smooth zoom transition.
Grace Klobac6f95fe2010-03-10 13:25:34 -08006357 */
Derek Sollenberger15c5ddb2010-06-10 12:31:29 -04006358 void centerFitRect(int docX, int docY, int docWidth, int docHeight) {
Grace Klobac6f95fe2010-03-10 13:25:34 -08006359 int viewWidth = getViewWidth();
6360 int viewHeight = getViewHeightWithTitle();
Grace Klobae8300a12010-03-12 13:32:55 -08006361 float scale = Math.min((float) viewWidth / docWidth, (float) viewHeight
6362 / docHeight);
Derek Sollenberger369aca22010-06-09 14:11:59 -04006363 scale = mZoomManager.computeScaleWithLimits(scale);
Derek Sollenberger03e48912010-05-18 17:03:42 -04006364 if (!mZoomManager.willScaleTriggerZoom(scale)) {
Grace Klobae8300a12010-03-12 13:32:55 -08006365 pinScrollTo(contentToViewX(docX + docWidth / 2) - viewWidth / 2,
6366 contentToViewY(docY + docHeight / 2) - viewHeight / 2,
Grace Klobac6f95fe2010-03-10 13:25:34 -08006367 true, 0);
6368 } else {
Derek Sollenbergerbffa8512010-06-10 14:24:03 -04006369 float actualScale = mZoomManager.getScale();
Derek Sollenberger03e48912010-05-18 17:03:42 -04006370 float oldScreenX = docX * actualScale - mScrollX;
Grace Kloba1e65d9e2010-03-12 19:19:48 -08006371 float rectViewX = docX * scale;
6372 float rectViewWidth = docWidth * scale;
6373 float newMaxWidth = mContentWidth * scale;
6374 float newScreenX = (viewWidth - rectViewWidth) / 2;
Grace Klobac6f95fe2010-03-10 13:25:34 -08006375 // pin the newX to the WebView
Grace Klobae8300a12010-03-12 13:32:55 -08006376 if (newScreenX > rectViewX) {
6377 newScreenX = rectViewX;
6378 } else if (newScreenX > (newMaxWidth - rectViewX - rectViewWidth)) {
6379 newScreenX = viewWidth - (newMaxWidth - rectViewX);
Grace Klobac6f95fe2010-03-10 13:25:34 -08006380 }
Derek Sollenberger03e48912010-05-18 17:03:42 -04006381 float zoomCenterX = (oldScreenX * scale - newScreenX * actualScale)
6382 / (scale - actualScale);
6383 float oldScreenY = docY * actualScale + getTitleHeight()
Grace Kloba1e65d9e2010-03-12 19:19:48 -08006384 - mScrollY;
6385 float rectViewY = docY * scale + getTitleHeight();
6386 float rectViewHeight = docHeight * scale;
6387 float newMaxHeight = mContentHeight * scale + getTitleHeight();
6388 float newScreenY = (viewHeight - rectViewHeight) / 2;
Grace Klobac6f95fe2010-03-10 13:25:34 -08006389 // pin the newY to the WebView
Grace Klobae8300a12010-03-12 13:32:55 -08006390 if (newScreenY > rectViewY) {
6391 newScreenY = rectViewY;
6392 } else if (newScreenY > (newMaxHeight - rectViewY - rectViewHeight)) {
6393 newScreenY = viewHeight - (newMaxHeight - rectViewY);
Grace Klobac6f95fe2010-03-10 13:25:34 -08006394 }
Derek Sollenberger03e48912010-05-18 17:03:42 -04006395 float zoomCenterY = (oldScreenY * scale - newScreenY * actualScale)
6396 / (scale - actualScale);
6397 mZoomManager.setZoomCenter(zoomCenterX, zoomCenterY);
Derek Sollenberger87b17be52010-06-01 11:49:31 -04006398 mZoomManager.startZoomAnimation(scale, false);
Grace Klobac6f95fe2010-03-10 13:25:34 -08006399 }
6400 }
6401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006402 // Called by JNI to handle a touch on a node representing an email address,
6403 // address, or phone number
6404 private void overrideLoading(String url) {
6405 mCallbackProxy.uiOverrideUrlLoading(url);
6406 }
6407
6408 @Override
6409 public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
Leon Scroggins III26723fc2010-04-19 13:21:42 -04006410 // FIXME: If a subwindow is showing find, and the user touches the
6411 // background window, it can steal focus.
6412 if (mFindIsUp) return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006413 boolean result = false;
6414 if (inEditingMode()) {
Leon Scrogginsd3465f62009-06-02 10:57:54 -04006415 result = mWebTextView.requestFocus(direction,
6416 previouslyFocusedRect);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006417 } else {
6418 result = super.requestFocus(direction, previouslyFocusedRect);
6419 if (mWebViewCore.getSettings().getNeedInitialFocus()) {
6420 // For cases such as GMail, where we gain focus from a direction,
6421 // we want to move to the first available link.
6422 // FIXME: If there are no visible links, we may not want to
6423 int fakeKeyDirection = 0;
6424 switch(direction) {
6425 case View.FOCUS_UP:
6426 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_UP;
6427 break;
6428 case View.FOCUS_DOWN:
6429 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_DOWN;
6430 break;
6431 case View.FOCUS_LEFT:
6432 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_LEFT;
6433 break;
6434 case View.FOCUS_RIGHT:
6435 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_RIGHT;
6436 break;
6437 default:
6438 return result;
6439 }
Cary Clarkd6982c92009-05-29 11:02:22 -04006440 if (mNativeClass != 0 && !nativeHasCursorNode()) {
Leon Scrogginsb127c8f2010-03-05 15:42:17 -05006441 navHandledKey(fakeKeyDirection, 1, true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006442 }
6443 }
6444 }
6445 return result;
6446 }
6447
6448 @Override
6449 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
6450 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
6451
6452 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
6453 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
6454 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
6455 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
6456
6457 int measuredHeight = heightSize;
6458 int measuredWidth = widthSize;
6459
6460 // Grab the content size from WebViewCore.
Grace Klobae621d6f2009-09-11 13:20:39 -07006461 int contentHeight = contentToViewDimension(mContentHeight);
6462 int contentWidth = contentToViewDimension(mContentWidth);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006463
6464// Log.d(LOGTAG, "------- measure " + heightMode);
6465
6466 if (heightMode != MeasureSpec.EXACTLY) {
6467 mHeightCanMeasure = true;
6468 measuredHeight = contentHeight;
6469 if (heightMode == MeasureSpec.AT_MOST) {
6470 // If we are larger than the AT_MOST height, then our height can
6471 // no longer be measured and we should scroll internally.
6472 if (measuredHeight > heightSize) {
6473 measuredHeight = heightSize;
6474 mHeightCanMeasure = false;
6475 }
6476 }
6477 } else {
6478 mHeightCanMeasure = false;
6479 }
6480 if (mNativeClass != 0) {
6481 nativeSetHeightCanMeasure(mHeightCanMeasure);
6482 }
6483 // For the width, always use the given size unless unspecified.
6484 if (widthMode == MeasureSpec.UNSPECIFIED) {
6485 mWidthCanMeasure = true;
6486 measuredWidth = contentWidth;
6487 } else {
6488 mWidthCanMeasure = false;
6489 }
6490
6491 synchronized (this) {
6492 setMeasuredDimension(measuredWidth, measuredHeight);
6493 }
6494 }
6495
6496 @Override
6497 public boolean requestChildRectangleOnScreen(View child,
6498 Rect rect,
6499 boolean immediate) {
Derek Sollenberger03e48912010-05-18 17:03:42 -04006500 // don't scroll while in zoom animation. When it is done, we will adjust
6501 // the necessary components (e.g., WebTextView if it is in editing mode)
Derek Sollenberger293c3602010-06-04 10:44:48 -04006502 if (mZoomManager.isFixedLengthAnimationInProgress()) {
Derek Sollenberger03e48912010-05-18 17:03:42 -04006503 return false;
6504 }
6505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006506 rect.offset(child.getLeft() - child.getScrollX(),
6507 child.getTop() - child.getScrollY());
6508
Cary Clark31b83672010-03-09 09:20:34 -05006509 Rect content = new Rect(viewToContentX(mScrollX),
6510 viewToContentY(mScrollY),
6511 viewToContentX(mScrollX + getWidth()
6512 - getVerticalScrollbarWidth()),
6513 viewToContentY(mScrollY + getViewHeightWithTitle()));
6514 content = nativeSubtractLayers(content);
6515 int screenTop = contentToViewY(content.top);
6516 int screenBottom = contentToViewY(content.bottom);
6517 int height = screenBottom - screenTop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006518 int scrollYDelta = 0;
6519
Leon Scrogginsbed911a2009-03-31 14:29:35 -07006520 if (rect.bottom > screenBottom) {
6521 int oneThirdOfScreenHeight = height / 3;
6522 if (rect.height() > 2 * oneThirdOfScreenHeight) {
6523 // If the rectangle is too tall to fit in the bottom two thirds
6524 // of the screen, place it at the top.
6525 scrollYDelta = rect.top - screenTop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006526 } else {
Leon Scrogginsbed911a2009-03-31 14:29:35 -07006527 // If the rectangle will still fit on screen, we want its
6528 // top to be in the top third of the screen.
6529 scrollYDelta = rect.top - (screenTop + oneThirdOfScreenHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006530 }
6531 } else if (rect.top < screenTop) {
Leon Scrogginsbed911a2009-03-31 14:29:35 -07006532 scrollYDelta = rect.top - screenTop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006533 }
6534
Cary Clark31b83672010-03-09 09:20:34 -05006535 int screenLeft = contentToViewX(content.left);
6536 int screenRight = contentToViewX(content.right);
6537 int width = screenRight - screenLeft;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006538 int scrollXDelta = 0;
6539
6540 if (rect.right > screenRight && rect.left > screenLeft) {
6541 if (rect.width() > width) {
6542 scrollXDelta += (rect.left - screenLeft);
6543 } else {
6544 scrollXDelta += (rect.right - screenRight);
6545 }
6546 } else if (rect.left < screenLeft) {
6547 scrollXDelta -= (screenLeft - rect.left);
6548 }
6549
6550 if ((scrollYDelta | scrollXDelta) != 0) {
6551 return pinScrollBy(scrollXDelta, scrollYDelta, !immediate, 0);
6552 }
6553
6554 return false;
6555 }
Cary Clarkd6982c92009-05-29 11:02:22 -04006556
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006557 /* package */ void replaceTextfieldText(int oldStart, int oldEnd,
6558 String replace, int newStart, int newEnd) {
Cary Clarkded054c2009-06-15 10:26:08 -04006559 WebViewCore.ReplaceTextData arg = new WebViewCore.ReplaceTextData();
6560 arg.mReplace = replace;
6561 arg.mNewStart = newStart;
6562 arg.mNewEnd = newEnd;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07006563 mTextGeneration++;
Leon Scroggins43488fc2009-07-06 14:32:49 -04006564 arg.mTextGeneration = mTextGeneration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006565 mWebViewCore.sendMessage(EventHub.REPLACE_TEXT, oldStart, oldEnd, arg);
6566 }
6567
6568 /* package */ void passToJavaScript(String currentText, KeyEvent event) {
Cary Clarkded054c2009-06-15 10:26:08 -04006569 WebViewCore.JSKeyData arg = new WebViewCore.JSKeyData();
6570 arg.mEvent = event;
6571 arg.mCurrentText = currentText;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006572 // Increase our text generation number, and pass it to webcore thread
6573 mTextGeneration++;
6574 mWebViewCore.sendMessage(EventHub.PASS_TO_JS, mTextGeneration, 0, arg);
6575 // WebKit's document state is not saved until about to leave the page.
Cary Clarkd6982c92009-05-29 11:02:22 -04006576 // To make sure the host application, like Browser, has the up to date
6577 // document state when it goes to background, we force to save the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006578 // document state.
6579 mWebViewCore.removeMessages(EventHub.SAVE_DOCUMENT_STATE);
6580 mWebViewCore.sendMessageDelayed(EventHub.SAVE_DOCUMENT_STATE,
Cary Clarkd6982c92009-05-29 11:02:22 -04006581 cursorData(), 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006582 }
6583
Andrei Popescu04098572010-03-09 12:23:19 +00006584 /* package */ synchronized WebViewCore getWebViewCore() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006585 return mWebViewCore;
6586 }
6587
6588 //-------------------------------------------------------------------------
6589 // Methods can be called from a separate thread, like WebViewCore
6590 // If it needs to call the View system, it has to send message.
6591 //-------------------------------------------------------------------------
6592
6593 /**
6594 * General handler to receive message coming from webkit thread
6595 */
6596 class PrivateHandler extends Handler {
6597 @Override
6598 public void handleMessage(Message msg) {
Cary Clark3e88ddc2009-10-08 14:59:46 -04006599 // exclude INVAL_RECT_MSG_ID since it is frequently output
6600 if (DebugFlags.WEB_VIEW && msg.what != INVAL_RECT_MSG_ID) {
Grace Klobac2242f22010-03-05 14:00:26 -08006601 if (msg.what >= FIRST_PRIVATE_MSG_ID
6602 && msg.what <= LAST_PRIVATE_MSG_ID) {
6603 Log.v(LOGTAG, HandlerPrivateDebugString[msg.what
6604 - FIRST_PRIVATE_MSG_ID]);
6605 } else if (msg.what >= FIRST_PACKAGE_MSG_ID
6606 && msg.what <= LAST_PACKAGE_MSG_ID) {
6607 Log.v(LOGTAG, HandlerPackageDebugString[msg.what
6608 - FIRST_PACKAGE_MSG_ID]);
6609 } else {
6610 Log.v(LOGTAG, Integer.toString(msg.what));
6611 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006612 }
Grace Kloba207308a2009-09-27 11:44:14 -07006613 if (mWebViewCore == null) {
6614 // after WebView's destroy() is called, skip handling messages.
6615 return;
6616 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006617 switch (msg.what) {
6618 case REMEMBER_PASSWORD: {
6619 mDatabase.setUsernamePassword(
6620 msg.getData().getString("host"),
6621 msg.getData().getString("username"),
6622 msg.getData().getString("password"));
6623 ((Message) msg.obj).sendToTarget();
6624 break;
6625 }
6626 case NEVER_REMEMBER_PASSWORD: {
6627 mDatabase.setUsernamePassword(
6628 msg.getData().getString("host"), null, null);
6629 ((Message) msg.obj).sendToTarget();
6630 break;
6631 }
Grace Klobac2242f22010-03-05 14:00:26 -08006632 case PREVENT_DEFAULT_TIMEOUT: {
6633 // if timeout happens, cancel it so that it won't block UI
6634 // to continue handling touch events
6635 if ((msg.arg1 == MotionEvent.ACTION_DOWN
6636 && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES)
6637 || (msg.arg1 == MotionEvent.ACTION_MOVE
6638 && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN)) {
6639 cancelWebCoreTouchEvent(
6640 viewToContentX((int) mLastTouchX + mScrollX),
6641 viewToContentY((int) mLastTouchY + mScrollY),
6642 true);
Grace Klobaf58af622009-09-24 17:41:23 -07006643 }
Grace Klobac2242f22010-03-05 14:00:26 -08006644 break;
6645 }
Cary Clark6f5dfc62010-11-11 13:09:20 -05006646 case SCROLL_SELECT_TEXT: {
6647 if (mAutoScrollX == 0 && mAutoScrollY == 0) {
6648 mSentAutoScrollMessage = false;
6649 break;
6650 }
6651 scrollBy(mAutoScrollX, mAutoScrollY);
6652 sendEmptyMessageDelayed(
6653 SCROLL_SELECT_TEXT, SELECT_SCROLL_INTERVAL);
6654 break;
6655 }
Grace Klobac2242f22010-03-05 14:00:26 -08006656 case SWITCH_TO_SHORTPRESS: {
Cary Clarkb8491342010-11-29 16:23:19 -05006657 mInitialHitTestResult = null; // set by updateSelection()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006658 if (mTouchMode == TOUCH_INIT_MODE) {
Grace Kloba178db412010-05-18 22:22:23 -07006659 if (!getSettings().supportTouchOnly()
6660 && mPreventDefault != PREVENT_DEFAULT_YES) {
Grace Klobac2242f22010-03-05 14:00:26 -08006661 mTouchMode = TOUCH_SHORTPRESS_START_MODE;
6662 updateSelection();
6663 } else {
6664 // set to TOUCH_SHORTPRESS_MODE so that it won't
6665 // trigger double tap any more
6666 mTouchMode = TOUCH_SHORTPRESS_MODE;
6667 }
Grace Kloba8b97e4b2009-07-28 13:11:38 -07006668 } else if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
6669 mTouchMode = TOUCH_DONE_MODE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006670 }
6671 break;
6672 }
6673 case SWITCH_TO_LONGPRESS: {
Grace Kloba178db412010-05-18 22:22:23 -07006674 if (getSettings().supportTouchOnly()) {
6675 removeTouchHighlight(false);
6676 }
Grace Klobac2242f22010-03-05 14:00:26 -08006677 if (inFullScreenMode() || mDeferTouchProcess) {
6678 TouchEventData ted = new TouchEventData();
Grace Kloba5f68d6f2009-12-08 18:42:54 -08006679 ted.mAction = WebViewCore.ACTION_LONGPRESS;
Huahui Wu41865f42010-09-02 13:41:41 -07006680 ted.mPoints = new Point[1];
6681 ted.mPoints[0] = new Point(viewToContentX((int) mLastTouchX + mScrollX),
6682 viewToContentY((int) mLastTouchY + mScrollY));
Grace Klobac2242f22010-03-05 14:00:26 -08006683 // metaState for long press is tricky. Should it be the
6684 // state when the press started or when the press was
6685 // released? Or some intermediary key state? For
6686 // simplicity for now, we don't set it.
Ben Murdoch8a032a32010-02-02 18:20:11 +00006687 ted.mMetaState = 0;
Grace Klobac2242f22010-03-05 14:00:26 -08006688 ted.mReprocess = mDeferTouchProcess;
Grace Kloba5f68d6f2009-12-08 18:42:54 -08006689 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
Grace Klobac2242f22010-03-05 14:00:26 -08006690 } else if (mPreventDefault != PREVENT_DEFAULT_YES) {
Grace Kloba6c451b72009-06-25 12:25:30 -07006691 mTouchMode = TOUCH_DONE_MODE;
Grace Klobac2242f22010-03-05 14:00:26 -08006692 performLongClick();
Grace Kloba6c451b72009-06-25 12:25:30 -07006693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006694 break;
6695 }
Grace Kloba8b97e4b2009-07-28 13:11:38 -07006696 case RELEASE_SINGLE_TAP: {
Grace Klobac2242f22010-03-05 14:00:26 -08006697 doShortPress();
Grace Kloba8b97e4b2009-07-28 13:11:38 -07006698 break;
6699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006700 case SCROLL_BY_MSG_ID:
6701 setContentScrollBy(msg.arg1, msg.arg2, (Boolean) msg.obj);
6702 break;
6703 case SYNC_SCROLL_TO_MSG_ID:
6704 if (mUserScroll) {
Cary Clarkd6982c92009-05-29 11:02:22 -04006705 // if user has scrolled explicitly, don't sync the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006706 // scroll position any more
6707 mUserScroll = false;
6708 break;
6709 }
Leon Scroggins1bf397f2010-11-16 16:02:25 -05006710 setContentScrollTo(msg.arg1, msg.arg2);
6711 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006712 case SCROLL_TO_MSG_ID:
6713 if (setContentScrollTo(msg.arg1, msg.arg2)) {
6714 // if we can't scroll to the exact position due to pin,
Cary Clarkd6982c92009-05-29 11:02:22 -04006715 // send a message to WebCore to re-scroll when we get a
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006716 // new picture
6717 mUserScroll = false;
6718 mWebViewCore.sendMessage(EventHub.SYNC_SCROLL,
6719 msg.arg1, msg.arg2);
6720 }
6721 break;
6722 case SPAWN_SCROLL_TO_MSG_ID:
6723 spawnContentScrollTo(msg.arg1, msg.arg2);
6724 break;
Grace Kloba769ed212010-01-27 10:52:47 -08006725 case UPDATE_ZOOM_RANGE: {
Derek Sollenbergerb983c892010-06-28 08:38:28 -04006726 WebViewCore.ViewState viewState = (WebViewCore.ViewState) msg.obj;
Grace Kloba188bf8d2010-04-07 11:30:19 -07006727 // mScrollX contains the new minPrefWidth
Derek Sollenbergerb983c892010-06-28 08:38:28 -04006728 mZoomManager.updateZoomRange(viewState, getViewWidth(), viewState.mScrollX);
Grace Kloba769ed212010-01-27 10:52:47 -08006729 break;
6730 }
Grace Kloba8abd50b2010-07-08 15:02:14 -07006731 case REPLACE_BASE_CONTENT: {
6732 nativeReplaceBaseContent(msg.arg1);
6733 break;
6734 }
Grace Klobae397a882009-08-06 12:04:14 -07006735 case NEW_PICTURE_MSG_ID: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006736 // called for new content
Shimeng (Simon) Wang50b10342010-10-21 17:14:39 -07006737 mUserScroll = false;
Derek Sollenberger341e22f2010-06-02 12:34:34 -04006738 final WebViewCore.DrawData draw = (WebViewCore.DrawData) msg.obj;
Nicolas Roard67a9f2a2010-09-07 14:49:06 -07006739 setBaseLayer(draw.mBaseLayer, draw.mInvalRegion.getBounds());
Derek Sollenberger7e6bf6f2010-10-28 09:33:47 -04006740 final Point viewSize = draw.mViewSize;
Derek Sollenbergerb983c892010-06-28 08:38:28 -04006741 WebViewCore.ViewState viewState = draw.mViewState;
6742 boolean isPictureAfterFirstLayout = viewState != null;
6743 if (isPictureAfterFirstLayout) {
Shimeng (Simon) Wang0a4a70d2010-06-30 11:48:05 -07006744 // Reset the last sent data here since dealing with new page.
6745 mLastWidthSent = 0;
Derek Sollenbergerb983c892010-06-28 08:38:28 -04006746 mZoomManager.onFirstLayout(draw);
Shimeng (Simon) Wang1c02c6a2010-03-04 18:06:49 -08006747 if (!mDrawHistory) {
Derek Sollenbergerb983c892010-06-28 08:38:28 -04006748 setContentScrollTo(viewState.mScrollX, viewState.mScrollY);
Shimeng (Simon) Wang1c02c6a2010-03-04 18:06:49 -08006749 // As we are on a new page, remove the WebTextView. This
6750 // is necessary for page loads driven by webkit, and in
6751 // particular when the user was on a password field, so
6752 // the WebTextView was visible.
Leon Scroggins2aed7762010-08-13 17:11:42 -04006753 clearTextEntry();
Mike Reed8b302092009-11-12 12:50:20 -05006754 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006755 }
Derek Sollenberger341e22f2010-06-02 12:34:34 -04006756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006757 // We update the layout (i.e. request a layout from the
6758 // view system) if the last view size that we sent to
6759 // WebCore matches the view size of the picture we just
6760 // received in the fixed dimension.
6761 final boolean updateLayout = viewSize.x == mLastWidthSent
6762 && viewSize.y == mLastHeightSent;
Derek Sollenberger7e6bf6f2010-10-28 09:33:47 -04006763 recordNewContentSize(draw.mContentSize.x,
6764 draw.mContentSize.y, updateLayout);
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04006765 if (DebugFlags.WEB_VIEW) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006766 Rect b = draw.mInvalRegion.getBounds();
6767 Log.v(LOGTAG, "NEW_PICTURE_MSG_ID {" +
6768 b.left+","+b.top+","+b.right+","+b.bottom+"}");
6769 }
Mike Reede9e86b82009-09-15 11:26:53 -04006770 invalidateContentRect(draw.mInvalRegion.getBounds());
Derek Sollenberger341e22f2010-06-02 12:34:34 -04006771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006772 if (mPictureListener != null) {
6773 mPictureListener.onNewPicture(WebView.this, capturePicture());
6774 }
Derek Sollenberger341e22f2010-06-02 12:34:34 -04006775
6776 // update the zoom information based on the new picture
6777 mZoomManager.onNewPicture(draw);
6778
Cary Clark5da9aeb2009-10-06 17:40:53 -04006779 if (draw.mFocusSizeChanged && inEditingMode()) {
6780 mFocusSizeChanged = true;
6781 }
Derek Sollenbergerb983c892010-06-28 08:38:28 -04006782 if (isPictureAfterFirstLayout) {
Grace Kloba9a67c822009-12-20 11:33:58 -08006783 mViewManager.postReadyToDrawAll();
6784 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006785 break;
Grace Klobae397a882009-08-06 12:04:14 -07006786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006787 case WEBCORE_INITIALIZED_MSG_ID:
6788 // nativeCreate sets mNativeClass to a non-zero value
6789 nativeCreate(msg.arg1);
6790 break;
6791 case UPDATE_TEXTFIELD_TEXT_MSG_ID:
6792 // Make sure that the textfield is currently focused
Cary Clarkd6982c92009-05-29 11:02:22 -04006793 // and representing the same node as the pointer.
6794 if (inEditingMode() &&
Leon Scrogginsd3465f62009-06-02 10:57:54 -04006795 mWebTextView.isSameTextField(msg.arg1)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006796 if (msg.getData().getBoolean("password")) {
Leon Scrogginsd3465f62009-06-02 10:57:54 -04006797 Spannable text = (Spannable) mWebTextView.getText();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006798 int start = Selection.getSelectionStart(text);
6799 int end = Selection.getSelectionEnd(text);
Leon Scrogginsd3465f62009-06-02 10:57:54 -04006800 mWebTextView.setInPassword(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006801 // Restore the selection, which may have been
6802 // ruined by setInPassword.
Leon Scrogginsd3465f62009-06-02 10:57:54 -04006803 Spannable pword =
6804 (Spannable) mWebTextView.getText();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006805 Selection.setSelection(pword, start, end);
6806 // If the text entry has created more events, ignore
6807 // this one.
6808 } else if (msg.arg2 == mTextGeneration) {
Leon Scrogginsef7af282010-11-11 14:20:06 -05006809 String text = (String) msg.obj;
6810 if (null == text) {
6811 text = "";
6812 }
6813 mWebTextView.setTextAndKeepSelection(text);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006814 }
6815 }
6816 break;
Leon Scrogginsb4157792010-03-18 12:42:33 -04006817 case REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID:
6818 displaySoftKeyboard(true);
Leon Scroggins III901a7c22010-04-20 15:14:02 -04006819 // fall through to UPDATE_TEXT_SELECTION_MSG_ID
Leon Scroggins6679f2f2009-08-12 18:48:10 -04006820 case UPDATE_TEXT_SELECTION_MSG_ID:
Leon Scrogginsb4157792010-03-18 12:42:33 -04006821 updateTextSelectionFromMessage(msg.arg1, msg.arg2,
6822 (WebViewCore.TextSelectionData) msg.obj);
Leon Scroggins6679f2f2009-08-12 18:48:10 -04006823 break;
Leon Scrogginsf2e17a82010-09-24 15:58:50 -04006824 case FORM_DID_BLUR:
6825 if (inEditingMode()
6826 && mWebTextView.isSameTextField(msg.arg1)) {
6827 hideSoftKeyboard();
6828 }
6829 break;
Leon Scroggins3a503392010-01-06 17:04:38 -05006830 case RETURN_LABEL:
6831 if (inEditingMode()
6832 && mWebTextView.isSameTextField(msg.arg1)) {
6833 mWebTextView.setHint((String) msg.obj);
6834 InputMethodManager imm
6835 = InputMethodManager.peekInstance();
6836 // The hint is propagated to the IME in
6837 // onCreateInputConnection. If the IME is already
6838 // active, restart it so that its hint text is updated.
6839 if (imm != null && imm.isActive(mWebTextView)) {
6840 imm.restartInput(mWebTextView);
6841 }
6842 }
6843 break;
Leon Scroggins9ab32b62010-05-03 14:19:50 +01006844 case UNHANDLED_NAV_KEY:
Leon Scrogginsb127c8f2010-03-05 15:42:17 -05006845 navHandledKey(msg.arg1, 1, false, 0);
Cary Clark215b72c2009-06-26 14:38:43 -04006846 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006847 case UPDATE_TEXT_ENTRY_MSG_ID:
Cary Clarkd6982c92009-05-29 11:02:22 -04006848 // this is sent after finishing resize in WebViewCore. Make
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006849 // sure the text edit box is still on the screen.
Cary Clarkd6982c92009-05-29 11:02:22 -04006850 if (inEditingMode() && nativeCursorIsTextInput()) {
Leon Scrogginsd3465f62009-06-02 10:57:54 -04006851 mWebTextView.bringIntoView();
Leon Scroggins4890feb2009-07-02 10:37:10 -04006852 rebuildWebTextView();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006854 break;
Cary Clark243ea062009-06-25 10:49:32 -04006855 case CLEAR_TEXT_ENTRY:
Leon Scroggins2aed7762010-08-13 17:11:42 -04006856 clearTextEntry();
Cary Clark243ea062009-06-25 10:49:32 -04006857 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006858 case INVAL_RECT_MSG_ID: {
6859 Rect r = (Rect)msg.obj;
6860 if (r == null) {
6861 invalidate();
6862 } else {
6863 // we need to scale r from content into view coords,
6864 // which viewInvalidate() does for us
6865 viewInvalidate(r.left, r.top, r.right, r.bottom);
6866 }
6867 break;
6868 }
Leon Scrogginsd3465f62009-06-02 10:57:54 -04006869 case REQUEST_FORM_DATA:
Cary Clarkded054c2009-06-15 10:26:08 -04006870 AutoCompleteAdapter adapter = (AutoCompleteAdapter) msg.obj;
Leon Scrogginsd3465f62009-06-02 10:57:54 -04006871 if (mWebTextView.isSameTextField(msg.arg1)) {
Leon Scrogginsd3465f62009-06-02 10:57:54 -04006872 mWebTextView.setAdapterCustom(adapter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006873 }
6874 break;
Grace Kloba96949ef2010-01-25 09:53:01 -08006875 case RESUME_WEBCORE_PRIORITY:
Grace Klobaa7bc87c2010-01-29 14:56:25 -08006876 WebViewCore.resumePriority();
Grace Kloba524aab572010-04-07 11:12:52 -07006877 WebViewCore.resumeUpdatePicture(mWebViewCore);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006878 break;
6879
Leon Scrogginse3225672009-06-03 15:53:13 -04006880 case LONG_PRESS_CENTER:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006881 // as this is shared by keydown and trackballdown, reset all
6882 // the states
Leon Scrogginse3225672009-06-03 15:53:13 -04006883 mGotCenterDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006884 mTrackballDown = false;
Grace Kloba98e6fcf2010-01-27 15:20:30 -08006885 performLongClick();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006886 break;
6887
6888 case WEBCORE_NEED_TOUCH_EVENTS:
6889 mForwardTouchEvents = (msg.arg1 != 0);
6890 break;
6891
6892 case PREVENT_TOUCH_ID:
Grace Klobac2242f22010-03-05 14:00:26 -08006893 if (inFullScreenMode()) {
6894 break;
6895 }
6896 if (msg.obj == null) {
6897 if (msg.arg1 == MotionEvent.ACTION_DOWN
6898 && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES) {
6899 // if prevent default is called from WebCore, UI
6900 // will not handle the rest of the touch events any
6901 // more.
6902 mPreventDefault = msg.arg2 == 1 ? PREVENT_DEFAULT_YES
6903 : PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN;
6904 } else if (msg.arg1 == MotionEvent.ACTION_MOVE
6905 && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) {
6906 // the return for the first ACTION_MOVE will decide
6907 // whether UI will handle touch or not. Currently no
6908 // support for alternating prevent default
6909 mPreventDefault = msg.arg2 == 1 ? PREVENT_DEFAULT_YES
6910 : PREVENT_DEFAULT_NO;
6911 }
Grace Kloba178db412010-05-18 22:22:23 -07006912 if (mPreventDefault == PREVENT_DEFAULT_YES) {
6913 mTouchHighlightRegion.setEmpty();
6914 }
Grace Klobac2242f22010-03-05 14:00:26 -08006915 } else if (msg.arg2 == 0) {
6916 // prevent default is not called in WebCore, so the
6917 // message needs to be reprocessed in UI
6918 TouchEventData ted = (TouchEventData) msg.obj;
6919 switch (ted.mAction) {
6920 case MotionEvent.ACTION_DOWN:
Huahui Wu41865f42010-09-02 13:41:41 -07006921 mLastDeferTouchX = contentToViewX(ted.mPoints[0].x)
Grace Klobac2242f22010-03-05 14:00:26 -08006922 - mScrollX;
Huahui Wu41865f42010-09-02 13:41:41 -07006923 mLastDeferTouchY = contentToViewY(ted.mPoints[0].y)
Grace Klobac2242f22010-03-05 14:00:26 -08006924 - mScrollY;
6925 mDeferTouchMode = TOUCH_INIT_MODE;
6926 break;
6927 case MotionEvent.ACTION_MOVE: {
6928 // no snapping in defer process
Huahui Wu41865f42010-09-02 13:41:41 -07006929 int x = contentToViewX(ted.mPoints[0].x) - mScrollX;
6930 int y = contentToViewY(ted.mPoints[0].y) - mScrollY;
Grace Klobac2242f22010-03-05 14:00:26 -08006931 if (mDeferTouchMode != TOUCH_DRAG_MODE) {
6932 mDeferTouchMode = TOUCH_DRAG_MODE;
6933 mLastDeferTouchX = x;
6934 mLastDeferTouchY = y;
6935 startDrag();
6936 }
Grace Klobaad7a1d72010-03-31 23:04:56 -07006937 int deltaX = pinLocX((int) (mScrollX
6938 + mLastDeferTouchX - x))
6939 - mScrollX;
6940 int deltaY = pinLocY((int) (mScrollY
6941 + mLastDeferTouchY - y))
6942 - mScrollY;
Patrick Scott2f492272010-12-03 09:52:35 -05006943 startScrollingLayer(x, y);
Grace Klobaad7a1d72010-03-31 23:04:56 -07006944 doDrag(deltaX, deltaY);
6945 if (deltaX != 0) mLastDeferTouchX = x;
6946 if (deltaY != 0) mLastDeferTouchY = y;
Grace Klobac2242f22010-03-05 14:00:26 -08006947 break;
Grace Klobaf58af622009-09-24 17:41:23 -07006948 }
Grace Klobac2242f22010-03-05 14:00:26 -08006949 case MotionEvent.ACTION_UP:
6950 case MotionEvent.ACTION_CANCEL:
6951 if (mDeferTouchMode == TOUCH_DRAG_MODE) {
6952 // no fling in defer process
Adam Powell637d3372010-08-25 14:37:03 -07006953 mScroller.springBack(mScrollX, mScrollY, 0,
6954 computeMaxScrollX(), 0,
6955 computeMaxScrollY());
6956 invalidate();
Grace Klobac2242f22010-03-05 14:00:26 -08006957 WebViewCore.resumePriority();
Grace Klobaaa373c92010-04-16 15:49:36 -07006958 WebViewCore.resumeUpdatePicture(mWebViewCore);
Grace Klobac2242f22010-03-05 14:00:26 -08006959 }
6960 mDeferTouchMode = TOUCH_DONE_MODE;
6961 break;
6962 case WebViewCore.ACTION_DOUBLETAP:
6963 // doDoubleTap() needs mLastTouchX/Y as anchor
Huahui Wu41865f42010-09-02 13:41:41 -07006964 mLastTouchX = contentToViewX(ted.mPoints[0].x) - mScrollX;
6965 mLastTouchY = contentToViewY(ted.mPoints[0].y) - mScrollY;
Derek Sollenberger15c5ddb2010-06-10 12:31:29 -04006966 mZoomManager.handleDoubleTap(mLastTouchX, mLastTouchY);
Grace Klobac2242f22010-03-05 14:00:26 -08006967 mDeferTouchMode = TOUCH_DONE_MODE;
6968 break;
6969 case WebViewCore.ACTION_LONGPRESS:
6970 HitTestResult hitTest = getHitTestResult();
6971 if (hitTest != null && hitTest.mType
6972 != HitTestResult.UNKNOWN_TYPE) {
6973 performLongClick();
Grace Klobac2242f22010-03-05 14:00:26 -08006974 }
6975 mDeferTouchMode = TOUCH_DONE_MODE;
6976 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006977 }
6978 }
6979 break;
6980
Derek Sollenberger4c41e8d2009-06-29 13:49:27 -04006981 case REQUEST_KEYBOARD:
6982 if (msg.arg1 == 0) {
6983 hideSoftKeyboard();
6984 } else {
Leon Scrogginsb4157792010-03-18 12:42:33 -04006985 displaySoftKeyboard(false);
Derek Sollenberger4c41e8d2009-06-29 13:49:27 -04006986 }
6987 break;
6988
Leon Scroggins5de63892009-10-29 09:48:43 -04006989 case FIND_AGAIN:
6990 // Ignore if find has been dismissed.
Leon Scrogginsfe026bd2010-08-24 14:16:09 -04006991 if (mFindIsUp && mFindCallback != null) {
6992 mFindCallback.findAll();
Leon Scroggins5de63892009-10-29 09:48:43 -04006993 }
6994 break;
6995
Cary Clark25415e22009-10-12 13:41:28 -04006996 case DRAG_HELD_MOTIONLESS:
6997 mHeldMotionless = MOTIONLESS_TRUE;
6998 invalidate();
6999 // fall through to keep scrollbars awake
7000
7001 case AWAKEN_SCROLL_BARS:
7002 if (mTouchMode == TOUCH_DRAG_MODE
7003 && mHeldMotionless == MOTIONLESS_TRUE) {
7004 awakenScrollBars(ViewConfiguration
7005 .getScrollDefaultDelay(), false);
7006 mPrivateHandler.sendMessageDelayed(mPrivateHandler
7007 .obtainMessage(AWAKEN_SCROLL_BARS),
7008 ViewConfiguration.getScrollDefaultDelay());
7009 }
7010 break;
Cary Clark1cb97ee2009-12-11 12:10:36 -05007011
7012 case DO_MOTION_UP:
Cary Clarkbad0c542010-01-11 14:58:21 -05007013 doMotionUp(msg.arg1, msg.arg2);
Cary Clark1cb97ee2009-12-11 12:10:36 -05007014 break;
7015
Grace Kloba3a0def22010-01-23 21:11:54 -08007016 case SHOW_FULLSCREEN: {
Derek Sollenbergerc28ff442010-03-09 17:38:49 -05007017 View view = (View) msg.obj;
7018 int npp = msg.arg1;
Grace Kloba11438c32009-12-16 11:39:12 -08007019
Derek Sollenbergerfa89c502010-10-01 11:19:36 -04007020 if (inFullScreenMode()) {
Derek Sollenbergerc28ff442010-03-09 17:38:49 -05007021 Log.w(LOGTAG, "Should not have another full screen.");
Derek Sollenbergerfa89c502010-10-01 11:19:36 -04007022 dismissFullScreenMode();
Derek Sollenbergerc28ff442010-03-09 17:38:49 -05007023 }
7024 mFullScreenHolder = new PluginFullScreenHolder(WebView.this, npp);
7025 mFullScreenHolder.setContentView(view);
7026 mFullScreenHolder.setCancelable(false);
7027 mFullScreenHolder.setCanceledOnTouchOutside(false);
7028 mFullScreenHolder.show();
7029
7030 break;
7031 }
Grace Kloba11438c32009-12-16 11:39:12 -08007032 case HIDE_FULLSCREEN:
Derek Sollenbergerfa89c502010-10-01 11:19:36 -04007033 dismissFullScreenMode();
Grace Kloba11438c32009-12-16 11:39:12 -08007034 break;
7035
Leon Scrogginse26efa32009-12-15 16:38:45 -05007036 case DOM_FOCUS_CHANGED:
7037 if (inEditingMode()) {
7038 nativeClearCursor();
7039 rebuildWebTextView();
7040 }
7041 break;
7042
Grace Kloba3a0def22010-01-23 21:11:54 -08007043 case SHOW_RECT_MSG_ID: {
7044 WebViewCore.ShowRectData data = (WebViewCore.ShowRectData) msg.obj;
7045 int x = mScrollX;
Shimeng (Simon) Wang8a7ac8d2010-01-28 15:05:51 -08007046 int left = contentToViewX(data.mLeft);
Grace Kloba3a0def22010-01-23 21:11:54 -08007047 int width = contentToViewDimension(data.mWidth);
7048 int maxWidth = contentToViewDimension(data.mContentWidth);
7049 int viewWidth = getViewWidth();
7050 if (width < viewWidth) {
7051 // center align
7052 x += left + width / 2 - mScrollX - viewWidth / 2;
7053 } else {
7054 x += (int) (left + data.mXPercentInDoc * width
7055 - mScrollX - data.mXPercentInView * viewWidth);
7056 }
Shimeng (Simon) Wang8a7ac8d2010-01-28 15:05:51 -08007057 if (DebugFlags.WEB_VIEW) {
7058 Log.v(LOGTAG, "showRectMsg=(left=" + left + ",width=" +
7059 width + ",maxWidth=" + maxWidth +
7060 ",viewWidth=" + viewWidth + ",x="
7061 + x + ",xPercentInDoc=" + data.mXPercentInDoc +
7062 ",xPercentInView=" + data.mXPercentInView+ ")");
7063 }
Grace Kloba3a0def22010-01-23 21:11:54 -08007064 // use the passing content width to cap x as the current
7065 // mContentWidth may not be updated yet
7066 x = Math.max(0,
7067 (Math.min(maxWidth, x + viewWidth)) - viewWidth);
Shimeng (Simon) Wang8a7ac8d2010-01-28 15:05:51 -08007068 int top = contentToViewY(data.mTop);
Grace Kloba3a0def22010-01-23 21:11:54 -08007069 int height = contentToViewDimension(data.mHeight);
7070 int maxHeight = contentToViewDimension(data.mContentHeight);
7071 int viewHeight = getViewHeight();
Shimeng (Simon) Wang8a7ac8d2010-01-28 15:05:51 -08007072 int y = (int) (top + data.mYPercentInDoc * height -
7073 data.mYPercentInView * viewHeight);
7074 if (DebugFlags.WEB_VIEW) {
7075 Log.v(LOGTAG, "showRectMsg=(top=" + top + ",height=" +
7076 height + ",maxHeight=" + maxHeight +
7077 ",viewHeight=" + viewHeight + ",y="
7078 + y + ",yPercentInDoc=" + data.mYPercentInDoc +
7079 ",yPercentInView=" + data.mYPercentInView+ ")");
Grace Kloba3a0def22010-01-23 21:11:54 -08007080 }
7081 // use the passing content height to cap y as the current
7082 // mContentHeight may not be updated yet
7083 y = Math.max(0,
7084 (Math.min(maxHeight, y + viewHeight) - viewHeight));
Shimeng (Simon) Wangb7f17d42010-02-08 15:17:21 -08007085 // We need to take into account the visible title height
7086 // when scrolling since y is an absolute view position.
7087 y = Math.max(0, y - getVisibleTitleHeight());
Grace Kloba3a0def22010-01-23 21:11:54 -08007088 scrollTo(x, y);
7089 }
7090 break;
7091
Grace Klobae8300a12010-03-12 13:32:55 -08007092 case CENTER_FIT_RECT:
7093 Rect r = (Rect)msg.obj;
Grace Klobae8300a12010-03-12 13:32:55 -08007094 centerFitRect(r.left, r.top, r.width(), r.height());
7095 break;
7096
Grace Kloba50004bc2010-04-13 22:58:51 -07007097 case SET_SCROLLBAR_MODES:
7098 mHorizontalScrollBarMode = msg.arg1;
7099 mVerticalScrollBarMode = msg.arg2;
7100 break;
7101
Svetoslav Ganovda355512010-05-12 22:04:44 -07007102 case SELECTION_STRING_CHANGED:
7103 if (mAccessibilityInjector != null) {
7104 String selectionString = (String) msg.obj;
7105 mAccessibilityInjector.onSelectionStringChange(selectionString);
7106 }
7107 break;
7108
Grace Kloba178db412010-05-18 22:22:23 -07007109 case SET_TOUCH_HIGHLIGHT_RECTS:
7110 invalidate(mTouchHighlightRegion.getBounds());
7111 mTouchHighlightRegion.setEmpty();
7112 if (msg.obj != null) {
7113 ArrayList<Rect> rects = (ArrayList<Rect>) msg.obj;
7114 for (Rect rect : rects) {
7115 Rect viewRect = contentToViewRect(rect);
7116 // some sites, like stories in nytimes.com, set
7117 // mouse event handler in the top div. It is not
7118 // user friendly to highlight the div if it covers
7119 // more than half of the screen.
7120 if (viewRect.width() < getWidth() >> 1
7121 || viewRect.height() < getHeight() >> 1) {
7122 mTouchHighlightRegion.union(viewRect);
7123 invalidate(viewRect);
7124 } else {
7125 Log.w(LOGTAG, "Skip the huge selection rect:"
7126 + viewRect);
7127 }
7128 }
7129 }
7130 break;
7131
Elliott Slaughterb48fdbe2010-06-30 11:39:52 -07007132 case SAVE_WEBARCHIVE_FINISHED:
7133 SaveWebArchiveMessage saveMessage = (SaveWebArchiveMessage)msg.obj;
7134 if (saveMessage.mCallback != null) {
7135 saveMessage.mCallback.onReceiveValue(saveMessage.mResultFile);
7136 }
7137 break;
7138
Ben Murdoch62275a42010-09-07 11:27:28 +01007139 case SET_AUTOFILLABLE:
Ben Murdochdb8d19c2010-10-29 11:44:17 +01007140 mAutoFillData = (WebViewCore.AutoFillData) msg.obj;
Ben Murdoch62275a42010-09-07 11:27:28 +01007141 if (mWebTextView != null) {
Ben Murdochdb8d19c2010-10-29 11:44:17 +01007142 mWebTextView.setAutoFillable(mAutoFillData.getQueryId());
Ben Murdoch62275a42010-09-07 11:27:28 +01007143 rebuildWebTextView();
7144 }
7145 break;
7146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007147 default:
7148 super.handleMessage(msg);
7149 break;
7150 }
7151 }
7152 }
7153
Leon Scrogginsb4157792010-03-18 12:42:33 -04007154 /**
7155 * Used when receiving messages for REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID
7156 * and UPDATE_TEXT_SELECTION_MSG_ID. Update the selection of WebTextView.
7157 */
7158 private void updateTextSelectionFromMessage(int nodePointer,
7159 int textGeneration, WebViewCore.TextSelectionData data) {
7160 if (inEditingMode()
7161 && mWebTextView.isSameTextField(nodePointer)
7162 && textGeneration == mTextGeneration) {
7163 mWebTextView.setSelectionFromWebKit(data.mStart, data.mEnd);
7164 }
7165 }
7166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007167 // Class used to use a dropdown for a <select> element
7168 private class InvokeListBox implements Runnable {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007169 // Whether the listbox allows multiple selection.
7170 private boolean mMultiple;
7171 // Passed in to a list with multiple selection to tell
7172 // which items are selected.
7173 private int[] mSelectedArray;
Cary Clarkd6982c92009-05-29 11:02:22 -04007174 // Passed in to a list with single selection to tell
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007175 // where the initial selection is.
7176 private int mSelection;
7177
7178 private Container[] mContainers;
7179
7180 // Need these to provide stable ids to my ArrayAdapter,
7181 // which normally does not have stable ids. (Bug 1250098)
7182 private class Container extends Object {
Leon Scrogginsa8da1732009-10-19 19:04:30 -04007183 /**
7184 * Possible values for mEnabled. Keep in sync with OptionStatus in
7185 * WebViewCore.cpp
7186 */
7187 final static int OPTGROUP = -1;
7188 final static int OPTION_DISABLED = 0;
7189 final static int OPTION_ENABLED = 1;
7190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007191 String mString;
Leon Scrogginsa8da1732009-10-19 19:04:30 -04007192 int mEnabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007193 int mId;
7194
7195 public String toString() {
7196 return mString;
7197 }
7198 }
7199
7200 /**
Cary Clarkd6982c92009-05-29 11:02:22 -04007201 * Subclass ArrayAdapter so we can disable OptionGroupLabels,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007202 * and allow filtering.
7203 */
7204 private class MyArrayListAdapter extends ArrayAdapter<Container> {
7205 public MyArrayListAdapter(Context context, Container[] objects, boolean multiple) {
Cary Clarkd6982c92009-05-29 11:02:22 -04007206 super(context,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007207 multiple ? com.android.internal.R.layout.select_dialog_multichoice :
Cary Clarkd6982c92009-05-29 11:02:22 -04007208 com.android.internal.R.layout.select_dialog_singlechoice,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007209 objects);
7210 }
7211
7212 @Override
Leon Scrogginsa8da1732009-10-19 19:04:30 -04007213 public View getView(int position, View convertView,
7214 ViewGroup parent) {
7215 // Always pass in null so that we will get a new CheckedTextView
7216 // Otherwise, an item which was previously used as an <optgroup>
7217 // element (i.e. has no check), could get used as an <option>
7218 // element, which needs a checkbox/radio, but it would not have
7219 // one.
7220 convertView = super.getView(position, null, parent);
7221 Container c = item(position);
Leon Scrogginsf1e1fb32009-10-21 13:39:33 -04007222 if (c != null && Container.OPTION_ENABLED != c.mEnabled) {
7223 // ListView does not draw dividers between disabled and
7224 // enabled elements. Use a LinearLayout to provide dividers
7225 LinearLayout layout = new LinearLayout(mContext);
7226 layout.setOrientation(LinearLayout.VERTICAL);
7227 if (position > 0) {
7228 View dividerTop = new View(mContext);
7229 dividerTop.setBackgroundResource(
7230 android.R.drawable.divider_horizontal_bright);
7231 layout.addView(dividerTop);
7232 }
7233
7234 if (Container.OPTGROUP == c.mEnabled) {
7235 // Currently select_dialog_multichoice and
7236 // select_dialog_singlechoice are CheckedTextViews. If
7237 // that changes, the class cast will no longer be valid.
7238 Assert.assertTrue(
7239 convertView instanceof CheckedTextView);
7240 ((CheckedTextView) convertView).setCheckMarkDrawable(
7241 null);
7242 } else {
7243 // c.mEnabled == Container.OPTION_DISABLED
7244 // Draw the disabled element in a disabled state.
7245 convertView.setEnabled(false);
7246 }
7247
7248 layout.addView(convertView);
7249 if (position < getCount() - 1) {
7250 View dividerBottom = new View(mContext);
7251 dividerBottom.setBackgroundResource(
7252 android.R.drawable.divider_horizontal_bright);
7253 layout.addView(dividerBottom);
7254 }
7255 return layout;
Leon Scrogginsa8da1732009-10-19 19:04:30 -04007256 }
7257 return convertView;
7258 }
7259
7260 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007261 public boolean hasStableIds() {
Leon Scroggins3667ce42009-05-13 15:58:03 -04007262 // AdapterView's onChanged method uses this to determine whether
7263 // to restore the old state. Return false so that the old (out
7264 // of date) state does not replace the new, valid state.
7265 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007266 }
7267
7268 private Container item(int position) {
7269 if (position < 0 || position >= getCount()) {
7270 return null;
7271 }
7272 return (Container) getItem(position);
7273 }
7274
7275 @Override
7276 public long getItemId(int position) {
7277 Container item = item(position);
7278 if (item == null) {
7279 return -1;
7280 }
7281 return item.mId;
7282 }
7283
7284 @Override
7285 public boolean areAllItemsEnabled() {
7286 return false;
7287 }
7288
7289 @Override
7290 public boolean isEnabled(int position) {
7291 Container item = item(position);
7292 if (item == null) {
7293 return false;
7294 }
Leon Scrogginsa8da1732009-10-19 19:04:30 -04007295 return Container.OPTION_ENABLED == item.mEnabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007296 }
7297 }
7298
Leon Scrogginsa8da1732009-10-19 19:04:30 -04007299 private InvokeListBox(String[] array, int[] enabled, int[] selected) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007300 mMultiple = true;
7301 mSelectedArray = selected;
7302
7303 int length = array.length;
7304 mContainers = new Container[length];
7305 for (int i = 0; i < length; i++) {
7306 mContainers[i] = new Container();
7307 mContainers[i].mString = array[i];
7308 mContainers[i].mEnabled = enabled[i];
7309 mContainers[i].mId = i;
7310 }
7311 }
7312
Leon Scrogginsa8da1732009-10-19 19:04:30 -04007313 private InvokeListBox(String[] array, int[] enabled, int selection) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007314 mSelection = selection;
7315 mMultiple = false;
7316
7317 int length = array.length;
7318 mContainers = new Container[length];
7319 for (int i = 0; i < length; i++) {
7320 mContainers[i] = new Container();
7321 mContainers[i].mString = array[i];
7322 mContainers[i].mEnabled = enabled[i];
7323 mContainers[i].mId = i;
7324 }
7325 }
7326
Leon Scroggins3667ce42009-05-13 15:58:03 -04007327 /*
7328 * Whenever the data set changes due to filtering, this class ensures
7329 * that the checked item remains checked.
7330 */
7331 private class SingleDataSetObserver extends DataSetObserver {
7332 private long mCheckedId;
7333 private ListView mListView;
7334 private Adapter mAdapter;
7335
7336 /*
7337 * Create a new observer.
7338 * @param id The ID of the item to keep checked.
7339 * @param l ListView for getting and clearing the checked states
7340 * @param a Adapter for getting the IDs
7341 */
7342 public SingleDataSetObserver(long id, ListView l, Adapter a) {
7343 mCheckedId = id;
7344 mListView = l;
7345 mAdapter = a;
7346 }
7347
7348 public void onChanged() {
7349 // The filter may have changed which item is checked. Find the
7350 // item that the ListView thinks is checked.
7351 int position = mListView.getCheckedItemPosition();
7352 long id = mAdapter.getItemId(position);
7353 if (mCheckedId != id) {
7354 // Clear the ListView's idea of the checked item, since
7355 // it is incorrect
7356 mListView.clearChoices();
7357 // Search for mCheckedId. If it is in the filtered list,
7358 // mark it as checked
7359 int count = mAdapter.getCount();
7360 for (int i = 0; i < count; i++) {
7361 if (mAdapter.getItemId(i) == mCheckedId) {
7362 mListView.setItemChecked(i, true);
7363 break;
7364 }
7365 }
7366 }
7367 }
7368
7369 public void onInvalidate() {}
7370 }
7371
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007372 public void run() {
7373 final ListView listView = (ListView) LayoutInflater.from(mContext)
7374 .inflate(com.android.internal.R.layout.select_dialog, null);
Cary Clarkd6982c92009-05-29 11:02:22 -04007375 final MyArrayListAdapter adapter = new
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007376 MyArrayListAdapter(mContext, mContainers, mMultiple);
7377 AlertDialog.Builder b = new AlertDialog.Builder(mContext)
7378 .setView(listView).setCancelable(true)
7379 .setInverseBackgroundForced(true);
Cary Clarkd6982c92009-05-29 11:02:22 -04007380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007381 if (mMultiple) {
7382 b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
7383 public void onClick(DialogInterface dialog, int which) {
7384 mWebViewCore.sendMessage(
Cary Clarkd6982c92009-05-29 11:02:22 -04007385 EventHub.LISTBOX_CHOICES,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007386 adapter.getCount(), 0,
7387 listView.getCheckedItemPositions());
7388 }});
Leon Scroggins238ddbb2009-04-02 10:47:53 -07007389 b.setNegativeButton(android.R.string.cancel,
7390 new DialogInterface.OnClickListener() {
7391 public void onClick(DialogInterface dialog, int which) {
7392 mWebViewCore.sendMessage(
7393 EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
7394 }});
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007395 }
Mattias Falk0ae2ec82010-09-16 16:24:46 +02007396 mListBoxDialog = b.create();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007397 listView.setAdapter(adapter);
7398 listView.setFocusableInTouchMode(true);
7399 // There is a bug (1250103) where the checks in a ListView with
7400 // multiple items selected are associated with the positions, not
Cary Clarkd6982c92009-05-29 11:02:22 -04007401 // the ids, so the items do not properly retain their checks when
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007402 // filtered. Do not allow filtering on multiple lists until
7403 // that bug is fixed.
Cary Clarkd6982c92009-05-29 11:02:22 -04007404
Leon Scroggins3667ce42009-05-13 15:58:03 -04007405 listView.setTextFilterEnabled(!mMultiple);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007406 if (mMultiple) {
7407 listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
7408 int length = mSelectedArray.length;
7409 for (int i = 0; i < length; i++) {
7410 listView.setItemChecked(mSelectedArray[i], true);
7411 }
7412 } else {
7413 listView.setOnItemClickListener(new OnItemClickListener() {
7414 public void onItemClick(AdapterView parent, View v,
7415 int position, long id) {
7416 mWebViewCore.sendMessage(
7417 EventHub.SINGLE_LISTBOX_CHOICE, (int)id, 0);
Mattias Falk0ae2ec82010-09-16 16:24:46 +02007418 mListBoxDialog.dismiss();
7419 mListBoxDialog = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007420 }
7421 });
7422 if (mSelection != -1) {
7423 listView.setSelection(mSelection);
7424 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
7425 listView.setItemChecked(mSelection, true);
Leon Scroggins3667ce42009-05-13 15:58:03 -04007426 DataSetObserver observer = new SingleDataSetObserver(
7427 adapter.getItemId(mSelection), listView, adapter);
7428 adapter.registerDataSetObserver(observer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007429 }
7430 }
Mattias Falk0ae2ec82010-09-16 16:24:46 +02007431 mListBoxDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007432 public void onCancel(DialogInterface dialog) {
7433 mWebViewCore.sendMessage(
7434 EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
Mattias Falk0ae2ec82010-09-16 16:24:46 +02007435 mListBoxDialog = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007436 }
7437 });
Mattias Falk0ae2ec82010-09-16 16:24:46 +02007438 mListBoxDialog.show();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007439 }
7440 }
7441
7442 /*
7443 * Request a dropdown menu for a listbox with multiple selection.
7444 *
7445 * @param array Labels for the listbox.
Leon Scrogginsa8da1732009-10-19 19:04:30 -04007446 * @param enabledArray State for each element in the list. See static
7447 * integers in Container class.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007448 * @param selectedArray Which positions are initally selected.
7449 */
Leon Scrogginsa8da1732009-10-19 19:04:30 -04007450 void requestListBox(String[] array, int[] enabledArray, int[]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007451 selectedArray) {
7452 mPrivateHandler.post(
7453 new InvokeListBox(array, enabledArray, selectedArray));
7454 }
7455
7456 /*
7457 * Request a dropdown menu for a listbox with single selection or a single
7458 * <select> element.
7459 *
7460 * @param array Labels for the listbox.
Leon Scrogginsa8da1732009-10-19 19:04:30 -04007461 * @param enabledArray State for each element in the list. See static
7462 * integers in Container class.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007463 * @param selection Which position is initally selected.
7464 */
Leon Scrogginsa8da1732009-10-19 19:04:30 -04007465 void requestListBox(String[] array, int[] enabledArray, int selection) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007466 mPrivateHandler.post(
7467 new InvokeListBox(array, enabledArray, selection));
7468 }
7469
7470 // called by JNI
Leon Scroggins47fabbf2009-12-08 16:57:26 -05007471 private void sendMoveFocus(int frame, int node) {
7472 mWebViewCore.sendMessage(EventHub.SET_MOVE_FOCUS,
7473 new WebViewCore.CursorData(frame, node, 0, 0));
7474 }
7475
7476 // called by JNI
Cary Clarkd6982c92009-05-29 11:02:22 -04007477 private void sendMoveMouse(int frame, int node, int x, int y) {
7478 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE,
7479 new WebViewCore.CursorData(frame, node, x, y));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007480 }
7481
Leon Scroggins0658e8f2009-06-26 14:09:09 -04007482 /*
7483 * Send a mouse move event to the webcore thread.
7484 *
7485 * @param removeFocus Pass true if the "mouse" cursor is now over a node
7486 * which wants key events, but it is not the focus. This
7487 * will make the visual appear as though nothing is in
7488 * focus. Remove the WebTextView, if present, and stop
7489 * drawing the blinking caret.
7490 * called by JNI
7491 */
7492 private void sendMoveMouseIfLatest(boolean removeFocus) {
7493 if (removeFocus) {
Leon Scroggins2aed7762010-08-13 17:11:42 -04007494 clearTextEntry();
Cary Clark19436562009-06-04 16:25:07 -04007495 }
Leon Scroggins0658e8f2009-06-26 14:09:09 -04007496 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE_IF_LATEST,
7497 cursorData());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007498 }
7499
7500 // called by JNI
Cary Clarkd6982c92009-05-29 11:02:22 -04007501 private void sendMotionUp(int touchGeneration,
Leon Scroggins6679f2f2009-08-12 18:48:10 -04007502 int frame, int node, int x, int y) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007503 WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData();
7504 touchUpData.mMoveGeneration = touchGeneration;
Cary Clarkd6982c92009-05-29 11:02:22 -04007505 touchUpData.mFrame = frame;
7506 touchUpData.mNode = node;
7507 touchUpData.mX = x;
7508 touchUpData.mY = y;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007509 mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData);
7510 }
7511
7512
7513 private int getScaledMaxXScroll() {
7514 int width;
7515 if (mHeightCanMeasure == false) {
7516 width = getViewWidth() / 4;
7517 } else {
7518 Rect visRect = new Rect();
7519 calcOurVisibleRect(visRect);
7520 width = visRect.width() / 2;
7521 }
7522 // FIXME the divisor should be retrieved from somewhere
Leon Scroggins0236e672009-09-02 21:12:08 -04007523 return viewToContentX(width);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007524 }
7525
7526 private int getScaledMaxYScroll() {
7527 int height;
7528 if (mHeightCanMeasure == false) {
7529 height = getViewHeight() / 4;
7530 } else {
7531 Rect visRect = new Rect();
7532 calcOurVisibleRect(visRect);
7533 height = visRect.height() / 2;
7534 }
7535 // FIXME the divisor should be retrieved from somewhere
7536 // the closest thing today is hard-coded into ScrollView.java
7537 // (from ScrollView.java, line 363) int maxJump = height/2;
Derek Sollenbergerbffa8512010-06-10 14:24:03 -04007538 return Math.round(height * mZoomManager.getInvScale());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007539 }
7540
7541 /**
7542 * Called by JNI to invalidate view
7543 */
7544 private void viewInvalidate() {
7545 invalidate();
7546 }
Cary Clarkd6982c92009-05-29 11:02:22 -04007547
Leon Scrogginsb127c8f2010-03-05 15:42:17 -05007548 /**
Leon Scroggins9ab32b62010-05-03 14:19:50 +01007549 * Pass the key directly to the page. This assumes that
7550 * nativePageShouldHandleShiftAndArrows() returned true.
Leon Scrogginsb127c8f2010-03-05 15:42:17 -05007551 */
Svetoslav Ganov9b756ac2010-11-05 15:42:22 -07007552 private void letPageHandleNavKey(int keyCode, long time, boolean down, int metaState) {
Leon Scrogginsb127c8f2010-03-05 15:42:17 -05007553 int keyEventAction;
7554 int eventHubAction;
7555 if (down) {
7556 keyEventAction = KeyEvent.ACTION_DOWN;
7557 eventHubAction = EventHub.KEY_DOWN;
7558 playSoundEffect(keyCodeToSoundsEffect(keyCode));
7559 } else {
7560 keyEventAction = KeyEvent.ACTION_UP;
7561 eventHubAction = EventHub.KEY_UP;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007562 }
Svetoslav Ganov9b756ac2010-11-05 15:42:22 -07007563
Leon Scrogginsb127c8f2010-03-05 15:42:17 -05007564 KeyEvent event = new KeyEvent(time, time, keyEventAction, keyCode,
Svetoslav Ganov9b756ac2010-11-05 15:42:22 -07007565 1, (metaState & KeyEvent.META_SHIFT_ON)
7566 | (metaState & KeyEvent.META_ALT_ON)
7567 | (metaState & KeyEvent.META_SYM_ON)
Jeff Brown6b53e8d2010-11-10 16:03:06 -08007568 , KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0);
Leon Scrogginsb127c8f2010-03-05 15:42:17 -05007569 mWebViewCore.sendMessage(eventHubAction, event);
7570 }
7571
7572 // return true if the key was handled
7573 private boolean navHandledKey(int keyCode, int count, boolean noScroll,
7574 long time) {
7575 if (mNativeClass == 0) {
7576 return false;
Cary Clark215b72c2009-06-26 14:38:43 -04007577 }
Cary Clark32820242010-12-03 10:27:20 -05007578 mInitialHitTestResult = null;
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04007579 mLastCursorTime = time;
7580 mLastCursorBounds = nativeGetCursorRingBounds();
7581 boolean keyHandled
7582 = nativeMoveCursor(keyCode, count, noScroll) == false;
Derek Sollenberger2e5c1502009-06-03 10:44:42 -04007583 if (DebugFlags.WEB_VIEW) {
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04007584 Log.v(LOGTAG, "navHandledKey mLastCursorBounds=" + mLastCursorBounds
7585 + " mLastCursorTime=" + mLastCursorTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007586 + " handled=" + keyHandled);
7587 }
7588 if (keyHandled == false || mHeightCanMeasure == false) {
7589 return keyHandled;
7590 }
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04007591 Rect contentCursorRingBounds = nativeGetCursorRingBounds();
7592 if (contentCursorRingBounds.isEmpty()) return keyHandled;
Mike Reede9e86b82009-09-15 11:26:53 -04007593 Rect viewCursorRingBounds = contentToViewRect(contentCursorRingBounds);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007594 Rect visRect = new Rect();
7595 calcOurVisibleRect(visRect);
7596 Rect outset = new Rect(visRect);
7597 int maxXScroll = visRect.width() / 2;
7598 int maxYScroll = visRect.height() / 2;
7599 outset.inset(-maxXScroll, -maxYScroll);
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04007600 if (Rect.intersects(outset, viewCursorRingBounds) == false) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007601 return keyHandled;
7602 }
7603 // FIXME: Necessary because ScrollView/ListView do not scroll left/right
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04007604 int maxH = Math.min(viewCursorRingBounds.right - visRect.right,
7605 maxXScroll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007606 if (maxH > 0) {
7607 pinScrollBy(maxH, 0, true, 0);
7608 } else {
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04007609 maxH = Math.max(viewCursorRingBounds.left - visRect.left,
7610 -maxXScroll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007611 if (maxH < 0) {
7612 pinScrollBy(maxH, 0, true, 0);
7613 }
7614 }
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04007615 if (mLastCursorBounds.isEmpty()) return keyHandled;
7616 if (mLastCursorBounds.equals(contentCursorRingBounds)) {
7617 return keyHandled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007618 }
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04007619 if (DebugFlags.WEB_VIEW) {
7620 Log.v(LOGTAG, "navHandledKey contentCursorRingBounds="
7621 + contentCursorRingBounds);
7622 }
7623 requestRectangleOnScreen(viewCursorRingBounds);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007624 mUserScroll = true;
7625 return keyHandled;
7626 }
Cary Clarkd6982c92009-05-29 11:02:22 -04007627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007628 /**
Svetoslav Ganov585f13f8d2010-08-10 07:59:15 -07007629 * @return If the page should receive Shift and arrows.
7630 */
7631 private boolean pageShouldHandleShiftAndArrows() {
7632 // TODO: Maybe the injected script should announce its presence in
7633 // the page meta-tag so the nativePageShouldHandleShiftAndArrows
7634 // will check that as one of the conditions it looks for
7635 return (nativePageShouldHandleShiftAndArrows() || mAccessibilityScriptInjected);
7636 }
7637
7638 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007639 * Set the background color. It's white by default. Pass
7640 * zero to make the view transparent.
7641 * @param color the ARGB color described by Color.java
7642 */
7643 public void setBackgroundColor(int color) {
7644 mBackgroundColor = color;
7645 mWebViewCore.sendMessage(EventHub.SET_BACKGROUND_COLOR, color);
7646 }
7647
7648 public void debugDump() {
7649 nativeDebugDump();
7650 mWebViewCore.sendMessage(EventHub.DUMP_NAVTREE);
7651 }
Cary Clarkd6982c92009-05-29 11:02:22 -04007652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007653 /**
Mike Reedefe2c722009-10-14 09:42:02 -04007654 * Draw the HTML page into the specified canvas. This call ignores any
7655 * view-specific zoom, scroll offset, or other changes. It does not draw
7656 * any view-specific chrome, such as progress or URL bars.
7657 *
7658 * @hide only needs to be accessible to Browser and testing
7659 */
7660 public void drawPage(Canvas canvas) {
Grace Kloba8abd50b2010-07-08 15:02:14 -07007661 nativeDraw(canvas, 0, 0, false);
Mike Reedefe2c722009-10-14 09:42:02 -04007662 }
7663
7664 /**
Ben Murdochecbc65c2010-01-13 10:54:56 +00007665 * Set the time to wait between passing touches to WebCore. See also the
7666 * TOUCH_SENT_INTERVAL member for further discussion.
7667 *
7668 * @hide This is only used by the DRT test application.
7669 */
7670 public void setTouchInterval(int interval) {
7671 mCurrentTouchInterval = interval;
7672 }
7673
7674 /**
Huahui Wu41865f42010-09-02 13:41:41 -07007675 * Toggle whether multi touch events should be sent to webkit
7676 * no matter if UI wants to handle it first.
7677 *
7678 * @hide This is only used by the webkit layout test.
7679 */
7680 public void setDeferMultiTouch(boolean value) {
7681 mDeferMultitouch = value;
7682 Log.v(LOGTAG, "set mDeferMultitouch to " + value);
7683 }
7684
7685 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007686 * Update our cache with updatedText.
7687 * @param updatedText The new text to put in our cache.
7688 */
7689 /* package */ void updateCachedTextfield(String updatedText) {
7690 // Also place our generation number so that when we look at the cache
7691 // we recognize that it is up to date.
7692 nativeUpdateCachedTextfield(updatedText, mTextGeneration);
7693 }
Cary Clarkd6982c92009-05-29 11:02:22 -04007694
Ben Murdoch62275a42010-09-07 11:27:28 +01007695 /*package*/ void autoFillForm(int autoFillQueryId) {
7696 mWebViewCore.sendMessage(EventHub.AUTOFILL_FORM, autoFillQueryId, /* unused */0);
7697 }
7698
Ben Murdoch1708ad52010-11-11 15:56:16 +00007699 /* package */ ViewManager getViewManager() {
7700 return mViewManager;
7701 }
7702
Cary Clark1cb97ee2009-12-11 12:10:36 -05007703 private native int nativeCacheHitFramePointer();
7704 private native Rect nativeCacheHitNodeBounds();
7705 private native int nativeCacheHitNodePointer();
Leon Scroggins4890feb2009-07-02 10:37:10 -04007706 /* package */ native void nativeClearCursor();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007707 private native void nativeCreate(int ptr);
Cary Clarkd6982c92009-05-29 11:02:22 -04007708 private native int nativeCursorFramePointer();
7709 private native Rect nativeCursorNodeBounds();
Cary Clarkaffa5d22010-01-07 12:18:23 -05007710 private native int nativeCursorNodePointer();
Cary Clarkd6982c92009-05-29 11:02:22 -04007711 /* package */ native boolean nativeCursorMatchesFocus();
7712 private native boolean nativeCursorIntersects(Rect visibleRect);
7713 private native boolean nativeCursorIsAnchor();
7714 private native boolean nativeCursorIsTextInput();
Cary Clarked56eda2009-06-18 09:48:47 -04007715 private native Point nativeCursorPosition();
Cary Clarkd6982c92009-05-29 11:02:22 -04007716 private native String nativeCursorText();
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04007717 /**
7718 * Returns true if the native cursor node says it wants to handle key events
7719 * (ala plugins). This can only be called if mNativeClass is non-zero!
7720 */
Cary Clark2f1d60c2009-06-03 08:05:53 -04007721 private native boolean nativeCursorWantsKeyEvents();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007722 private native void nativeDebugDump();
7723 private native void nativeDestroy();
Grace Kloba8abd50b2010-07-08 15:02:14 -07007724
7725 /**
7726 * Draw the picture set with a background color and extra. If
7727 * "splitIfNeeded" is true and the return value is not 0, the return value
7728 * MUST be passed to WebViewCore with SPLIT_PICTURE_SET message so that the
7729 * native allocation can be freed.
7730 */
7731 private native int nativeDraw(Canvas canvas, int color, int extra,
7732 boolean splitIfNeeded);
Cary Clarkd6982c92009-05-29 11:02:22 -04007733 private native void nativeDumpDisplayTree(String urlOrNull);
Cary Clark924af702010-06-04 16:37:43 -04007734 private native boolean nativeEvaluateLayersAnimations();
Nicolas Roard67a9f2a2010-09-07 14:49:06 -07007735 private native boolean nativeDrawGL(Rect rect, float scale, int extras);
Cary Clark924af702010-06-04 16:37:43 -04007736 private native void nativeExtendSelection(int x, int y);
Leon Scroggins4f4a5672010-10-19 13:58:11 -04007737 private native int nativeFindAll(String findLower, String findUpper,
7738 boolean sameAsLastSearch);
Cary Clarkd6982c92009-05-29 11:02:22 -04007739 private native void nativeFindNext(boolean forward);
Leon Scroggins3a503392010-01-06 17:04:38 -05007740 /* package */ native int nativeFocusCandidateFramePointer();
Leon Scrogginsf9b1a092010-03-31 15:32:36 -04007741 /* package */ native boolean nativeFocusCandidateHasNextTextfield();
Leon Scroggins69ec5c22010-04-22 16:27:21 -04007742 /* package */ native boolean nativeFocusCandidateIsPassword();
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04007743 private native boolean nativeFocusCandidateIsRtlText();
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04007744 private native boolean nativeFocusCandidateIsTextInput();
Leon Scrogginsaa7b9d72009-12-07 13:38:07 -05007745 /* package */ native int nativeFocusCandidateMaxLength();
Leon Scroggins0ca70882009-06-26 17:45:29 -04007746 /* package */ native String nativeFocusCandidateName();
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04007747 private native Rect nativeFocusCandidateNodeBounds();
Leon Scrogginsdfc07272010-10-12 13:40:23 -04007748 /**
7749 * @return A Rect with left, top, right, bottom set to the corresponding
7750 * padding values in the focus candidate, if it is a textfield/textarea with
7751 * a style. Otherwise return null. This is not actually a rectangle; Rect
7752 * is being used to pass four integers.
7753 */
7754 private native Rect nativeFocusCandidatePaddingRect();
Leon Scroggins69ec5c22010-04-22 16:27:21 -04007755 /* package */ native int nativeFocusCandidatePointer();
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04007756 private native String nativeFocusCandidateText();
Leon Scroggins56a102c2010-11-12 14:40:07 -05007757 /* package */ native float nativeFocusCandidateTextSize();
Leon Scroggins1ca56262010-11-18 14:03:03 -05007758 /* package */ native int nativeFocusCandidateLineHeight();
Leon Scrogginsaa7b9d72009-12-07 13:38:07 -05007759 /**
7760 * Returns an integer corresponding to WebView.cpp::type.
7761 * See WebTextView.setType()
7762 */
7763 private native int nativeFocusCandidateType();
Derek Sollenberger718d69f2009-10-19 15:56:43 -04007764 private native boolean nativeFocusIsPlugin();
Cary Clarke84a0db2010-03-17 15:58:20 -04007765 private native Rect nativeFocusNodeBounds();
Leon Scroggins4890feb2009-07-02 10:37:10 -04007766 /* package */ native int nativeFocusNodePointer();
Cary Clarkd6982c92009-05-29 11:02:22 -04007767 private native Rect nativeGetCursorRingBounds();
Cary Clark57d2c3a2009-12-23 13:57:15 -05007768 private native String nativeGetSelection();
Cary Clarkd6982c92009-05-29 11:02:22 -04007769 private native boolean nativeHasCursorNode();
7770 private native boolean nativeHasFocusNode();
Cary Clarke872f3a2009-06-11 09:51:11 -04007771 private native void nativeHideCursor();
Cary Clark924af702010-06-04 16:37:43 -04007772 private native boolean nativeHitSelection(int x, int y);
Cary Clarkd6982c92009-05-29 11:02:22 -04007773 private native String nativeImageURI(int x, int y);
7774 private native void nativeInstrumentReport();
Cary Clark6f5dfc62010-11-11 13:09:20 -05007775 private native Rect nativeLayerBounds(int layer);
Leon Scroggins1be40982010-03-01 11:20:31 -05007776 /* package */ native boolean nativeMoveCursorToNextTextInput();
Cary Clarkd6982c92009-05-29 11:02:22 -04007777 // return true if the page has been scrolled
7778 private native boolean nativeMotionUp(int x, int y, int slop);
7779 // returns false if it handled the key
Leon Scroggins1c7f8c52009-06-05 13:49:26 -04007780 private native boolean nativeMoveCursor(int keyCode, int count,
Cary Clarkd6982c92009-05-29 11:02:22 -04007781 boolean noScroll);
7782 private native int nativeMoveGeneration();
Cary Clark924af702010-06-04 16:37:43 -04007783 private native void nativeMoveSelection(int x, int y);
Leon Scroggins9ab32b62010-05-03 14:19:50 +01007784 /**
7785 * @return true if the page should get the shift and arrow keys, rather
7786 * than select text/navigation.
7787 *
7788 * If the focus is a plugin, or if the focus and cursor match and are
7789 * a contentEditable element, then the page should handle these keys.
7790 */
7791 private native boolean nativePageShouldHandleShiftAndArrows();
Cary Clark1cb97ee2009-12-11 12:10:36 -05007792 private native boolean nativePointInNavCache(int x, int y, int slop);
Cary Clarkd6982c92009-05-29 11:02:22 -04007793 // Like many other of our native methods, you must make sure that
7794 // mNativeClass is not null before calling this method.
7795 private native void nativeRecordButtons(boolean focused,
7796 boolean pressed, boolean invalidate);
Cary Clark924af702010-06-04 16:37:43 -04007797 private native void nativeResetSelection();
7798 private native void nativeSelectAll();
Cary Clarkd6982c92009-05-29 11:02:22 -04007799 private native void nativeSelectBestAt(Rect rect);
Cary Clark924af702010-06-04 16:37:43 -04007800 private native int nativeSelectionX();
7801 private native int nativeSelectionY();
Leon Scroggins6a367f52010-05-06 17:37:40 -04007802 private native int nativeFindIndex();
Cary Clark924af702010-06-04 16:37:43 -04007803 private native void nativeSetExtendSelection();
Cary Clarkde023c12010-03-03 10:05:16 -05007804 private native void nativeSetFindIsEmpty();
7805 private native void nativeSetFindIsUp(boolean isUp);
Cary Clarkd6982c92009-05-29 11:02:22 -04007806 private native void nativeSetHeightCanMeasure(boolean measure);
Nicolas Roard67a9f2a2010-09-07 14:49:06 -07007807 private native void nativeSetBaseLayer(int layer, Rect invalRect);
Cary Clarke60cb7f2010-08-25 14:56:00 -04007808 private native void nativeShowCursorTimed();
Grace Kloba8abd50b2010-07-08 15:02:14 -07007809 private native void nativeReplaceBaseContent(int content);
7810 private native void nativeCopyBaseContentToPicture(Picture pict);
7811 private native boolean nativeHasContent();
Cary Clark2ec30692010-02-23 10:50:38 -05007812 private native void nativeSetSelectionPointer(boolean set,
Cary Clark924af702010-06-04 16:37:43 -04007813 float scale, int x, int y);
7814 private native boolean nativeStartSelection(int x, int y);
Cary Clark31b83672010-03-09 09:20:34 -05007815 private native Rect nativeSubtractLayers(Rect content);
Cary Clarkd6982c92009-05-29 11:02:22 -04007816 private native int nativeTextGeneration();
7817 // Never call this version except by updateCachedTextfield(String) -
7818 // we always want to pass in our generation number.
7819 private native void nativeUpdateCachedTextfield(String updatedText,
7820 int generation);
Cary Clark924af702010-06-04 16:37:43 -04007821 private native boolean nativeWordSelection(int x, int y);
Grace Kloba8b97e4b2009-07-28 13:11:38 -07007822 // return NO_LEFTEDGE means failure.
Derek Sollenberger15c5ddb2010-06-10 12:31:29 -04007823 static final int NO_LEFTEDGE = -1;
7824 native int nativeGetBlockLeftEdge(int x, int y, float scale);
Patrick Scotta3ebcc92010-07-16 11:52:22 -04007825
7826 // Returns a pointer to the scrollable LayerAndroid at the given point.
7827 private native int nativeScrollableLayer(int x, int y);
7828 private native boolean nativeScrollLayer(int layer, int dx, int dy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007829}