WebViewClassic.java revision efd8b105ca7ff1f44040845af201e4bec356f824
1/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.webkit;
18
19import android.accessibilityservice.AccessibilityServiceInfo;
20import android.animation.ObjectAnimator;
21import android.annotation.Widget;
22import android.app.ActivityManager;
23import android.app.AlertDialog;
24import android.content.BroadcastReceiver;
25import android.content.ClipData;
26import android.content.ClipboardManager;
27import android.content.ComponentCallbacks2;
28import android.content.Context;
29import android.content.DialogInterface;
30import android.content.Intent;
31import android.content.IntentFilter;
32import android.content.pm.PackageManager;
33import android.content.res.Configuration;
34import android.database.DataSetObserver;
35import android.graphics.Bitmap;
36import android.graphics.BitmapFactory;
37import android.graphics.BitmapShader;
38import android.graphics.Canvas;
39import android.graphics.Color;
40import android.graphics.ColorFilter;
41import android.graphics.DrawFilter;
42import android.graphics.Paint;
43import android.graphics.PaintFlagsDrawFilter;
44import android.graphics.Picture;
45import android.graphics.Point;
46import android.graphics.PointF;
47import android.graphics.Rect;
48import android.graphics.RectF;
49import android.graphics.Region;
50import android.graphics.RegionIterator;
51import android.graphics.Shader;
52import android.graphics.drawable.Drawable;
53import android.net.Proxy;
54import android.net.ProxyProperties;
55import android.net.Uri;
56import android.net.http.SslCertificate;
57import android.os.AsyncTask;
58import android.os.Build;
59import android.os.Bundle;
60import android.os.Handler;
61import android.os.Looper;
62import android.os.Message;
63import android.os.SystemClock;
64import android.security.KeyChain;
65import android.text.Editable;
66import android.text.InputType;
67import android.text.Selection;
68import android.text.TextUtils;
69import android.util.DisplayMetrics;
70import android.util.EventLog;
71import android.util.Log;
72import android.view.Gravity;
73import android.view.HapticFeedbackConstants;
74import android.view.HardwareCanvas;
75import android.view.InputDevice;
76import android.view.KeyCharacterMap;
77import android.view.KeyEvent;
78import android.view.LayoutInflater;
79import android.view.MotionEvent;
80import android.view.ScaleGestureDetector;
81import android.view.SoundEffectConstants;
82import android.view.VelocityTracker;
83import android.view.View;
84import android.view.View.MeasureSpec;
85import android.view.ViewConfiguration;
86import android.view.ViewGroup;
87import android.view.ViewParent;
88import android.view.ViewRootImpl;
89import android.view.accessibility.AccessibilityEvent;
90import android.view.accessibility.AccessibilityManager;
91import android.view.accessibility.AccessibilityNodeInfo;
92import android.view.inputmethod.BaseInputConnection;
93import android.view.inputmethod.EditorInfo;
94import android.view.inputmethod.InputConnection;
95import android.view.inputmethod.InputMethodManager;
96import android.webkit.WebView.HitTestResult;
97import android.webkit.WebView.PictureListener;
98import android.webkit.WebViewCore.DrawData;
99import android.webkit.WebViewCore.EventHub;
100import android.webkit.WebViewCore.TextFieldInitData;
101import android.webkit.WebViewCore.TextSelectionData;
102import android.webkit.WebViewCore.WebKitHitTest;
103import android.widget.AbsoluteLayout;
104import android.widget.Adapter;
105import android.widget.AdapterView;
106import android.widget.AdapterView.OnItemClickListener;
107import android.widget.ArrayAdapter;
108import android.widget.CheckedTextView;
109import android.widget.LinearLayout;
110import android.widget.ListView;
111import android.widget.OverScroller;
112import android.widget.PopupWindow;
113import android.widget.Scroller;
114import android.widget.TextView;
115import android.widget.Toast;
116
117import junit.framework.Assert;
118
119import java.io.BufferedWriter;
120import java.io.ByteArrayOutputStream;
121import java.io.File;
122import java.io.FileInputStream;
123import java.io.FileNotFoundException;
124import java.io.FileOutputStream;
125import java.io.IOException;
126import java.io.InputStream;
127import java.io.OutputStream;
128import java.net.URLDecoder;
129import java.util.ArrayList;
130import java.util.HashMap;
131import java.util.HashSet;
132import java.util.List;
133import java.util.Locale;
134import java.util.Map;
135import java.util.Set;
136import java.util.Vector;
137
138/**
139 * Implements a backend provider for the {@link WebView} public API.
140 * @hide
141 */
142// TODO: Check if any WebView published API methods are called from within here, and if so
143// we should bounce the call out via the proxy to enable any sub-class to override it.
144@Widget
145@SuppressWarnings("deprecation")
146public final class WebViewClassic implements WebViewProvider, WebViewProvider.ScrollDelegate,
147        WebViewProvider.ViewDelegate {
148    /**
149     * InputConnection used for ContentEditable. This captures changes
150     * to the text and sends them either as key strokes or text changes.
151     */
152    class WebViewInputConnection extends BaseInputConnection {
153        // Used for mapping characters to keys typed.
154        private KeyCharacterMap mKeyCharacterMap;
155        private boolean mIsKeySentByMe;
156        private int mInputType;
157        private int mImeOptions;
158        private String mHint;
159        private int mMaxLength;
160        private boolean mIsAutoFillable;
161        private boolean mIsAutoCompleteEnabled;
162        private String mName;
163        private int mBatchLevel;
164
165        public WebViewInputConnection() {
166            super(mWebView, true);
167        }
168
169        public void setAutoFillable(int queryId) {
170            mIsAutoFillable = getSettings().getAutoFillEnabled()
171                    && (queryId != WebTextView.FORM_NOT_AUTOFILLABLE);
172            int variation = mInputType & EditorInfo.TYPE_MASK_VARIATION;
173            if (variation != EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD
174                    && (mIsAutoFillable || mIsAutoCompleteEnabled)) {
175                if (mName != null && mName.length() > 0) {
176                    requestFormData(mName, mFieldPointer, mIsAutoFillable,
177                            mIsAutoCompleteEnabled);
178                }
179            }
180        }
181
182        @Override
183        public boolean beginBatchEdit() {
184            if (mBatchLevel == 0) {
185                beginTextBatch();
186            }
187            mBatchLevel++;
188            return false;
189        }
190
191        @Override
192        public boolean endBatchEdit() {
193            mBatchLevel--;
194            if (mBatchLevel == 0) {
195                commitTextBatch();
196            }
197            return false;
198        }
199
200        public boolean getIsAutoFillable() {
201            return mIsAutoFillable;
202        }
203
204        @Override
205        public boolean sendKeyEvent(KeyEvent event) {
206            // Some IMEs send key events directly using sendKeyEvents.
207            // WebViewInputConnection should treat these as text changes.
208            if (!mIsKeySentByMe) {
209                if (event.getAction() == KeyEvent.ACTION_UP) {
210                    if (event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
211                        return deleteSurroundingText(1, 0);
212                    } else if (event.getKeyCode() == KeyEvent.KEYCODE_FORWARD_DEL) {
213                        return deleteSurroundingText(0, 1);
214                    } else if (event.getUnicodeChar() != 0){
215                        String newComposingText =
216                                Character.toString((char)event.getUnicodeChar());
217                        return commitText(newComposingText, 1);
218                    }
219                } else if (event.getAction() == KeyEvent.ACTION_DOWN &&
220                        (event.getKeyCode() == KeyEvent.KEYCODE_DEL
221                        || event.getKeyCode() == KeyEvent.KEYCODE_FORWARD_DEL
222                        || event.getUnicodeChar() != 0)) {
223                    return true; // only act on action_down
224                }
225            }
226            return super.sendKeyEvent(event);
227        }
228
229        public void setTextAndKeepSelection(CharSequence text) {
230            Editable editable = getEditable();
231            int selectionStart = Selection.getSelectionStart(editable);
232            int selectionEnd = Selection.getSelectionEnd(editable);
233            text = limitReplaceTextByMaxLength(text, editable.length());
234            editable.replace(0, editable.length(), text);
235            restartInput();
236            // Keep the previous selection.
237            selectionStart = Math.min(selectionStart, editable.length());
238            selectionEnd = Math.min(selectionEnd, editable.length());
239            setSelection(selectionStart, selectionEnd);
240            finishComposingText();
241        }
242
243        public void replaceSelection(CharSequence text) {
244            Editable editable = getEditable();
245            int selectionStart = Selection.getSelectionStart(editable);
246            int selectionEnd = Selection.getSelectionEnd(editable);
247            text = limitReplaceTextByMaxLength(text, selectionEnd - selectionStart);
248            setNewText(selectionStart, selectionEnd, text);
249            editable.replace(selectionStart, selectionEnd, text);
250            restartInput();
251            // Move caret to the end of the new text
252            int newCaret = selectionStart + text.length();
253            setSelection(newCaret, newCaret);
254        }
255
256        @Override
257        public boolean setComposingText(CharSequence text, int newCursorPosition) {
258            Editable editable = getEditable();
259            int start = getComposingSpanStart(editable);
260            int end = getComposingSpanEnd(editable);
261            if (start < 0 || end < 0) {
262                start = Selection.getSelectionStart(editable);
263                end = Selection.getSelectionEnd(editable);
264            }
265            if (end < start) {
266                int temp = end;
267                end = start;
268                start = temp;
269            }
270            CharSequence limitedText = limitReplaceTextByMaxLength(text, end - start);
271            setNewText(start, end, limitedText);
272            if (limitedText != text) {
273                newCursorPosition -= text.length() - limitedText.length();
274            }
275            super.setComposingText(limitedText, newCursorPosition);
276            updateSelection();
277            if (limitedText != text) {
278                int lastCaret = start + limitedText.length();
279                finishComposingText();
280                setSelection(lastCaret, lastCaret);
281            }
282            return true;
283        }
284
285        @Override
286        public boolean commitText(CharSequence text, int newCursorPosition) {
287            setComposingText(text, newCursorPosition);
288            finishComposingText();
289            return true;
290        }
291
292        @Override
293        public boolean deleteSurroundingText(int leftLength, int rightLength) {
294            // This code is from BaseInputConnection#deleteSurroundText.
295            // We have to delete the same text in webkit.
296            Editable content = getEditable();
297            int a = Selection.getSelectionStart(content);
298            int b = Selection.getSelectionEnd(content);
299
300            if (a > b) {
301                int tmp = a;
302                a = b;
303                b = tmp;
304            }
305
306            int ca = getComposingSpanStart(content);
307            int cb = getComposingSpanEnd(content);
308            if (cb < ca) {
309                int tmp = ca;
310                ca = cb;
311                cb = tmp;
312            }
313            if (ca != -1 && cb != -1) {
314                if (ca < a) a = ca;
315                if (cb > b) b = cb;
316            }
317
318            int endDelete = Math.min(content.length(), b + rightLength);
319            if (endDelete > b) {
320                setNewText(b, endDelete, "");
321            }
322            int startDelete = Math.max(0, a - leftLength);
323            if (startDelete < a) {
324                setNewText(startDelete, a, "");
325            }
326            return super.deleteSurroundingText(leftLength, rightLength);
327        }
328
329        @Override
330        public boolean performEditorAction(int editorAction) {
331
332            boolean handled = true;
333            switch (editorAction) {
334            case EditorInfo.IME_ACTION_NEXT:
335                mWebView.requestFocus(View.FOCUS_FORWARD);
336                break;
337            case EditorInfo.IME_ACTION_PREVIOUS:
338                mWebView.requestFocus(View.FOCUS_BACKWARD);
339                break;
340            case EditorInfo.IME_ACTION_DONE:
341                WebViewClassic.this.hideSoftKeyboard();
342                break;
343            case EditorInfo.IME_ACTION_GO:
344            case EditorInfo.IME_ACTION_SEARCH:
345                WebViewClassic.this.hideSoftKeyboard();
346                String text = getEditable().toString();
347                passToJavaScript(text, new KeyEvent(KeyEvent.ACTION_DOWN,
348                        KeyEvent.KEYCODE_ENTER));
349                passToJavaScript(text, new KeyEvent(KeyEvent.ACTION_UP,
350                        KeyEvent.KEYCODE_ENTER));
351                break;
352
353            default:
354                handled = super.performEditorAction(editorAction);
355                break;
356            }
357
358            return handled;
359        }
360
361        public void initEditorInfo(WebViewCore.TextFieldInitData initData) {
362            int type = initData.mType;
363            int inputType = InputType.TYPE_CLASS_TEXT
364                    | InputType.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT;
365            int imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI
366                    | EditorInfo.IME_FLAG_NO_FULLSCREEN;
367            if (!initData.mIsSpellCheckEnabled) {
368                inputType |= InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
369            }
370            if (WebTextView.TEXT_AREA != type) {
371                if (initData.mIsTextFieldNext) {
372                    imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_NEXT;
373                }
374                if (initData.mIsTextFieldPrev) {
375                    imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_PREVIOUS;
376                }
377            }
378            int action = EditorInfo.IME_ACTION_GO;
379            switch (type) {
380                case WebTextView.NORMAL_TEXT_FIELD:
381                    break;
382                case WebTextView.TEXT_AREA:
383                    inputType |= InputType.TYPE_TEXT_FLAG_MULTI_LINE
384                            | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
385                            | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT;
386                    action = EditorInfo.IME_ACTION_NONE;
387                    break;
388                case WebTextView.PASSWORD:
389                    inputType |= EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD;
390                    break;
391                case WebTextView.SEARCH:
392                    action = EditorInfo.IME_ACTION_SEARCH;
393                    break;
394                case WebTextView.EMAIL:
395                    // inputType needs to be overwritten because of the different text variation.
396                    inputType = InputType.TYPE_CLASS_TEXT
397                            | InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS;
398                    break;
399                case WebTextView.NUMBER:
400                    // inputType needs to be overwritten because of the different class.
401                    inputType = InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL
402                            | InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_NUMBER_FLAG_DECIMAL;
403                    // Number and telephone do not have both a Tab key and an
404                    // action, so set the action to NEXT
405                    break;
406                case WebTextView.TELEPHONE:
407                    // inputType needs to be overwritten because of the different class.
408                    inputType = InputType.TYPE_CLASS_PHONE;
409                    break;
410                case WebTextView.URL:
411                    // TYPE_TEXT_VARIATION_URI prevents Tab key from showing, so
412                    // exclude it for now.
413                    inputType |= InputType.TYPE_TEXT_VARIATION_URI;
414                    break;
415                default:
416                    break;
417            }
418            imeOptions |= action;
419            mHint = initData.mLabel;
420            mInputType = inputType;
421            mImeOptions = imeOptions;
422            mMaxLength = initData.mMaxLength;
423            mIsAutoCompleteEnabled = initData.mIsAutoCompleteEnabled;
424            mName = initData.mName;
425            mAutoCompletePopup.clearAdapter();
426        }
427
428        public void setupEditorInfo(EditorInfo outAttrs) {
429            outAttrs.inputType = mInputType;
430            outAttrs.imeOptions = mImeOptions;
431            outAttrs.hintText = mHint;
432            outAttrs.initialCapsMode = getCursorCapsMode(InputType.TYPE_CLASS_TEXT);
433
434            Editable editable = getEditable();
435            int selectionStart = Selection.getSelectionStart(editable);
436            int selectionEnd = Selection.getSelectionEnd(editable);
437            if (selectionStart < 0 || selectionEnd < 0) {
438                selectionStart = editable.length();
439                selectionEnd = selectionStart;
440            }
441            outAttrs.initialSelStart = selectionStart;
442            outAttrs.initialSelEnd = selectionEnd;
443        }
444
445        @Override
446        public boolean setSelection(int start, int end) {
447            boolean result = super.setSelection(start, end);
448            updateSelection();
449            return result;
450        }
451
452        @Override
453        public boolean setComposingRegion(int start, int end) {
454            boolean result = super.setComposingRegion(start, end);
455            updateSelection();
456            return result;
457        }
458
459        /**
460         * Send the selection and composing spans to the IME.
461         */
462        private void updateSelection() {
463            Editable editable = getEditable();
464            int selectionStart = Selection.getSelectionStart(editable);
465            int selectionEnd = Selection.getSelectionEnd(editable);
466            int composingStart = getComposingSpanStart(editable);
467            int composingEnd = getComposingSpanEnd(editable);
468            InputMethodManager imm = InputMethodManager.peekInstance();
469            if (imm != null) {
470                imm.updateSelection(mWebView, selectionStart, selectionEnd,
471                        composingStart, composingEnd);
472            }
473        }
474
475        /**
476         * Sends a text change to webkit indirectly. If it is a single-
477         * character add or delete, it sends it as a key stroke. If it cannot
478         * be represented as a key stroke, it sends it as a field change.
479         * @param start The start offset (inclusive) of the text being changed.
480         * @param end The end offset (exclusive) of the text being changed.
481         * @param text The new text to replace the changed text.
482         */
483        private void setNewText(int start, int end, CharSequence text) {
484            mIsKeySentByMe = true;
485            Editable editable = getEditable();
486            CharSequence original = editable.subSequence(start, end);
487            boolean isCharacterAdd = false;
488            boolean isCharacterDelete = false;
489            int textLength = text.length();
490            int originalLength = original.length();
491            int selectionStart = Selection.getSelectionStart(editable);
492            int selectionEnd = Selection.getSelectionEnd(editable);
493            if (selectionStart == selectionEnd) {
494                if (textLength > originalLength) {
495                    isCharacterAdd = (textLength == originalLength + 1)
496                            && TextUtils.regionMatches(text, 0, original, 0,
497                                    originalLength);
498                } else if (originalLength > textLength) {
499                    isCharacterDelete = (textLength == originalLength - 1)
500                            && TextUtils.regionMatches(text, 0, original, 0,
501                                    textLength);
502                }
503            }
504            if (isCharacterAdd) {
505                sendCharacter(text.charAt(textLength - 1));
506            } else if (isCharacterDelete) {
507                sendKey(KeyEvent.KEYCODE_DEL);
508            } else if ((textLength != originalLength) ||
509                    !TextUtils.regionMatches(text, 0, original, 0,
510                            textLength)) {
511                // Send a message so that key strokes and text replacement
512                // do not come out of order.
513                Message replaceMessage = mPrivateHandler.obtainMessage(
514                        REPLACE_TEXT, start,  end, text.toString());
515                mPrivateHandler.sendMessage(replaceMessage);
516            }
517            if (mAutoCompletePopup != null) {
518                StringBuilder newText = new StringBuilder();
519                newText.append(editable.subSequence(0, start));
520                newText.append(text);
521                newText.append(editable.subSequence(end, editable.length()));
522                mAutoCompletePopup.setText(newText.toString());
523            }
524            mIsKeySentByMe = false;
525        }
526
527        /**
528         * Send a single character to the WebView as a key down and up event.
529         * @param c The character to be sent.
530         */
531        private void sendCharacter(char c) {
532            if (mKeyCharacterMap == null) {
533                mKeyCharacterMap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
534            }
535            char[] chars = new char[1];
536            chars[0] = c;
537            KeyEvent[] events = mKeyCharacterMap.getEvents(chars);
538            if (events != null) {
539                for (KeyEvent event : events) {
540                    sendKeyEvent(event);
541                }
542            } else {
543                Message msg = mPrivateHandler.obtainMessage(KEY_PRESS, (int) c, 0);
544                mPrivateHandler.sendMessage(msg);
545            }
546        }
547
548        /**
549         * Send a key event for a specific key code, not a standard
550         * unicode character.
551         * @param keyCode The key code to send.
552         */
553        private void sendKey(int keyCode) {
554            long eventTime = SystemClock.uptimeMillis();
555            sendKeyEvent(new KeyEvent(eventTime, eventTime,
556                    KeyEvent.ACTION_DOWN, keyCode, 0, 0,
557                    KeyCharacterMap.VIRTUAL_KEYBOARD, 0,
558                    KeyEvent.FLAG_SOFT_KEYBOARD));
559            sendKeyEvent(new KeyEvent(SystemClock.uptimeMillis(), eventTime,
560                    KeyEvent.ACTION_UP, keyCode, 0, 0,
561                    KeyCharacterMap.VIRTUAL_KEYBOARD, 0,
562                    KeyEvent.FLAG_SOFT_KEYBOARD));
563        }
564
565        private CharSequence limitReplaceTextByMaxLength(CharSequence text,
566                int numReplaced) {
567            if (mMaxLength > 0) {
568                Editable editable = getEditable();
569                int maxReplace = mMaxLength - editable.length() + numReplaced;
570                if (maxReplace < text.length()) {
571                    maxReplace = Math.max(maxReplace, 0);
572                    // New length is greater than the maximum. trim it down.
573                    text = text.subSequence(0, maxReplace);
574                }
575            }
576            return text;
577        }
578
579        private void restartInput() {
580            InputMethodManager imm = InputMethodManager.peekInstance();
581            if (imm != null) {
582                // Since the text has changed, do not allow the IME to replace the
583                // existing text as though it were a completion.
584                imm.restartInput(mWebView);
585            }
586        }
587    }
588
589    private class PastePopupWindow extends PopupWindow implements View.OnClickListener {
590        private ViewGroup mContentView;
591        private TextView mPasteTextView;
592
593        public PastePopupWindow() {
594            super(mContext, null,
595                    com.android.internal.R.attr.textSelectHandleWindowStyle);
596            setClippingEnabled(true);
597            LinearLayout linearLayout = new LinearLayout(mContext);
598            linearLayout.setOrientation(LinearLayout.HORIZONTAL);
599            mContentView = linearLayout;
600            mContentView.setBackgroundResource(
601                    com.android.internal.R.drawable.text_edit_paste_window);
602
603            LayoutInflater inflater = (LayoutInflater)mContext.
604                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
605
606            ViewGroup.LayoutParams wrapContent = new ViewGroup.LayoutParams(
607                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
608
609            mPasteTextView = (TextView) inflater.inflate(
610                    com.android.internal.R.layout.text_edit_action_popup_text, null);
611            mPasteTextView.setLayoutParams(wrapContent);
612            mContentView.addView(mPasteTextView);
613            mPasteTextView.setText(com.android.internal.R.string.paste);
614            mPasteTextView.setOnClickListener(this);
615            this.setContentView(mContentView);
616        }
617
618        public void show(Point cursorBottom, Point cursorTop,
619                int windowLeft, int windowTop) {
620            measureContent();
621
622            int width = mContentView.getMeasuredWidth();
623            int height = mContentView.getMeasuredHeight();
624            int y = cursorTop.y - height;
625            int x = cursorTop.x - (width / 2);
626            if (y < windowTop) {
627                // There's not enough room vertically, move it below the
628                // handle.
629                ensureSelectionHandles();
630                y = cursorBottom.y + mSelectHandleCenter.getIntrinsicHeight();
631                x = cursorBottom.x - (width / 2);
632            }
633            if (x < windowLeft) {
634                x = windowLeft;
635            }
636            if (!isShowing()) {
637                showAtLocation(mWebView, Gravity.NO_GRAVITY, x, y);
638            }
639            update(x, y, width, height);
640        }
641
642        public void hide() {
643            dismiss();
644        }
645
646        @Override
647        public void onClick(View view) {
648            pasteFromClipboard();
649            selectionDone();
650        }
651
652        protected void measureContent() {
653            final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
654            mContentView.measure(
655                    View.MeasureSpec.makeMeasureSpec(displayMetrics.widthPixels,
656                            View.MeasureSpec.AT_MOST),
657                    View.MeasureSpec.makeMeasureSpec(displayMetrics.heightPixels,
658                            View.MeasureSpec.AT_MOST));
659        }
660    }
661
662    // if AUTO_REDRAW_HACK is true, then the CALL key will toggle redrawing
663    // the screen all-the-time. Good for profiling our drawing code
664    static private final boolean AUTO_REDRAW_HACK = false;
665
666    // The rate at which edit text is scrolled in content pixels per millisecond
667    static private final float TEXT_SCROLL_RATE = 0.01f;
668
669    // The presumed scroll rate for the first scroll of edit text
670    static private final long TEXT_SCROLL_FIRST_SCROLL_MS = 16;
671
672    // Buffer pixels of the caret rectangle when moving edit text into view
673    // after resize.
674    static private final int EDIT_RECT_BUFFER = 10;
675
676    static private final long SELECTION_HANDLE_ANIMATION_MS = 150;
677
678    // true means redraw the screen all-the-time. Only with AUTO_REDRAW_HACK
679    private boolean mAutoRedraw;
680
681    // Reference to the AlertDialog displayed by InvokeListBox.
682    // It's used to dismiss the dialog in destroy if not done before.
683    private AlertDialog mListBoxDialog = null;
684
685    // Reference to the save password dialog so it can be dimissed in
686    // destroy if not done before.
687    private AlertDialog mSavePasswordDialog = null;
688
689    static final String LOGTAG = "webview";
690
691    private ZoomManager mZoomManager;
692
693    private final Rect mInvScreenRect = new Rect();
694    private final Rect mScreenRect = new Rect();
695    private final RectF mVisibleContentRect = new RectF();
696    private boolean mIsWebViewVisible = true;
697    WebViewInputConnection mInputConnection = null;
698    private int mFieldPointer;
699    private PastePopupWindow mPasteWindow;
700    private AutoCompletePopup mAutoCompletePopup;
701    Rect mEditTextContentBounds = new Rect();
702    Rect mEditTextContent = new Rect();
703    int mEditTextLayerId;
704    boolean mIsEditingText = false;
705    ArrayList<Message> mBatchedTextChanges = new ArrayList<Message>();
706    boolean mIsBatchingTextChanges = false;
707    private long mLastEditScroll = 0;
708
709    private static class OnTrimMemoryListener implements ComponentCallbacks2 {
710        private static OnTrimMemoryListener sInstance = null;
711
712        static void init(Context c) {
713            if (sInstance == null) {
714                sInstance = new OnTrimMemoryListener(c.getApplicationContext());
715            }
716        }
717
718        private OnTrimMemoryListener(Context c) {
719            c.registerComponentCallbacks(this);
720        }
721
722        @Override
723        public void onConfigurationChanged(Configuration newConfig) {
724            // Ignore
725        }
726
727        @Override
728        public void onLowMemory() {
729            // Ignore
730        }
731
732        @Override
733        public void onTrimMemory(int level) {
734            if (DebugFlags.WEB_VIEW) {
735                Log.d("WebView", "onTrimMemory: " + level);
736            }
737            // When framework reset EGL context during high memory pressure, all
738            // the existing GL resources for the html5 video will be destroyed
739            // at native side.
740            // Here we just need to clean up the Surface Texture which is static.
741            if (level > TRIM_MEMORY_UI_HIDDEN) {
742                HTML5VideoInline.cleanupSurfaceTexture();
743                HTML5VideoView.release();
744            }
745            WebViewClassic.nativeOnTrimMemory(level);
746        }
747    }
748
749    // A final CallbackProxy shared by WebViewCore and BrowserFrame.
750    private CallbackProxy mCallbackProxy;
751
752    private WebViewDatabaseClassic mDatabase;
753
754    // SSL certificate for the main top-level page (if secure)
755    private SslCertificate mCertificate;
756
757    // Native WebView pointer that is 0 until the native object has been
758    // created.
759    private int mNativeClass;
760    // This would be final but it needs to be set to null when the WebView is
761    // destroyed.
762    private WebViewCore mWebViewCore;
763    // Handler for dispatching UI messages.
764    /* package */ final Handler mPrivateHandler = new PrivateHandler();
765    // Used to ignore changes to webkit text that arrives to the UI side after
766    // more key events.
767    private int mTextGeneration;
768
769    /* package */ void incrementTextGeneration() { mTextGeneration++; }
770
771    // Used by WebViewCore to create child views.
772    /* package */ ViewManager mViewManager;
773
774    // Used to display in full screen mode
775    PluginFullScreenHolder mFullScreenHolder;
776
777    /**
778     * Position of the last touch event in pixels.
779     * Use integer to prevent loss of dragging delta calculation accuracy;
780     * which was done in float and converted to integer, and resulted in gradual
781     * and compounding touch position and view dragging mismatch.
782     */
783    private int mLastTouchX;
784    private int mLastTouchY;
785    private int mStartTouchX;
786    private int mStartTouchY;
787    private float mAverageAngle;
788
789    /**
790     * Time of the last touch event.
791     */
792    private long mLastTouchTime;
793
794    /**
795     * Time of the last time sending touch event to WebViewCore
796     */
797    private long mLastSentTouchTime;
798
799    /**
800     * The minimum elapsed time before sending another ACTION_MOVE event to
801     * WebViewCore. This really should be tuned for each type of the devices.
802     * For example in Google Map api test case, it takes Dream device at least
803     * 150ms to do a full cycle in the WebViewCore by processing a touch event,
804     * triggering the layout and drawing the picture. While the same process
805     * takes 60+ms on the current high speed device. If we make
806     * TOUCH_SENT_INTERVAL too small, there will be multiple touch events sent
807     * to WebViewCore queue and the real layout and draw events will be pushed
808     * to further, which slows down the refresh rate. Choose 50 to favor the
809     * current high speed devices. For Dream like devices, 100 is a better
810     * choice. Maybe make this in the buildspec later.
811     * (Update 12/14/2010: changed to 0 since current device should be able to
812     * handle the raw events and Map team voted to have the raw events too.
813     */
814    private static final int TOUCH_SENT_INTERVAL = 0;
815    private int mCurrentTouchInterval = TOUCH_SENT_INTERVAL;
816
817    /**
818     * Helper class to get velocity for fling
819     */
820    VelocityTracker mVelocityTracker;
821    private int mMaximumFling;
822    private float mLastVelocity;
823    private float mLastVelX;
824    private float mLastVelY;
825
826    // The id of the native layer being scrolled.
827    private int mCurrentScrollingLayerId;
828    private Rect mScrollingLayerRect = new Rect();
829
830    // only trigger accelerated fling if the new velocity is at least
831    // MINIMUM_VELOCITY_RATIO_FOR_ACCELERATION times of the previous velocity
832    private static final float MINIMUM_VELOCITY_RATIO_FOR_ACCELERATION = 0.2f;
833
834    /**
835     * Touch mode
836     * TODO: Some of this is now unnecessary as it is handled by
837     * WebInputTouchDispatcher (such as click, long press, and double tap).
838     */
839    private int mTouchMode = TOUCH_DONE_MODE;
840    private static final int TOUCH_INIT_MODE = 1;
841    private static final int TOUCH_DRAG_START_MODE = 2;
842    private static final int TOUCH_DRAG_MODE = 3;
843    private static final int TOUCH_SHORTPRESS_START_MODE = 4;
844    private static final int TOUCH_SHORTPRESS_MODE = 5;
845    private static final int TOUCH_DOUBLE_TAP_MODE = 6;
846    private static final int TOUCH_DONE_MODE = 7;
847    private static final int TOUCH_PINCH_DRAG = 8;
848    private static final int TOUCH_DRAG_LAYER_MODE = 9;
849    private static final int TOUCH_DRAG_TEXT_MODE = 10;
850
851    // true when the touch movement exceeds the slop
852    private boolean mConfirmMove;
853    private boolean mTouchInEditText;
854
855    // Whether or not to draw the cursor ring.
856    private boolean mDrawCursorRing = true;
857
858    // true if onPause has been called (and not onResume)
859    private boolean mIsPaused;
860
861    private HitTestResult mInitialHitTestResult;
862    private WebKitHitTest mFocusedNode;
863
864    /**
865     * Customizable constant
866     */
867    // pre-computed square of ViewConfiguration.getScaledTouchSlop()
868    private int mTouchSlopSquare;
869    // pre-computed square of ViewConfiguration.getScaledDoubleTapSlop()
870    private int mDoubleTapSlopSquare;
871    // pre-computed density adjusted navigation slop
872    private int mNavSlop;
873    // This should be ViewConfiguration.getTapTimeout()
874    // But system time out is 100ms, which is too short for the browser.
875    // In the browser, if it switches out of tap too soon, jump tap won't work.
876    // In addition, a double tap on a trackpad will always have a duration of
877    // 300ms, so this value must be at least that (otherwise we will timeout the
878    // first tap and convert it to a long press).
879    private static final int TAP_TIMEOUT = 300;
880    // This should be ViewConfiguration.getLongPressTimeout()
881    // But system time out is 500ms, which is too short for the browser.
882    // With a short timeout, it's difficult to treat trigger a short press.
883    private static final int LONG_PRESS_TIMEOUT = 1000;
884    // needed to avoid flinging after a pause of no movement
885    private static final int MIN_FLING_TIME = 250;
886    // draw unfiltered after drag is held without movement
887    private static final int MOTIONLESS_TIME = 100;
888    // The amount of content to overlap between two screens when going through
889    // pages with the space bar, in pixels.
890    private static final int PAGE_SCROLL_OVERLAP = 24;
891
892    /**
893     * These prevent calling requestLayout if either dimension is fixed. This
894     * depends on the layout parameters and the measure specs.
895     */
896    boolean mWidthCanMeasure;
897    boolean mHeightCanMeasure;
898
899    // Remember the last dimensions we sent to the native side so we can avoid
900    // sending the same dimensions more than once.
901    int mLastWidthSent;
902    int mLastHeightSent;
903    // Since view height sent to webkit could be fixed to avoid relayout, this
904    // value records the last sent actual view height.
905    int mLastActualHeightSent;
906
907    private int mContentWidth;   // cache of value from WebViewCore
908    private int mContentHeight;  // cache of value from WebViewCore
909
910    // Need to have the separate control for horizontal and vertical scrollbar
911    // style than the View's single scrollbar style
912    private boolean mOverlayHorizontalScrollbar = true;
913    private boolean mOverlayVerticalScrollbar = false;
914
915    // our standard speed. this way small distances will be traversed in less
916    // time than large distances, but we cap the duration, so that very large
917    // distances won't take too long to get there.
918    private static final int STD_SPEED = 480;  // pixels per second
919    // time for the longest scroll animation
920    private static final int MAX_DURATION = 750;   // milliseconds
921
922    // Used by OverScrollGlow
923    OverScroller mScroller;
924    Scroller mEditTextScroller;
925
926    private boolean mInOverScrollMode = false;
927    private static Paint mOverScrollBackground;
928    private static Paint mOverScrollBorder;
929
930    private boolean mWrapContent;
931    private static final int MOTIONLESS_FALSE           = 0;
932    private static final int MOTIONLESS_PENDING         = 1;
933    private static final int MOTIONLESS_TRUE            = 2;
934    private static final int MOTIONLESS_IGNORE          = 3;
935    private int mHeldMotionless;
936
937    // Lazily-instantiated instance for injecting accessibility.
938    private AccessibilityInjector mAccessibilityInjector;
939
940    /**
941     * How long the caret handle will last without being touched.
942     */
943    private static final long CARET_HANDLE_STAMINA_MS = 3000;
944
945    private Drawable mSelectHandleLeft;
946    private Drawable mSelectHandleRight;
947    private Drawable mSelectHandleCenter;
948    private Point mSelectOffset;
949    private Point mSelectCursorBase = new Point();
950    private Rect mSelectHandleBaseBounds = new Rect();
951    private int mSelectCursorBaseLayerId;
952    private QuadF mSelectCursorBaseTextQuad = new QuadF();
953    private Point mSelectCursorExtent = new Point();
954    private Rect mSelectHandleExtentBounds = new Rect();
955    private int mSelectCursorExtentLayerId;
956    private QuadF mSelectCursorExtentTextQuad = new QuadF();
957    private Point mSelectDraggingCursor;
958    private QuadF mSelectDraggingTextQuad;
959    private boolean mIsCaretSelection;
960    static final int HANDLE_ID_BASE = 0;
961    static final int HANDLE_ID_EXTENT = 1;
962
963    // the color used to highlight the touch rectangles
964    static final int HIGHLIGHT_COLOR = 0x6633b5e5;
965    // the region indicating where the user touched on the screen
966    private Region mTouchHighlightRegion = new Region();
967    // the paint for the touch highlight
968    private Paint mTouchHightlightPaint = new Paint();
969    // debug only
970    private static final boolean DEBUG_TOUCH_HIGHLIGHT = true;
971    private static final int TOUCH_HIGHLIGHT_ELAPSE_TIME = 2000;
972    private Paint mTouchCrossHairColor;
973    private int mTouchHighlightX;
974    private int mTouchHighlightY;
975    private boolean mShowTapHighlight;
976
977    // Basically this proxy is used to tell the Video to update layer tree at
978    // SetBaseLayer time and to pause when WebView paused.
979    private HTML5VideoViewProxy mHTML5VideoViewProxy;
980
981    // If we are using a set picture, don't send view updates to webkit
982    private boolean mBlockWebkitViewMessages = false;
983
984    // cached value used to determine if we need to switch drawing models
985    private boolean mHardwareAccelSkia = false;
986
987    /*
988     * Private message ids
989     */
990    private static final int REMEMBER_PASSWORD          = 1;
991    private static final int NEVER_REMEMBER_PASSWORD    = 2;
992    private static final int SWITCH_TO_SHORTPRESS       = 3;
993    private static final int SWITCH_TO_LONGPRESS        = 4;
994    private static final int RELEASE_SINGLE_TAP         = 5;
995    private static final int REQUEST_FORM_DATA          = 6;
996    private static final int DRAG_HELD_MOTIONLESS       = 8;
997    private static final int PREVENT_DEFAULT_TIMEOUT    = 10;
998    private static final int SCROLL_SELECT_TEXT         = 11;
999
1000
1001    private static final int FIRST_PRIVATE_MSG_ID = REMEMBER_PASSWORD;
1002    private static final int LAST_PRIVATE_MSG_ID = SCROLL_SELECT_TEXT;
1003
1004    /*
1005     * Package message ids
1006     */
1007    static final int SCROLL_TO_MSG_ID                   = 101;
1008    static final int NEW_PICTURE_MSG_ID                 = 105;
1009    static final int WEBCORE_INITIALIZED_MSG_ID         = 107;
1010    static final int UPDATE_TEXTFIELD_TEXT_MSG_ID       = 108;
1011    static final int UPDATE_ZOOM_RANGE                  = 109;
1012    static final int TAKE_FOCUS                         = 110;
1013    static final int CLEAR_TEXT_ENTRY                   = 111;
1014    static final int UPDATE_TEXT_SELECTION_MSG_ID       = 112;
1015    static final int SHOW_RECT_MSG_ID                   = 113;
1016    static final int LONG_PRESS_CENTER                  = 114;
1017    static final int PREVENT_TOUCH_ID                   = 115;
1018    static final int WEBCORE_NEED_TOUCH_EVENTS          = 116;
1019    // obj=Rect in doc coordinates
1020    static final int INVAL_RECT_MSG_ID                  = 117;
1021    static final int REQUEST_KEYBOARD                   = 118;
1022    static final int SHOW_FULLSCREEN                    = 120;
1023    static final int HIDE_FULLSCREEN                    = 121;
1024    static final int UPDATE_MATCH_COUNT                 = 126;
1025    static final int CENTER_FIT_RECT                    = 127;
1026    static final int SET_SCROLLBAR_MODES                = 129;
1027    static final int HIT_TEST_RESULT                    = 130;
1028    static final int SAVE_WEBARCHIVE_FINISHED           = 131;
1029    static final int SET_AUTOFILLABLE                   = 132;
1030    static final int AUTOFILL_COMPLETE                  = 133;
1031    static final int SCREEN_ON                          = 134;
1032    static final int UPDATE_ZOOM_DENSITY                = 135;
1033    static final int EXIT_FULLSCREEN_VIDEO              = 136;
1034    static final int COPY_TO_CLIPBOARD                  = 137;
1035    static final int INIT_EDIT_FIELD                    = 138;
1036    static final int REPLACE_TEXT                       = 139;
1037    static final int CLEAR_CARET_HANDLE                 = 140;
1038    static final int KEY_PRESS                          = 141;
1039    static final int RELOCATE_AUTO_COMPLETE_POPUP       = 142;
1040    static final int FOCUS_NODE_CHANGED                 = 143;
1041    static final int AUTOFILL_FORM                      = 144;
1042    static final int SCROLL_EDIT_TEXT                   = 145;
1043    static final int EDIT_TEXT_SIZE_CHANGED             = 146;
1044    static final int SHOW_CARET_HANDLE                  = 147;
1045    static final int UPDATE_CONTENT_BOUNDS              = 148;
1046    static final int SCROLL_HANDLE_INTO_VIEW            = 149;
1047
1048    private static final int FIRST_PACKAGE_MSG_ID = SCROLL_TO_MSG_ID;
1049    private static final int LAST_PACKAGE_MSG_ID = HIT_TEST_RESULT;
1050
1051    static final String[] HandlerPrivateDebugString = {
1052        "REMEMBER_PASSWORD", //              = 1;
1053        "NEVER_REMEMBER_PASSWORD", //        = 2;
1054        "SWITCH_TO_SHORTPRESS", //           = 3;
1055        "SWITCH_TO_LONGPRESS", //            = 4;
1056        "RELEASE_SINGLE_TAP", //             = 5;
1057        "REQUEST_FORM_DATA", //              = 6;
1058        "RESUME_WEBCORE_PRIORITY", //        = 7;
1059        "DRAG_HELD_MOTIONLESS", //           = 8;
1060        "", //             = 9;
1061        "PREVENT_DEFAULT_TIMEOUT", //        = 10;
1062        "SCROLL_SELECT_TEXT" //              = 11;
1063    };
1064
1065    static final String[] HandlerPackageDebugString = {
1066        "SCROLL_TO_MSG_ID", //               = 101;
1067        "102", //                            = 102;
1068        "103", //                            = 103;
1069        "104", //                            = 104;
1070        "NEW_PICTURE_MSG_ID", //             = 105;
1071        "UPDATE_TEXT_ENTRY_MSG_ID", //       = 106;
1072        "WEBCORE_INITIALIZED_MSG_ID", //     = 107;
1073        "UPDATE_TEXTFIELD_TEXT_MSG_ID", //   = 108;
1074        "UPDATE_ZOOM_RANGE", //              = 109;
1075        "UNHANDLED_NAV_KEY", //              = 110;
1076        "CLEAR_TEXT_ENTRY", //               = 111;
1077        "UPDATE_TEXT_SELECTION_MSG_ID", //   = 112;
1078        "SHOW_RECT_MSG_ID", //               = 113;
1079        "LONG_PRESS_CENTER", //              = 114;
1080        "PREVENT_TOUCH_ID", //               = 115;
1081        "WEBCORE_NEED_TOUCH_EVENTS", //      = 116;
1082        "INVAL_RECT_MSG_ID", //              = 117;
1083        "REQUEST_KEYBOARD", //               = 118;
1084        "DO_MOTION_UP", //                   = 119;
1085        "SHOW_FULLSCREEN", //                = 120;
1086        "HIDE_FULLSCREEN", //                = 121;
1087        "DOM_FOCUS_CHANGED", //              = 122;
1088        "REPLACE_BASE_CONTENT", //           = 123;
1089        "RETURN_LABEL", //                   = 125;
1090        "UPDATE_MATCH_COUNT", //             = 126;
1091        "CENTER_FIT_RECT", //                = 127;
1092        "REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID", // = 128;
1093        "SET_SCROLLBAR_MODES", //            = 129;
1094        "SELECTION_STRING_CHANGED", //       = 130;
1095        "SET_TOUCH_HIGHLIGHT_RECTS", //      = 131;
1096        "SAVE_WEBARCHIVE_FINISHED", //       = 132;
1097        "SET_AUTOFILLABLE", //               = 133;
1098        "AUTOFILL_COMPLETE", //              = 134;
1099        "SELECT_AT", //                      = 135;
1100        "SCREEN_ON", //                      = 136;
1101        "ENTER_FULLSCREEN_VIDEO", //         = 137;
1102        "UPDATE_SELECTION", //               = 138;
1103        "UPDATE_ZOOM_DENSITY" //             = 139;
1104    };
1105
1106    // If the site doesn't use the viewport meta tag to specify the viewport,
1107    // use DEFAULT_VIEWPORT_WIDTH as the default viewport width
1108    static final int DEFAULT_VIEWPORT_WIDTH = 980;
1109
1110    // normally we try to fit the content to the minimum preferred width
1111    // calculated by the Webkit. To avoid the bad behavior when some site's
1112    // minimum preferred width keeps growing when changing the viewport width or
1113    // the minimum preferred width is huge, an upper limit is needed.
1114    static int sMaxViewportWidth = DEFAULT_VIEWPORT_WIDTH;
1115
1116    // initial scale in percent. 0 means using default.
1117    private int mInitialScaleInPercent = 0;
1118
1119    // Whether or not a scroll event should be sent to webkit.  This is only set
1120    // to false when restoring the scroll position.
1121    private boolean mSendScrollEvent = true;
1122
1123    private int mSnapScrollMode = SNAP_NONE;
1124    private static final int SNAP_NONE = 0;
1125    private static final int SNAP_LOCK = 1; // not a separate state
1126    private static final int SNAP_X = 2; // may be combined with SNAP_LOCK
1127    private static final int SNAP_Y = 4; // may be combined with SNAP_LOCK
1128    private boolean mSnapPositive;
1129
1130    // keep these in sync with their counterparts in WebView.cpp
1131    private static final int DRAW_EXTRAS_NONE = 0;
1132    private static final int DRAW_EXTRAS_SELECTION = 1;
1133    private static final int DRAW_EXTRAS_CURSOR_RING = 2;
1134
1135    // keep this in sync with WebCore:ScrollbarMode in WebKit
1136    private static final int SCROLLBAR_AUTO = 0;
1137    private static final int SCROLLBAR_ALWAYSOFF = 1;
1138    // as we auto fade scrollbar, this is ignored.
1139    private static final int SCROLLBAR_ALWAYSON = 2;
1140    private int mHorizontalScrollBarMode = SCROLLBAR_AUTO;
1141    private int mVerticalScrollBarMode = SCROLLBAR_AUTO;
1142
1143    /**
1144     * Max distance to overscroll by in pixels.
1145     * This how far content can be pulled beyond its normal bounds by the user.
1146     */
1147    private int mOverscrollDistance;
1148
1149    /**
1150     * Max distance to overfling by in pixels.
1151     * This is how far flinged content can move beyond the end of its normal bounds.
1152     */
1153    private int mOverflingDistance;
1154
1155    private OverScrollGlow mOverScrollGlow;
1156
1157    // Used to match key downs and key ups
1158    private Vector<Integer> mKeysPressed;
1159
1160    /* package */ static boolean mLogEvent = true;
1161
1162    // for event log
1163    private long mLastTouchUpTime = 0;
1164
1165    private WebViewCore.AutoFillData mAutoFillData;
1166
1167    private static boolean sNotificationsEnabled = true;
1168
1169    /**
1170     * URI scheme for telephone number
1171     */
1172    public static final String SCHEME_TEL = "tel:";
1173    /**
1174     * URI scheme for email address
1175     */
1176    public static final String SCHEME_MAILTO = "mailto:";
1177    /**
1178     * URI scheme for map address
1179     */
1180    public static final String SCHEME_GEO = "geo:0,0?q=";
1181
1182    private int mBackgroundColor = Color.WHITE;
1183
1184    private static final long SELECT_SCROLL_INTERVAL = 1000 / 60; // 60 / second
1185    private int mAutoScrollX = 0;
1186    private int mAutoScrollY = 0;
1187    private int mMinAutoScrollX = 0;
1188    private int mMaxAutoScrollX = 0;
1189    private int mMinAutoScrollY = 0;
1190    private int mMaxAutoScrollY = 0;
1191    private Rect mScrollingLayerBounds = new Rect();
1192    private boolean mSentAutoScrollMessage = false;
1193
1194    // used for serializing asynchronously handled touch events.
1195    private WebViewInputDispatcher mInputDispatcher;
1196
1197    // Used to track whether picture updating was paused due to a window focus change.
1198    private boolean mPictureUpdatePausedForFocusChange = false;
1199
1200    // Used to notify listeners of a new picture.
1201    private PictureListener mPictureListener;
1202
1203    // Used to notify listeners about find-on-page results.
1204    private WebView.FindListener mFindListener;
1205
1206    // Used to prevent resending save password message
1207    private Message mResumeMsg;
1208
1209    /**
1210     * Refer to {@link WebView#requestFocusNodeHref(Message)} for more information
1211     */
1212    static class FocusNodeHref {
1213        static final String TITLE = "title";
1214        static final String URL = "url";
1215        static final String SRC = "src";
1216    }
1217
1218    public WebViewClassic(WebView webView, WebView.PrivateAccess privateAccess) {
1219        mWebView = webView;
1220        mWebViewPrivate = privateAccess;
1221        mContext = webView.getContext();
1222    }
1223
1224    /**
1225     * See {@link WebViewProvider#init(Map, boolean)}
1226     */
1227    @Override
1228    public void init(Map<String, Object> javaScriptInterfaces, boolean privateBrowsing) {
1229        Context context = mContext;
1230
1231        // Used by the chrome stack to find application paths
1232        JniUtil.setContext(context);
1233
1234        mCallbackProxy = new CallbackProxy(context, this);
1235        mViewManager = new ViewManager(this);
1236        L10nUtils.setApplicationContext(context.getApplicationContext());
1237        mWebViewCore = new WebViewCore(context, this, mCallbackProxy, javaScriptInterfaces);
1238        mDatabase = WebViewDatabaseClassic.getInstance(context);
1239        mScroller = new OverScroller(context, null, 0, 0, false); //TODO Use OverScroller's flywheel
1240        mZoomManager = new ZoomManager(this, mCallbackProxy);
1241
1242        /* The init method must follow the creation of certain member variables,
1243         * such as the mZoomManager.
1244         */
1245        init();
1246        setupPackageListener(context);
1247        setupProxyListener(context);
1248        setupTrustStorageListener(context);
1249        updateMultiTouchSupport(context);
1250
1251        if (privateBrowsing) {
1252            startPrivateBrowsing();
1253        }
1254
1255        mAutoFillData = new WebViewCore.AutoFillData();
1256        mEditTextScroller = new Scroller(context);
1257
1258        // Calculate channel distance
1259        calculateChannelDistance(context);
1260    }
1261
1262    /**
1263     * Calculate sChannelDistance based on the screen information.
1264     * @param context A Context object used to access application assets.
1265     */
1266    private void calculateChannelDistance(Context context) {
1267        // The channel distance is adjusted for density and screen size
1268        final DisplayMetrics metrics = context.getResources().getDisplayMetrics();
1269        final double screenSize = Math.hypot((double)(metrics.widthPixels/metrics.densityDpi),
1270                (double)(metrics.heightPixels/metrics.densityDpi));
1271        if (screenSize < 3.0) {
1272            sChannelDistance = 16;
1273        } else if (screenSize < 5.0) {
1274            sChannelDistance = 22;
1275        } else if (screenSize < 7.0) {
1276            sChannelDistance = 28;
1277        } else {
1278            sChannelDistance = 34;
1279        }
1280        sChannelDistance = (int)(sChannelDistance * metrics.density);
1281        if (sChannelDistance < 16) sChannelDistance = 16;
1282
1283        if (DebugFlags.WEB_VIEW) {
1284            Log.v(LOGTAG, "sChannelDistance : " + sChannelDistance
1285                    + ", density : " + metrics.density
1286                    + ", screenSize : " + screenSize
1287                    + ", metrics.heightPixels : " + metrics.heightPixels
1288                    + ", metrics.widthPixels : " + metrics.widthPixels
1289                    + ", metrics.densityDpi : " + metrics.densityDpi);
1290        }
1291    }
1292
1293    // WebViewProvider bindings
1294
1295    static class Factory implements WebViewFactoryProvider,  WebViewFactoryProvider.Statics {
1296        @Override
1297        public String findAddress(String addr) {
1298            return WebViewClassic.findAddress(addr);
1299        }
1300        @Override
1301        public void setPlatformNotificationsEnabled(boolean enable) {
1302            if (enable) {
1303                WebViewClassic.enablePlatformNotifications();
1304            } else {
1305                WebViewClassic.disablePlatformNotifications();
1306            }
1307        }
1308
1309        @Override
1310        public Statics getStatics() { return this; }
1311
1312        @Override
1313        public WebViewProvider createWebView(WebView webView, WebView.PrivateAccess privateAccess) {
1314            return new WebViewClassic(webView, privateAccess);
1315        }
1316
1317        @Override
1318        public GeolocationPermissions getGeolocationPermissions() {
1319            return GeolocationPermissionsClassic.getInstance();
1320        }
1321
1322        @Override
1323        public CookieManager getCookieManager() {
1324            return CookieManagerClassic.getInstance();
1325        }
1326
1327        @Override
1328        public WebIconDatabase getWebIconDatabase() {
1329            return WebIconDatabaseClassic.getInstance();
1330        }
1331
1332        @Override
1333        public WebStorage getWebStorage() {
1334            return WebStorageClassic.getInstance();
1335        }
1336
1337        @Override
1338        public WebViewDatabase getWebViewDatabase(Context context) {
1339            return WebViewDatabaseClassic.getInstance(context);
1340        }
1341
1342        @Override
1343        public String getDefaultUserAgent(Context context) {
1344            return WebSettingsClassic.getDefaultUserAgentForLocale(context,
1345                    Locale.getDefault());
1346        }
1347    }
1348
1349    private void onHandleUiEvent(MotionEvent event, int eventType, int flags) {
1350        switch (eventType) {
1351        case WebViewInputDispatcher.EVENT_TYPE_LONG_PRESS:
1352            HitTestResult hitTest = getHitTestResult();
1353            if (hitTest != null) {
1354                mWebView.performLongClick();
1355            }
1356            break;
1357        case WebViewInputDispatcher.EVENT_TYPE_DOUBLE_TAP:
1358            mZoomManager.handleDoubleTap(event.getX(), event.getY());
1359            break;
1360        case WebViewInputDispatcher.EVENT_TYPE_TOUCH:
1361            onHandleUiTouchEvent(event);
1362            break;
1363        case WebViewInputDispatcher.EVENT_TYPE_CLICK:
1364            if (mFocusedNode != null && mFocusedNode.mIntentUrl != null) {
1365                mWebView.playSoundEffect(SoundEffectConstants.CLICK);
1366                overrideLoading(mFocusedNode.mIntentUrl);
1367            }
1368            break;
1369        }
1370    }
1371
1372    private void onHandleUiTouchEvent(MotionEvent ev) {
1373        final ScaleGestureDetector detector =
1374                mZoomManager.getScaleGestureDetector();
1375
1376        int action = ev.getActionMasked();
1377        final boolean pointerUp = action == MotionEvent.ACTION_POINTER_UP;
1378        final boolean configChanged =
1379            action == MotionEvent.ACTION_POINTER_UP ||
1380            action == MotionEvent.ACTION_POINTER_DOWN;
1381        final int skipIndex = pointerUp ? ev.getActionIndex() : -1;
1382
1383        // Determine focal point
1384        float sumX = 0, sumY = 0;
1385        final int count = ev.getPointerCount();
1386        for (int i = 0; i < count; i++) {
1387            if (skipIndex == i) continue;
1388            sumX += ev.getX(i);
1389            sumY += ev.getY(i);
1390        }
1391        final int div = pointerUp ? count - 1 : count;
1392        float x = sumX / div;
1393        float y = sumY / div;
1394
1395        if (configChanged) {
1396            mLastTouchX = Math.round(x);
1397            mLastTouchY = Math.round(y);
1398            mLastTouchTime = ev.getEventTime();
1399            mWebView.cancelLongPress();
1400            mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
1401        }
1402
1403        if (detector != null) {
1404            detector.onTouchEvent(ev);
1405            if (detector.isInProgress()) {
1406                mLastTouchTime = ev.getEventTime();
1407
1408                if (!mZoomManager.supportsPanDuringZoom()) {
1409                    return;
1410                }
1411                mTouchMode = TOUCH_DRAG_MODE;
1412                if (mVelocityTracker == null) {
1413                    mVelocityTracker = VelocityTracker.obtain();
1414                }
1415            }
1416        }
1417
1418        if (action == MotionEvent.ACTION_POINTER_DOWN) {
1419            cancelTouch();
1420            action = MotionEvent.ACTION_DOWN;
1421        } else if (action == MotionEvent.ACTION_MOVE) {
1422            // negative x or y indicate it is on the edge, skip it.
1423            if (x < 0 || y < 0) {
1424                return;
1425            }
1426        }
1427
1428        handleTouchEventCommon(ev, action, Math.round(x), Math.round(y));
1429    }
1430
1431    // The webview that is bound to this WebViewClassic instance. Primarily needed for supplying
1432    // as the first param in the WebViewClient and WebChromeClient callbacks.
1433    final private WebView mWebView;
1434    // Callback interface, provides priviledged access into the WebView instance.
1435    final private WebView.PrivateAccess mWebViewPrivate;
1436    // Cached reference to mWebView.getContext(), for convenience.
1437    final private Context mContext;
1438
1439    /**
1440     * @return The webview proxy that this classic webview is bound to.
1441     */
1442    public WebView getWebView() {
1443        return mWebView;
1444    }
1445
1446    @Override
1447    public ViewDelegate getViewDelegate() {
1448        return this;
1449    }
1450
1451    @Override
1452    public ScrollDelegate getScrollDelegate() {
1453        return this;
1454    }
1455
1456    public static WebViewClassic fromWebView(WebView webView) {
1457        return webView == null ? null : (WebViewClassic) webView.getWebViewProvider();
1458    }
1459
1460    // Accessors, purely for convenience (and to reduce code churn during webview proxy migration).
1461    int getScrollX() {
1462        return mWebView.getScrollX();
1463    }
1464
1465    int getScrollY() {
1466        return mWebView.getScrollY();
1467    }
1468
1469    int getWidth() {
1470        return mWebView.getWidth();
1471    }
1472
1473    int getHeight() {
1474        return mWebView.getHeight();
1475    }
1476
1477    Context getContext() {
1478        return mContext;
1479    }
1480
1481    void invalidate() {
1482        mWebView.invalidate();
1483    }
1484
1485    // Setters for the Scroll X & Y, without invoking the onScrollChanged etc code paths.
1486    void setScrollXRaw(int mScrollX) {
1487        mWebViewPrivate.setScrollXRaw(mScrollX);
1488    }
1489
1490    void setScrollYRaw(int mScrollY) {
1491        mWebViewPrivate.setScrollYRaw(mScrollY);
1492    }
1493
1494    private static class TrustStorageListener extends BroadcastReceiver {
1495        @Override
1496        public void onReceive(Context context, Intent intent) {
1497            if (intent.getAction().equals(KeyChain.ACTION_STORAGE_CHANGED)) {
1498                handleCertTrustChanged();
1499            }
1500        }
1501    }
1502    private static TrustStorageListener sTrustStorageListener;
1503
1504    /**
1505     * Handles update to the trust storage.
1506     */
1507    private static void handleCertTrustChanged() {
1508        // send a message for indicating trust storage change
1509        WebViewCore.sendStaticMessage(EventHub.TRUST_STORAGE_UPDATED, null);
1510    }
1511
1512    /*
1513     * @param context This method expects this to be a valid context.
1514     */
1515    private static void setupTrustStorageListener(Context context) {
1516        if (sTrustStorageListener != null ) {
1517            return;
1518        }
1519        IntentFilter filter = new IntentFilter();
1520        filter.addAction(KeyChain.ACTION_STORAGE_CHANGED);
1521        sTrustStorageListener = new TrustStorageListener();
1522        Intent current =
1523            context.getApplicationContext().registerReceiver(sTrustStorageListener, filter);
1524        if (current != null) {
1525            handleCertTrustChanged();
1526        }
1527    }
1528
1529    private static class ProxyReceiver extends BroadcastReceiver {
1530        @Override
1531        public void onReceive(Context context, Intent intent) {
1532            if (intent.getAction().equals(Proxy.PROXY_CHANGE_ACTION)) {
1533                handleProxyBroadcast(intent);
1534            }
1535        }
1536    }
1537
1538    /*
1539     * Receiver for PROXY_CHANGE_ACTION, will be null when it is not added handling broadcasts.
1540     */
1541    private static ProxyReceiver sProxyReceiver;
1542
1543    /*
1544     * @param context This method expects this to be a valid context
1545     */
1546    private static synchronized void setupProxyListener(Context context) {
1547        if (sProxyReceiver != null || sNotificationsEnabled == false) {
1548            return;
1549        }
1550        IntentFilter filter = new IntentFilter();
1551        filter.addAction(Proxy.PROXY_CHANGE_ACTION);
1552        sProxyReceiver = new ProxyReceiver();
1553        Intent currentProxy = context.getApplicationContext().registerReceiver(
1554                sProxyReceiver, filter);
1555        if (currentProxy != null) {
1556            handleProxyBroadcast(currentProxy);
1557        }
1558    }
1559
1560    /*
1561     * @param context This method expects this to be a valid context
1562     */
1563    private static synchronized void disableProxyListener(Context context) {
1564        if (sProxyReceiver == null)
1565            return;
1566
1567        context.getApplicationContext().unregisterReceiver(sProxyReceiver);
1568        sProxyReceiver = null;
1569    }
1570
1571    private static void handleProxyBroadcast(Intent intent) {
1572        ProxyProperties proxyProperties = (ProxyProperties)intent.getExtra(Proxy.EXTRA_PROXY_INFO);
1573        if (proxyProperties == null || proxyProperties.getHost() == null) {
1574            WebViewCore.sendStaticMessage(EventHub.PROXY_CHANGED, null);
1575            return;
1576        }
1577        WebViewCore.sendStaticMessage(EventHub.PROXY_CHANGED, proxyProperties);
1578    }
1579
1580    /*
1581     * A variable to track if there is a receiver added for ACTION_PACKAGE_ADDED
1582     * or ACTION_PACKAGE_REMOVED.
1583     */
1584    private static boolean sPackageInstallationReceiverAdded = false;
1585
1586    /*
1587     * A set of Google packages we monitor for the
1588     * navigator.isApplicationInstalled() API. Add additional packages as
1589     * needed.
1590     */
1591    private static Set<String> sGoogleApps;
1592    static {
1593        sGoogleApps = new HashSet<String>();
1594        sGoogleApps.add("com.google.android.youtube");
1595    }
1596
1597    private static class PackageListener extends BroadcastReceiver {
1598        @Override
1599        public void onReceive(Context context, Intent intent) {
1600            final String action = intent.getAction();
1601            final String packageName = intent.getData().getSchemeSpecificPart();
1602            final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
1603            if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
1604                // if it is replacing, refreshPlugins() when adding
1605                return;
1606            }
1607
1608            if (sGoogleApps.contains(packageName)) {
1609                if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
1610                    WebViewCore.sendStaticMessage(EventHub.ADD_PACKAGE_NAME, packageName);
1611                } else {
1612                    WebViewCore.sendStaticMessage(EventHub.REMOVE_PACKAGE_NAME, packageName);
1613                }
1614            }
1615
1616            PluginManager pm = PluginManager.getInstance(context);
1617            if (pm.containsPluginPermissionAndSignatures(packageName)) {
1618                pm.refreshPlugins(Intent.ACTION_PACKAGE_ADDED.equals(action));
1619            }
1620        }
1621    }
1622
1623    private void setupPackageListener(Context context) {
1624
1625        /*
1626         * we must synchronize the instance check and the creation of the
1627         * receiver to ensure that only ONE receiver exists for all WebView
1628         * instances.
1629         */
1630        synchronized (WebViewClassic.class) {
1631
1632            // if the receiver already exists then we do not need to register it
1633            // again
1634            if (sPackageInstallationReceiverAdded) {
1635                return;
1636            }
1637
1638            IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
1639            filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1640            filter.addDataScheme("package");
1641            BroadcastReceiver packageListener = new PackageListener();
1642            context.getApplicationContext().registerReceiver(packageListener, filter);
1643            sPackageInstallationReceiverAdded = true;
1644        }
1645
1646        // check if any of the monitored apps are already installed
1647        AsyncTask<Void, Void, Set<String>> task = new AsyncTask<Void, Void, Set<String>>() {
1648
1649            @Override
1650            protected Set<String> doInBackground(Void... unused) {
1651                Set<String> installedPackages = new HashSet<String>();
1652                PackageManager pm = mContext.getPackageManager();
1653                for (String name : sGoogleApps) {
1654                    try {
1655                        pm.getPackageInfo(name,
1656                                PackageManager.GET_ACTIVITIES | PackageManager.GET_SERVICES);
1657                        installedPackages.add(name);
1658                    } catch (PackageManager.NameNotFoundException e) {
1659                        // package not found
1660                    }
1661                }
1662                return installedPackages;
1663            }
1664
1665            // Executes on the UI thread
1666            @Override
1667            protected void onPostExecute(Set<String> installedPackages) {
1668                if (mWebViewCore != null) {
1669                    mWebViewCore.sendMessage(EventHub.ADD_PACKAGE_NAMES, installedPackages);
1670                }
1671            }
1672        };
1673        task.execute();
1674    }
1675
1676    void updateMultiTouchSupport(Context context) {
1677        mZoomManager.updateMultiTouchSupport(context);
1678    }
1679
1680    void updateJavaScriptEnabled(boolean enabled) {
1681        if (isAccessibilityInjectionEnabled()) {
1682            getAccessibilityInjector().updateJavaScriptEnabled(enabled);
1683        }
1684    }
1685
1686    private void init() {
1687        OnTrimMemoryListener.init(mContext);
1688        mWebView.setWillNotDraw(false);
1689        mWebView.setClickable(true);
1690        mWebView.setLongClickable(true);
1691
1692        final ViewConfiguration configuration = ViewConfiguration.get(mContext);
1693        int slop = configuration.getScaledTouchSlop();
1694        mTouchSlopSquare = slop * slop;
1695        slop = configuration.getScaledDoubleTapSlop();
1696        mDoubleTapSlopSquare = slop * slop;
1697        final float density = WebViewCore.getFixedDisplayDensity(mContext);
1698        // use one line height, 16 based on our current default font, for how
1699        // far we allow a touch be away from the edge of a link
1700        mNavSlop = (int) (16 * density);
1701        mZoomManager.init(density);
1702        mMaximumFling = configuration.getScaledMaximumFlingVelocity();
1703
1704        // Compute the inverse of the density squared.
1705        DRAG_LAYER_INVERSE_DENSITY_SQUARED = 1 / (density * density);
1706
1707        mOverscrollDistance = configuration.getScaledOverscrollDistance();
1708        mOverflingDistance = configuration.getScaledOverflingDistance();
1709
1710        setScrollBarStyle(mWebViewPrivate.super_getScrollBarStyle());
1711        // Initially use a size of two, since the user is likely to only hold
1712        // down two keys at a time (shift + another key)
1713        mKeysPressed = new Vector<Integer>(2);
1714        mHTML5VideoViewProxy = null ;
1715    }
1716
1717    @Override
1718    public boolean shouldDelayChildPressedState() {
1719        return true;
1720    }
1721
1722    @Override
1723    public boolean performAccessibilityAction(int action, Bundle arguments) {
1724        if (!mWebView.isEnabled()) {
1725            // Only default actions are supported while disabled.
1726            return mWebViewPrivate.super_performAccessibilityAction(action, arguments);
1727        }
1728
1729        if (getAccessibilityInjector().supportsAccessibilityAction(action)) {
1730            return getAccessibilityInjector().performAccessibilityAction(action, arguments);
1731        }
1732
1733        switch (action) {
1734            case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD:
1735            case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
1736                final int convertedContentHeight = contentToViewY(getContentHeight());
1737                final int adjustedViewHeight = getHeight() - mWebView.getPaddingTop()
1738                        - mWebView.getPaddingBottom();
1739                final int maxScrollY = Math.max(convertedContentHeight - adjustedViewHeight, 0);
1740                final boolean canScrollBackward = (getScrollY() > 0);
1741                final boolean canScrollForward = ((getScrollY() - maxScrollY) > 0);
1742                if ((action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD) && canScrollBackward) {
1743                    mWebView.scrollBy(0, adjustedViewHeight);
1744                    return true;
1745                }
1746                if ((action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD) && canScrollForward) {
1747                    mWebView.scrollBy(0, -adjustedViewHeight);
1748                    return true;
1749                }
1750                return false;
1751            }
1752        }
1753
1754        return mWebViewPrivate.super_performAccessibilityAction(action, arguments);
1755    }
1756
1757    @Override
1758    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
1759        if (!mWebView.isEnabled()) {
1760            // Only default actions are supported while disabled.
1761            return;
1762        }
1763
1764        info.setScrollable(isScrollableForAccessibility());
1765
1766        final int convertedContentHeight = contentToViewY(getContentHeight());
1767        final int adjustedViewHeight = getHeight() - mWebView.getPaddingTop()
1768                - mWebView.getPaddingBottom();
1769        final int maxScrollY = Math.max(convertedContentHeight - adjustedViewHeight, 0);
1770        final boolean canScrollBackward = (getScrollY() > 0);
1771        final boolean canScrollForward = ((getScrollY() - maxScrollY) > 0);
1772
1773        if (canScrollForward) {
1774            info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
1775        }
1776
1777        if (canScrollForward) {
1778            info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
1779        }
1780
1781        getAccessibilityInjector().onInitializeAccessibilityNodeInfo(info);
1782    }
1783
1784    @Override
1785    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
1786        event.setScrollable(isScrollableForAccessibility());
1787        event.setScrollX(getScrollX());
1788        event.setScrollY(getScrollY());
1789        final int convertedContentWidth = contentToViewX(getContentWidth());
1790        final int adjustedViewWidth = getWidth() - mWebView.getPaddingLeft()
1791                - mWebView.getPaddingLeft();
1792        event.setMaxScrollX(Math.max(convertedContentWidth - adjustedViewWidth, 0));
1793        final int convertedContentHeight = contentToViewY(getContentHeight());
1794        final int adjustedViewHeight = getHeight() - mWebView.getPaddingTop()
1795                - mWebView.getPaddingBottom();
1796        event.setMaxScrollY(Math.max(convertedContentHeight - adjustedViewHeight, 0));
1797    }
1798
1799    /* package */ void handleSelectionChangedWebCoreThread(String selection, int token) {
1800        if (isAccessibilityInjectionEnabled()) {
1801            getAccessibilityInjector().onSelectionStringChangedWebCoreThread(selection, token);
1802        }
1803    }
1804
1805    private boolean isAccessibilityInjectionEnabled() {
1806        final AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
1807        if (!manager.isEnabled()) {
1808            return false;
1809        }
1810
1811        // Accessibility scripts should be injected only when a speaking service
1812        // is enabled. This may need to change later to accommodate Braille.
1813        final List<AccessibilityServiceInfo> services = manager.getEnabledAccessibilityServiceList(
1814                AccessibilityServiceInfo.FEEDBACK_SPOKEN);
1815        if (services.isEmpty()) {
1816            return false;
1817        }
1818
1819        return true;
1820    }
1821
1822    private AccessibilityInjector getAccessibilityInjector() {
1823        if (mAccessibilityInjector == null) {
1824            mAccessibilityInjector = new AccessibilityInjector(this);
1825        }
1826        return mAccessibilityInjector;
1827    }
1828
1829    private boolean isScrollableForAccessibility() {
1830        return (contentToViewX(getContentWidth()) > getWidth() - mWebView.getPaddingLeft()
1831                - mWebView.getPaddingRight()
1832                || contentToViewY(getContentHeight()) > getHeight() - mWebView.getPaddingTop()
1833                - mWebView.getPaddingBottom());
1834    }
1835
1836    @Override
1837    public void setOverScrollMode(int mode) {
1838        if (mode != View.OVER_SCROLL_NEVER) {
1839            if (mOverScrollGlow == null) {
1840                mOverScrollGlow = new OverScrollGlow(this);
1841            }
1842        } else {
1843            mOverScrollGlow = null;
1844        }
1845    }
1846
1847    /* package */ void adjustDefaultZoomDensity(int zoomDensity) {
1848        final float density = WebViewCore.getFixedDisplayDensity(mContext)
1849                * 100 / zoomDensity;
1850        updateDefaultZoomDensity(density);
1851    }
1852
1853    /* package */ void updateDefaultZoomDensity(float density) {
1854        mNavSlop = (int) (16 * density);
1855        mZoomManager.updateDefaultZoomDensity(density);
1856    }
1857
1858    /* package */ int getScaledNavSlop() {
1859        return viewToContentDimension(mNavSlop);
1860    }
1861
1862    /* package */ boolean onSavePassword(String schemePlusHost, String username,
1863            String password, final Message resumeMsg) {
1864        boolean rVal = false;
1865        if (resumeMsg == null) {
1866            // null resumeMsg implies saving password silently
1867            mDatabase.setUsernamePassword(schemePlusHost, username, password);
1868        } else {
1869            if (mResumeMsg != null) {
1870                Log.w(LOGTAG, "onSavePassword should not be called while dialog is up");
1871                resumeMsg.sendToTarget();
1872                return true;
1873            }
1874            mResumeMsg = resumeMsg;
1875            final Message remember = mPrivateHandler.obtainMessage(
1876                    REMEMBER_PASSWORD);
1877            remember.getData().putString("host", schemePlusHost);
1878            remember.getData().putString("username", username);
1879            remember.getData().putString("password", password);
1880            remember.obj = resumeMsg;
1881
1882            final Message neverRemember = mPrivateHandler.obtainMessage(
1883                    NEVER_REMEMBER_PASSWORD);
1884            neverRemember.getData().putString("host", schemePlusHost);
1885            neverRemember.getData().putString("username", username);
1886            neverRemember.getData().putString("password", password);
1887            neverRemember.obj = resumeMsg;
1888
1889            mSavePasswordDialog = new AlertDialog.Builder(mContext)
1890                    .setTitle(com.android.internal.R.string.save_password_label)
1891                    .setMessage(com.android.internal.R.string.save_password_message)
1892                    .setPositiveButton(com.android.internal.R.string.save_password_notnow,
1893                    new DialogInterface.OnClickListener() {
1894                        @Override
1895                        public void onClick(DialogInterface dialog, int which) {
1896                            if (mResumeMsg != null) {
1897                                resumeMsg.sendToTarget();
1898                                mResumeMsg = null;
1899                            }
1900                            mSavePasswordDialog = null;
1901                        }
1902                    })
1903                    .setNeutralButton(com.android.internal.R.string.save_password_remember,
1904                    new DialogInterface.OnClickListener() {
1905                        @Override
1906                        public void onClick(DialogInterface dialog, int which) {
1907                            if (mResumeMsg != null) {
1908                                remember.sendToTarget();
1909                                mResumeMsg = null;
1910                            }
1911                            mSavePasswordDialog = null;
1912                        }
1913                    })
1914                    .setNegativeButton(com.android.internal.R.string.save_password_never,
1915                    new DialogInterface.OnClickListener() {
1916                        @Override
1917                        public void onClick(DialogInterface dialog, int which) {
1918                            if (mResumeMsg != null) {
1919                                neverRemember.sendToTarget();
1920                                mResumeMsg = null;
1921                            }
1922                            mSavePasswordDialog = null;
1923                        }
1924                    })
1925                    .setOnDismissListener(new DialogInterface.OnDismissListener() {
1926                        @Override
1927                        public void onDismiss(DialogInterface dialog) {
1928                            if (mResumeMsg != null) {
1929                                resumeMsg.sendToTarget();
1930                                mResumeMsg = null;
1931                            }
1932                            mSavePasswordDialog = null;
1933                        }
1934                    }).show();
1935            // Return true so that WebViewCore will pause while the dialog is
1936            // up.
1937            rVal = true;
1938        }
1939        return rVal;
1940    }
1941
1942    @Override
1943    public void setScrollBarStyle(int style) {
1944        if (style == View.SCROLLBARS_INSIDE_INSET
1945                || style == View.SCROLLBARS_OUTSIDE_INSET) {
1946            mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = false;
1947        } else {
1948            mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = true;
1949        }
1950    }
1951
1952    /**
1953     * See {@link WebView#setHorizontalScrollbarOverlay(boolean)}
1954     */
1955    @Override
1956    public void setHorizontalScrollbarOverlay(boolean overlay) {
1957        mOverlayHorizontalScrollbar = overlay;
1958    }
1959
1960    /**
1961     * See {@link WebView#setVerticalScrollbarOverlay(boolean)
1962     */
1963    @Override
1964    public void setVerticalScrollbarOverlay(boolean overlay) {
1965        mOverlayVerticalScrollbar = overlay;
1966    }
1967
1968    /**
1969     * See {@link WebView#overlayHorizontalScrollbar()}
1970     */
1971    @Override
1972    public boolean overlayHorizontalScrollbar() {
1973        return mOverlayHorizontalScrollbar;
1974    }
1975
1976    /**
1977     * See {@link WebView#overlayVerticalScrollbar()}
1978     */
1979    @Override
1980    public boolean overlayVerticalScrollbar() {
1981        return mOverlayVerticalScrollbar;
1982    }
1983
1984    /*
1985     * Return the width of the view where the content of WebView should render
1986     * to.
1987     * Note: this can be called from WebCoreThread.
1988     */
1989    /* package */ int getViewWidth() {
1990        if (!mWebView.isVerticalScrollBarEnabled() || mOverlayVerticalScrollbar) {
1991            return getWidth();
1992        } else {
1993            return Math.max(0, getWidth() - mWebView.getVerticalScrollbarWidth());
1994        }
1995    }
1996
1997    // Interface to enable the browser to override title bar handling.
1998    public interface TitleBarDelegate {
1999        int getTitleHeight();
2000        public void onSetEmbeddedTitleBar(final View title);
2001    }
2002
2003    /**
2004     * Returns the height (in pixels) of the embedded title bar (if any). Does not care about
2005     * scrolling
2006     */
2007    protected int getTitleHeight() {
2008        if (mWebView instanceof TitleBarDelegate) {
2009            return ((TitleBarDelegate) mWebView).getTitleHeight();
2010        }
2011        return 0;
2012    }
2013
2014    /**
2015     * See {@link WebView#getVisibleTitleHeight()}
2016     */
2017    @Override
2018    @Deprecated
2019    public int getVisibleTitleHeight() {
2020        // Actually, this method returns the height of the embedded title bar if one is set via the
2021        // hidden setEmbeddedTitleBar method.
2022        return getVisibleTitleHeightImpl();
2023    }
2024
2025    private int getVisibleTitleHeightImpl() {
2026        // need to restrict mScrollY due to over scroll
2027        return Math.max(getTitleHeight() - Math.max(0, getScrollY()),
2028                getOverlappingActionModeHeight());
2029    }
2030
2031    private int mCachedOverlappingActionModeHeight = -1;
2032
2033    private int getOverlappingActionModeHeight() {
2034        if (mFindCallback == null) {
2035            return 0;
2036        }
2037        if (mCachedOverlappingActionModeHeight < 0) {
2038            mWebView.getGlobalVisibleRect(mGlobalVisibleRect, mGlobalVisibleOffset);
2039            mCachedOverlappingActionModeHeight = Math.max(0,
2040                    mFindCallback.getActionModeGlobalBottom() - mGlobalVisibleRect.top);
2041        }
2042        return mCachedOverlappingActionModeHeight;
2043    }
2044
2045    /*
2046     * Return the height of the view where the content of WebView should render
2047     * to.  Note that this excludes mTitleBar, if there is one.
2048     * Note: this can be called from WebCoreThread.
2049     */
2050    /* package */ int getViewHeight() {
2051        return getViewHeightWithTitle() - getVisibleTitleHeightImpl();
2052    }
2053
2054    int getViewHeightWithTitle() {
2055        int height = getHeight();
2056        if (mWebView.isHorizontalScrollBarEnabled() && !mOverlayHorizontalScrollbar) {
2057            height -= mWebViewPrivate.getHorizontalScrollbarHeight();
2058        }
2059        return height;
2060    }
2061
2062    /**
2063     * See {@link WebView#getCertificate()}
2064     */
2065    @Override
2066    public SslCertificate getCertificate() {
2067        return mCertificate;
2068    }
2069
2070    /**
2071     * See {@link WebView#setCertificate(SslCertificate)}
2072     */
2073    @Override
2074    public void setCertificate(SslCertificate certificate) {
2075        if (DebugFlags.WEB_VIEW) {
2076            Log.v(LOGTAG, "setCertificate=" + certificate);
2077        }
2078        // here, the certificate can be null (if the site is not secure)
2079        mCertificate = certificate;
2080    }
2081
2082    //-------------------------------------------------------------------------
2083    // Methods called by activity
2084    //-------------------------------------------------------------------------
2085
2086    /**
2087     * See {@link WebView#savePassword(String, String, String)}
2088     */
2089    @Override
2090    public void savePassword(String host, String username, String password) {
2091        mDatabase.setUsernamePassword(host, username, password);
2092    }
2093
2094    /**
2095     * See {@link WebView#setHttpAuthUsernamePassword(String, String, String, String)}
2096     */
2097    @Override
2098    public void setHttpAuthUsernamePassword(String host, String realm,
2099            String username, String password) {
2100        mDatabase.setHttpAuthUsernamePassword(host, realm, username, password);
2101    }
2102
2103    /**
2104     * See {@link WebView#getHttpAuthUsernamePassword(String, String)}
2105     */
2106    @Override
2107    public String[] getHttpAuthUsernamePassword(String host, String realm) {
2108        return mDatabase.getHttpAuthUsernamePassword(host, realm);
2109    }
2110
2111    /**
2112     * Remove Find or Select ActionModes, if active.
2113     */
2114    private void clearActionModes() {
2115        if (mSelectCallback != null) {
2116            mSelectCallback.finish();
2117        }
2118        if (mFindCallback != null) {
2119            mFindCallback.finish();
2120        }
2121    }
2122
2123    /**
2124     * Called to clear state when moving from one page to another, or changing
2125     * in some other way that makes elements associated with the current page
2126     * (such as ActionModes) no longer relevant.
2127     */
2128    private void clearHelpers() {
2129        hideSoftKeyboard();
2130        clearActionModes();
2131        dismissFullScreenMode();
2132        cancelDialogs();
2133    }
2134
2135    private void cancelDialogs() {
2136        if (mListBoxDialog != null) {
2137            mListBoxDialog.cancel();
2138            mListBoxDialog = null;
2139        }
2140        if (mSavePasswordDialog != null) {
2141            mSavePasswordDialog.dismiss();
2142            mSavePasswordDialog = null;
2143        }
2144    }
2145
2146    /**
2147     * See {@link WebView#destroy()}
2148     */
2149    @Override
2150    public void destroy() {
2151        if (mWebView.getViewRootImpl() != null) {
2152            Log.e(LOGTAG, "Error: WebView.destroy() called while still attached!");
2153        }
2154        ensureFunctorDetached();
2155        destroyJava();
2156        destroyNative();
2157    }
2158
2159    private void ensureFunctorDetached() {
2160        if (mWebView.isHardwareAccelerated()) {
2161            int drawGLFunction = nativeGetDrawGLFunction(mNativeClass);
2162            ViewRootImpl viewRoot = mWebView.getViewRootImpl();
2163            if (drawGLFunction != 0 && viewRoot != null) {
2164                viewRoot.detachFunctor(drawGLFunction);
2165            }
2166        }
2167    }
2168
2169    private void destroyJava() {
2170        mCallbackProxy.blockMessages();
2171        if (mAccessibilityInjector != null) {
2172            mAccessibilityInjector.destroy();
2173            mAccessibilityInjector = null;
2174        }
2175        if (mWebViewCore != null) {
2176            // Tell WebViewCore to destroy itself
2177            synchronized (this) {
2178                WebViewCore webViewCore = mWebViewCore;
2179                mWebViewCore = null; // prevent using partial webViewCore
2180                webViewCore.destroy();
2181            }
2182            // Remove any pending messages that might not be serviced yet.
2183            mPrivateHandler.removeCallbacksAndMessages(null);
2184        }
2185    }
2186
2187    private void destroyNative() {
2188        if (mNativeClass == 0) return;
2189        int nptr = mNativeClass;
2190        mNativeClass = 0;
2191        if (Thread.currentThread() == mPrivateHandler.getLooper().getThread()) {
2192            // We are on the main thread and can safely delete
2193            nativeDestroy(nptr);
2194        } else {
2195            mPrivateHandler.post(new DestroyNativeRunnable(nptr));
2196        }
2197    }
2198
2199    private static class DestroyNativeRunnable implements Runnable {
2200
2201        private int mNativePtr;
2202
2203        public DestroyNativeRunnable(int nativePtr) {
2204            mNativePtr = nativePtr;
2205        }
2206
2207        @Override
2208        public void run() {
2209            // nativeDestroy also does a stopGL()
2210            nativeDestroy(mNativePtr);
2211        }
2212
2213    }
2214
2215    /**
2216     * See {@link WebView#enablePlatformNotifications()}
2217     */
2218    @Deprecated
2219    public static void enablePlatformNotifications() {
2220        synchronized (WebViewClassic.class) {
2221            sNotificationsEnabled = true;
2222            Context context = JniUtil.getContext();
2223            if (context != null)
2224                setupProxyListener(context);
2225        }
2226    }
2227
2228    /**
2229     * See {@link WebView#disablePlatformNotifications()}
2230     */
2231    @Deprecated
2232    public static void disablePlatformNotifications() {
2233        synchronized (WebViewClassic.class) {
2234            sNotificationsEnabled = false;
2235            Context context = JniUtil.getContext();
2236            if (context != null)
2237                disableProxyListener(context);
2238        }
2239    }
2240
2241    /**
2242     * Sets JavaScript engine flags.
2243     *
2244     * @param flags JS engine flags in a String
2245     *
2246     * This is an implementation detail.
2247     */
2248    public void setJsFlags(String flags) {
2249        mWebViewCore.sendMessage(EventHub.SET_JS_FLAGS, flags);
2250    }
2251
2252    /**
2253     * See {@link WebView#setNetworkAvailable(boolean)}
2254     */
2255    @Override
2256    public void setNetworkAvailable(boolean networkUp) {
2257        mWebViewCore.sendMessage(EventHub.SET_NETWORK_STATE,
2258                networkUp ? 1 : 0, 0);
2259    }
2260
2261    /**
2262     * Inform WebView about the current network type.
2263     */
2264    public void setNetworkType(String type, String subtype) {
2265        Map<String, String> map = new HashMap<String, String>();
2266        map.put("type", type);
2267        map.put("subtype", subtype);
2268        mWebViewCore.sendMessage(EventHub.SET_NETWORK_TYPE, map);
2269    }
2270
2271    /**
2272     * See {@link WebView#saveState(Bundle)}
2273     */
2274    @Override
2275    public WebBackForwardList saveState(Bundle outState) {
2276        if (outState == null) {
2277            return null;
2278        }
2279        // We grab a copy of the back/forward list because a client of WebView
2280        // may have invalidated the history list by calling clearHistory.
2281        WebBackForwardListClassic list = copyBackForwardList();
2282        final int currentIndex = list.getCurrentIndex();
2283        final int size = list.getSize();
2284        // We should fail saving the state if the list is empty or the index is
2285        // not in a valid range.
2286        if (currentIndex < 0 || currentIndex >= size || size == 0) {
2287            return null;
2288        }
2289        outState.putInt("index", currentIndex);
2290        // FIXME: This should just be a byte[][] instead of ArrayList but
2291        // Parcel.java does not have the code to handle multi-dimensional
2292        // arrays.
2293        ArrayList<byte[]> history = new ArrayList<byte[]>(size);
2294        for (int i = 0; i < size; i++) {
2295            WebHistoryItemClassic item = list.getItemAtIndex(i);
2296            if (null == item) {
2297                // FIXME: this shouldn't happen
2298                // need to determine how item got set to null
2299                Log.w(LOGTAG, "saveState: Unexpected null history item.");
2300                return null;
2301            }
2302            byte[] data = item.getFlattenedData();
2303            if (data == null) {
2304                // It would be very odd to not have any data for a given history
2305                // item. And we will fail to rebuild the history list without
2306                // flattened data.
2307                return null;
2308            }
2309            history.add(data);
2310        }
2311        outState.putSerializable("history", history);
2312        if (mCertificate != null) {
2313            outState.putBundle("certificate",
2314                               SslCertificate.saveState(mCertificate));
2315        }
2316        outState.putBoolean("privateBrowsingEnabled", isPrivateBrowsingEnabled());
2317        mZoomManager.saveZoomState(outState);
2318        return list;
2319    }
2320
2321    /**
2322     * See {@link WebView#savePicture(Bundle, File)}
2323     */
2324    @Override
2325    @Deprecated
2326    public boolean savePicture(Bundle b, final File dest) {
2327        if (dest == null || b == null) {
2328            return false;
2329        }
2330        final Picture p = capturePicture();
2331        // Use a temporary file while writing to ensure the destination file
2332        // contains valid data.
2333        final File temp = new File(dest.getPath() + ".writing");
2334        new Thread(new Runnable() {
2335            @Override
2336            public void run() {
2337                FileOutputStream out = null;
2338                try {
2339                    out = new FileOutputStream(temp);
2340                    p.writeToStream(out);
2341                    // Writing the picture succeeded, rename the temporary file
2342                    // to the destination.
2343                    temp.renameTo(dest);
2344                } catch (Exception e) {
2345                    // too late to do anything about it.
2346                } finally {
2347                    if (out != null) {
2348                        try {
2349                            out.close();
2350                        } catch (Exception e) {
2351                            // Can't do anything about that
2352                        }
2353                    }
2354                    temp.delete();
2355                }
2356            }
2357        }).start();
2358        // now update the bundle
2359        b.putInt("scrollX", getScrollX());
2360        b.putInt("scrollY", getScrollY());
2361        mZoomManager.saveZoomState(b);
2362        return true;
2363    }
2364
2365    private void restoreHistoryPictureFields(Picture p, Bundle b) {
2366        int sx = b.getInt("scrollX", 0);
2367        int sy = b.getInt("scrollY", 0);
2368
2369        mDrawHistory = true;
2370        mHistoryPicture = p;
2371
2372        setScrollXRaw(sx);
2373        setScrollYRaw(sy);
2374        mZoomManager.restoreZoomState(b);
2375        final float scale = mZoomManager.getScale();
2376        mHistoryWidth = Math.round(p.getWidth() * scale);
2377        mHistoryHeight = Math.round(p.getHeight() * scale);
2378
2379        invalidate();
2380    }
2381
2382    /**
2383     * See {@link WebView#restorePicture(Bundle, File)};
2384     */
2385    @Override
2386    @Deprecated
2387    public boolean restorePicture(Bundle b, File src) {
2388        if (src == null || b == null) {
2389            return false;
2390        }
2391        if (!src.exists()) {
2392            return false;
2393        }
2394        try {
2395            final FileInputStream in = new FileInputStream(src);
2396            final Bundle copy = new Bundle(b);
2397            new Thread(new Runnable() {
2398                @Override
2399                public void run() {
2400                    try {
2401                        final Picture p = Picture.createFromStream(in);
2402                        if (p != null) {
2403                            // Post a runnable on the main thread to update the
2404                            // history picture fields.
2405                            mPrivateHandler.post(new Runnable() {
2406                                @Override
2407                                public void run() {
2408                                    restoreHistoryPictureFields(p, copy);
2409                                }
2410                            });
2411                        }
2412                    } finally {
2413                        try {
2414                            in.close();
2415                        } catch (Exception e) {
2416                            // Nothing we can do now.
2417                        }
2418                    }
2419                }
2420            }).start();
2421        } catch (FileNotFoundException e){
2422            e.printStackTrace();
2423        }
2424        return true;
2425    }
2426
2427    /**
2428     * Saves the view data to the output stream. The output is highly
2429     * version specific, and may not be able to be loaded by newer versions
2430     * of WebView.
2431     * @param stream The {@link OutputStream} to save to
2432     * @param callback The {@link ValueCallback} to call with the result
2433     */
2434    public void saveViewState(OutputStream stream, ValueCallback<Boolean> callback) {
2435        if (mWebViewCore == null) {
2436            callback.onReceiveValue(false);
2437            return;
2438        }
2439        mWebViewCore.sendMessageAtFrontOfQueue(EventHub.SAVE_VIEW_STATE,
2440                new WebViewCore.SaveViewStateRequest(stream, callback));
2441    }
2442
2443    /**
2444     * Loads the view data from the input stream. See
2445     * {@link #saveViewState(java.io.OutputStream, ValueCallback)} for more information.
2446     * @param stream The {@link InputStream} to load from
2447     */
2448    public void loadViewState(InputStream stream) {
2449        mBlockWebkitViewMessages = true;
2450        new AsyncTask<InputStream, Void, DrawData>() {
2451
2452            @Override
2453            protected DrawData doInBackground(InputStream... params) {
2454                try {
2455                    return ViewStateSerializer.deserializeViewState(params[0]);
2456                } catch (IOException e) {
2457                    return null;
2458                }
2459            }
2460
2461            @Override
2462            protected void onPostExecute(DrawData draw) {
2463                if (draw == null) {
2464                    Log.e(LOGTAG, "Failed to load view state!");
2465                    return;
2466                }
2467                int viewWidth = getViewWidth();
2468                int viewHeight = getViewHeightWithTitle() - getTitleHeight();
2469                draw.mViewSize = new Point(viewWidth, viewHeight);
2470                draw.mViewState.mDefaultScale = getDefaultZoomScale();
2471                mLoadedPicture = draw;
2472                setNewPicture(mLoadedPicture, true);
2473                mLoadedPicture.mViewState = null;
2474            }
2475
2476        }.execute(stream);
2477    }
2478
2479    /**
2480     * Clears the view state set with {@link #loadViewState(InputStream)}.
2481     * This WebView will then switch to showing the content from webkit
2482     */
2483    public void clearViewState() {
2484        mBlockWebkitViewMessages = false;
2485        mLoadedPicture = null;
2486        invalidate();
2487    }
2488
2489    /**
2490     * See {@link WebView#restoreState(Bundle)}
2491     */
2492    @Override
2493    public WebBackForwardList restoreState(Bundle inState) {
2494        WebBackForwardListClassic returnList = null;
2495        if (inState == null) {
2496            return returnList;
2497        }
2498        if (inState.containsKey("index") && inState.containsKey("history")) {
2499            mCertificate = SslCertificate.restoreState(
2500                inState.getBundle("certificate"));
2501
2502            final WebBackForwardListClassic list = mCallbackProxy.getBackForwardList();
2503            final int index = inState.getInt("index");
2504            // We can't use a clone of the list because we need to modify the
2505            // shared copy, so synchronize instead to prevent concurrent
2506            // modifications.
2507            synchronized (list) {
2508                final List<byte[]> history =
2509                        (List<byte[]>) inState.getSerializable("history");
2510                final int size = history.size();
2511                // Check the index bounds so we don't crash in native code while
2512                // restoring the history index.
2513                if (index < 0 || index >= size) {
2514                    return null;
2515                }
2516                for (int i = 0; i < size; i++) {
2517                    byte[] data = history.remove(0);
2518                    if (data == null) {
2519                        // If we somehow have null data, we cannot reconstruct
2520                        // the item and thus our history list cannot be rebuilt.
2521                        return null;
2522                    }
2523                    WebHistoryItem item = new WebHistoryItemClassic(data);
2524                    list.addHistoryItem(item);
2525                }
2526                // Grab the most recent copy to return to the caller.
2527                returnList = copyBackForwardList();
2528                // Update the copy to have the correct index.
2529                returnList.setCurrentIndex(index);
2530            }
2531            // Restore private browsing setting.
2532            if (inState.getBoolean("privateBrowsingEnabled")) {
2533                getSettings().setPrivateBrowsingEnabled(true);
2534            }
2535            mZoomManager.restoreZoomState(inState);
2536            // Remove all pending messages because we are restoring previous
2537            // state.
2538            mWebViewCore.removeMessages();
2539            if (isAccessibilityInjectionEnabled()) {
2540                getAccessibilityInjector().addAccessibilityApisIfNecessary();
2541            }
2542            // Send a restore state message.
2543            mWebViewCore.sendMessage(EventHub.RESTORE_STATE, index);
2544        }
2545        return returnList;
2546    }
2547
2548    /**
2549     * See {@link WebView#loadUrl(String, Map)}
2550     */
2551    @Override
2552    public void loadUrl(String url, Map<String, String> additionalHttpHeaders) {
2553        loadUrlImpl(url, additionalHttpHeaders);
2554    }
2555
2556    private void loadUrlImpl(String url, Map<String, String> extraHeaders) {
2557        switchOutDrawHistory();
2558        WebViewCore.GetUrlData arg = new WebViewCore.GetUrlData();
2559        arg.mUrl = url;
2560        arg.mExtraHeaders = extraHeaders;
2561        mWebViewCore.sendMessage(EventHub.LOAD_URL, arg);
2562        clearHelpers();
2563    }
2564
2565    /**
2566     * See {@link WebView#loadUrl(String)}
2567     */
2568    @Override
2569    public void loadUrl(String url) {
2570        loadUrlImpl(url);
2571    }
2572
2573    private void loadUrlImpl(String url) {
2574        if (url == null) {
2575            return;
2576        }
2577        loadUrlImpl(url, null);
2578    }
2579
2580    /**
2581     * See {@link WebView#postUrl(String, byte[])}
2582     */
2583    @Override
2584    public void postUrl(String url, byte[] postData) {
2585        if (URLUtil.isNetworkUrl(url)) {
2586            switchOutDrawHistory();
2587            WebViewCore.PostUrlData arg = new WebViewCore.PostUrlData();
2588            arg.mUrl = url;
2589            arg.mPostData = postData;
2590            mWebViewCore.sendMessage(EventHub.POST_URL, arg);
2591            clearHelpers();
2592        } else {
2593            loadUrlImpl(url);
2594        }
2595    }
2596
2597    /**
2598     * See {@link WebView#loadData(String, String, String)}
2599     */
2600    @Override
2601    public void loadData(String data, String mimeType, String encoding) {
2602        loadDataImpl(data, mimeType, encoding);
2603    }
2604
2605    private void loadDataImpl(String data, String mimeType, String encoding) {
2606        StringBuilder dataUrl = new StringBuilder("data:");
2607        dataUrl.append(mimeType);
2608        if ("base64".equals(encoding)) {
2609            dataUrl.append(";base64");
2610        }
2611        dataUrl.append(",");
2612        dataUrl.append(data);
2613        loadUrlImpl(dataUrl.toString());
2614    }
2615
2616    /**
2617     * See {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}
2618     */
2619    @Override
2620    public void loadDataWithBaseURL(String baseUrl, String data,
2621            String mimeType, String encoding, String historyUrl) {
2622
2623        if (baseUrl != null && baseUrl.toLowerCase().startsWith("data:")) {
2624            loadDataImpl(data, mimeType, encoding);
2625            return;
2626        }
2627        switchOutDrawHistory();
2628        WebViewCore.BaseUrlData arg = new WebViewCore.BaseUrlData();
2629        arg.mBaseUrl = baseUrl;
2630        arg.mData = data;
2631        arg.mMimeType = mimeType;
2632        arg.mEncoding = encoding;
2633        arg.mHistoryUrl = historyUrl;
2634        mWebViewCore.sendMessage(EventHub.LOAD_DATA, arg);
2635        clearHelpers();
2636    }
2637
2638    /**
2639     * See {@link WebView#saveWebArchive(String)}
2640     */
2641    @Override
2642    public void saveWebArchive(String filename) {
2643        saveWebArchiveImpl(filename, false, null);
2644    }
2645
2646    /* package */ static class SaveWebArchiveMessage {
2647        SaveWebArchiveMessage (String basename, boolean autoname, ValueCallback<String> callback) {
2648            mBasename = basename;
2649            mAutoname = autoname;
2650            mCallback = callback;
2651        }
2652
2653        /* package */ final String mBasename;
2654        /* package */ final boolean mAutoname;
2655        /* package */ final ValueCallback<String> mCallback;
2656        /* package */ String mResultFile;
2657    }
2658
2659    /**
2660     * See {@link WebView#saveWebArchive(String, boolean, ValueCallback)}
2661     */
2662    @Override
2663    public void saveWebArchive(String basename, boolean autoname, ValueCallback<String> callback) {
2664        saveWebArchiveImpl(basename, autoname, callback);
2665    }
2666
2667    private void saveWebArchiveImpl(String basename, boolean autoname,
2668            ValueCallback<String> callback) {
2669        mWebViewCore.sendMessage(EventHub.SAVE_WEBARCHIVE,
2670            new SaveWebArchiveMessage(basename, autoname, callback));
2671    }
2672
2673    /**
2674     * See {@link WebView#stopLoading()}
2675     */
2676    @Override
2677    public void stopLoading() {
2678        // TODO: should we clear all the messages in the queue before sending
2679        // STOP_LOADING?
2680        switchOutDrawHistory();
2681        mWebViewCore.sendMessage(EventHub.STOP_LOADING);
2682    }
2683
2684    /**
2685     * See {@link WebView#reload()}
2686     */
2687    @Override
2688    public void reload() {
2689        clearHelpers();
2690        switchOutDrawHistory();
2691        mWebViewCore.sendMessage(EventHub.RELOAD);
2692    }
2693
2694    /**
2695     * See {@link WebView#canGoBack()}
2696     */
2697    @Override
2698    public boolean canGoBack() {
2699        WebBackForwardListClassic l = mCallbackProxy.getBackForwardList();
2700        synchronized (l) {
2701            if (l.getClearPending()) {
2702                return false;
2703            } else {
2704                return l.getCurrentIndex() > 0;
2705            }
2706        }
2707    }
2708
2709    /**
2710     * See {@link WebView#goBack()}
2711     */
2712    @Override
2713    public void goBack() {
2714        goBackOrForwardImpl(-1);
2715    }
2716
2717    /**
2718     * See {@link WebView#canGoForward()}
2719     */
2720    @Override
2721    public boolean canGoForward() {
2722        WebBackForwardListClassic l = mCallbackProxy.getBackForwardList();
2723        synchronized (l) {
2724            if (l.getClearPending()) {
2725                return false;
2726            } else {
2727                return l.getCurrentIndex() < l.getSize() - 1;
2728            }
2729        }
2730    }
2731
2732    /**
2733     * See {@link WebView#goForward()}
2734     */
2735    @Override
2736    public void goForward() {
2737        goBackOrForwardImpl(1);
2738    }
2739
2740    /**
2741     * See {@link WebView#canGoBackOrForward(int)}
2742     */
2743    @Override
2744    public boolean canGoBackOrForward(int steps) {
2745        WebBackForwardListClassic l = mCallbackProxy.getBackForwardList();
2746        synchronized (l) {
2747            if (l.getClearPending()) {
2748                return false;
2749            } else {
2750                int newIndex = l.getCurrentIndex() + steps;
2751                return newIndex >= 0 && newIndex < l.getSize();
2752            }
2753        }
2754    }
2755
2756    /**
2757     * See {@link WebView#goBackOrForward(int)}
2758     */
2759    @Override
2760    public void goBackOrForward(int steps) {
2761        goBackOrForwardImpl(steps);
2762    }
2763
2764    private void goBackOrForwardImpl(int steps) {
2765        goBackOrForward(steps, false);
2766    }
2767
2768    private void goBackOrForward(int steps, boolean ignoreSnapshot) {
2769        if (steps != 0) {
2770            clearHelpers();
2771            mWebViewCore.sendMessage(EventHub.GO_BACK_FORWARD, steps,
2772                    ignoreSnapshot ? 1 : 0);
2773        }
2774    }
2775
2776    /**
2777     * See {@link WebView#isPrivateBrowsingEnabled()}
2778     */
2779    @Override
2780    public boolean isPrivateBrowsingEnabled() {
2781        WebSettingsClassic settings = getSettings();
2782        return (settings != null) ? settings.isPrivateBrowsingEnabled() : false;
2783    }
2784
2785    private void startPrivateBrowsing() {
2786        getSettings().setPrivateBrowsingEnabled(true);
2787    }
2788
2789    private boolean extendScroll(int y) {
2790        int finalY = mScroller.getFinalY();
2791        int newY = pinLocY(finalY + y);
2792        if (newY == finalY) return false;
2793        mScroller.setFinalY(newY);
2794        mScroller.extendDuration(computeDuration(0, y));
2795        return true;
2796    }
2797
2798    /**
2799     * See {@link WebView#pageUp(boolean)}
2800     */
2801    @Override
2802    public boolean pageUp(boolean top) {
2803        if (mNativeClass == 0) {
2804            return false;
2805        }
2806        if (top) {
2807            // go to the top of the document
2808            return pinScrollTo(getScrollX(), 0, true, 0);
2809        }
2810        // Page up
2811        int h = getHeight();
2812        int y;
2813        if (h > 2 * PAGE_SCROLL_OVERLAP) {
2814            y = -h + PAGE_SCROLL_OVERLAP;
2815        } else {
2816            y = -h / 2;
2817        }
2818        return mScroller.isFinished() ? pinScrollBy(0, y, true, 0)
2819                : extendScroll(y);
2820    }
2821
2822    /**
2823     * See {@link WebView#pageDown(boolean)}
2824     */
2825    @Override
2826    public boolean pageDown(boolean bottom) {
2827        if (mNativeClass == 0) {
2828            return false;
2829        }
2830        if (bottom) {
2831            return pinScrollTo(getScrollX(), computeRealVerticalScrollRange(), true, 0);
2832        }
2833        // Page down.
2834        int h = getHeight();
2835        int y;
2836        if (h > 2 * PAGE_SCROLL_OVERLAP) {
2837            y = h - PAGE_SCROLL_OVERLAP;
2838        } else {
2839            y = h / 2;
2840        }
2841        return mScroller.isFinished() ? pinScrollBy(0, y, true, 0)
2842                : extendScroll(y);
2843    }
2844
2845    /**
2846     * See {@link WebView#clearView()}
2847     */
2848    @Override
2849    public void clearView() {
2850        mContentWidth = 0;
2851        mContentHeight = 0;
2852        setBaseLayer(0, false, false);
2853        mWebViewCore.sendMessage(EventHub.CLEAR_CONTENT);
2854    }
2855
2856    /**
2857     * See {@link WebView#capturePicture()}
2858     */
2859    @Override
2860    public Picture capturePicture() {
2861        if (mNativeClass == 0) return null;
2862        Picture result = new Picture();
2863        nativeCopyBaseContentToPicture(result);
2864        return result;
2865    }
2866
2867    /**
2868     * See {@link WebView#getScale()}
2869     */
2870    @Override
2871    public float getScale() {
2872        return mZoomManager.getScale();
2873    }
2874
2875    /**
2876     * Compute the reading level scale of the WebView
2877     * @param scale The current scale.
2878     * @return The reading level scale.
2879     */
2880    /*package*/ float computeReadingLevelScale(float scale) {
2881        return mZoomManager.computeReadingLevelScale(scale);
2882    }
2883
2884    /**
2885     * See {@link WebView#setInitialScale(int)}
2886     */
2887    @Override
2888    public void setInitialScale(int scaleInPercent) {
2889        mZoomManager.setInitialScaleInPercent(scaleInPercent);
2890    }
2891
2892    /**
2893     * See {@link WebView#invokeZoomPicker()}
2894     */
2895    @Override
2896    public void invokeZoomPicker() {
2897        if (!getSettings().supportZoom()) {
2898            Log.w(LOGTAG, "This WebView doesn't support zoom.");
2899            return;
2900        }
2901        clearHelpers();
2902        mZoomManager.invokeZoomPicker();
2903    }
2904
2905    /**
2906     * See {@link WebView#getHitTestResult()}
2907     */
2908    @Override
2909    public HitTestResult getHitTestResult() {
2910        return mInitialHitTestResult;
2911    }
2912
2913    // No left edge for double-tap zoom alignment
2914    static final int NO_LEFTEDGE = -1;
2915
2916    int getBlockLeftEdge(int x, int y, float readingScale) {
2917        float invReadingScale = 1.0f / readingScale;
2918        int readingWidth = (int) (getViewWidth() * invReadingScale);
2919        int left = NO_LEFTEDGE;
2920        if (mFocusedNode != null) {
2921            final int length = mFocusedNode.mEnclosingParentRects.length;
2922            for (int i = 0; i < length; i++) {
2923                Rect rect = mFocusedNode.mEnclosingParentRects[i];
2924                if (rect.width() < mFocusedNode.mHitTestSlop) {
2925                    // ignore bounding boxes that are too small
2926                    continue;
2927                } else if (rect.width() > readingWidth) {
2928                    // stop when bounding box doesn't fit the screen width
2929                    // at reading scale
2930                    break;
2931                }
2932
2933                left = rect.left;
2934            }
2935        }
2936
2937        return left;
2938    }
2939
2940    /**
2941     * See {@link WebView#requestFocusNodeHref(Message)}
2942     */
2943    @Override
2944    public void requestFocusNodeHref(Message hrefMsg) {
2945        if (hrefMsg == null) {
2946            return;
2947        }
2948        int contentX = viewToContentX(mLastTouchX + getScrollX());
2949        int contentY = viewToContentY(mLastTouchY + getScrollY());
2950        if (mFocusedNode != null && mFocusedNode.mHitTestX == contentX
2951                && mFocusedNode.mHitTestY == contentY) {
2952            hrefMsg.getData().putString(FocusNodeHref.URL, mFocusedNode.mLinkUrl);
2953            hrefMsg.getData().putString(FocusNodeHref.TITLE, mFocusedNode.mAnchorText);
2954            hrefMsg.getData().putString(FocusNodeHref.SRC, mFocusedNode.mImageUrl);
2955            hrefMsg.sendToTarget();
2956            return;
2957        }
2958        mWebViewCore.sendMessage(EventHub.REQUEST_CURSOR_HREF,
2959                contentX, contentY, hrefMsg);
2960    }
2961
2962    /**
2963     * See {@link WebView#requestImageRef(Message)}
2964     */
2965    @Override
2966    public void requestImageRef(Message msg) {
2967        if (0 == mNativeClass) return; // client isn't initialized
2968        String url = mFocusedNode != null ? mFocusedNode.mImageUrl : null;
2969        Bundle data = msg.getData();
2970        data.putString("url", url);
2971        msg.setData(data);
2972        msg.sendToTarget();
2973    }
2974
2975    static int pinLoc(int x, int viewMax, int docMax) {
2976//        Log.d(LOGTAG, "-- pinLoc " + x + " " + viewMax + " " + docMax);
2977        if (docMax < viewMax) {   // the doc has room on the sides for "blank"
2978            // pin the short document to the top/left of the screen
2979            x = 0;
2980//            Log.d(LOGTAG, "--- center " + x);
2981        } else if (x < 0) {
2982            x = 0;
2983//            Log.d(LOGTAG, "--- zero");
2984        } else if (x + viewMax > docMax) {
2985            x = docMax - viewMax;
2986//            Log.d(LOGTAG, "--- pin " + x);
2987        }
2988        return x;
2989    }
2990
2991    // Expects x in view coordinates
2992    int pinLocX(int x) {
2993        if (mInOverScrollMode) return x;
2994        return pinLoc(x, getViewWidth(), computeRealHorizontalScrollRange());
2995    }
2996
2997    // Expects y in view coordinates
2998    int pinLocY(int y) {
2999        if (mInOverScrollMode) return y;
3000        return pinLoc(y, getViewHeightWithTitle(),
3001                      computeRealVerticalScrollRange() + getTitleHeight());
3002    }
3003
3004    /**
3005     * Given a distance in view space, convert it to content space. Note: this
3006     * does not reflect translation, just scaling, so this should not be called
3007     * with coordinates, but should be called for dimensions like width or
3008     * height.
3009     */
3010    private int viewToContentDimension(int d) {
3011        return Math.round(d * mZoomManager.getInvScale());
3012    }
3013
3014    /**
3015     * Given an x coordinate in view space, convert it to content space.  Also
3016     * may be used for absolute heights.
3017     */
3018    /*package*/ int viewToContentX(int x) {
3019        return viewToContentDimension(x);
3020    }
3021
3022    /**
3023     * Given a y coordinate in view space, convert it to content space.
3024     * Takes into account the height of the title bar if there is one
3025     * embedded into the WebView.
3026     */
3027    /*package*/ int viewToContentY(int y) {
3028        return viewToContentDimension(y - getTitleHeight());
3029    }
3030
3031    /**
3032     * Given a x coordinate in view space, convert it to content space.
3033     * Returns the result as a float.
3034     */
3035    private float viewToContentXf(int x) {
3036        return x * mZoomManager.getInvScale();
3037    }
3038
3039    /**
3040     * Given a y coordinate in view space, convert it to content space.
3041     * Takes into account the height of the title bar if there is one
3042     * embedded into the WebView. Returns the result as a float.
3043     */
3044    private float viewToContentYf(int y) {
3045        return (y - getTitleHeight()) * mZoomManager.getInvScale();
3046    }
3047
3048    /**
3049     * Given a distance in content space, convert it to view space. Note: this
3050     * does not reflect translation, just scaling, so this should not be called
3051     * with coordinates, but should be called for dimensions like width or
3052     * height.
3053     */
3054    /*package*/ int contentToViewDimension(int d) {
3055        return Math.round(d * mZoomManager.getScale());
3056    }
3057
3058    /**
3059     * Given an x coordinate in content space, convert it to view
3060     * space.
3061     */
3062    /*package*/ int contentToViewX(int x) {
3063        return contentToViewDimension(x);
3064    }
3065
3066    /**
3067     * Given a y coordinate in content space, convert it to view
3068     * space.  Takes into account the height of the title bar.
3069     */
3070    /*package*/ int contentToViewY(int y) {
3071        return contentToViewDimension(y) + getTitleHeight();
3072    }
3073
3074    private Rect contentToViewRect(Rect x) {
3075        return new Rect(contentToViewX(x.left), contentToViewY(x.top),
3076                        contentToViewX(x.right), contentToViewY(x.bottom));
3077    }
3078
3079    /*  To invalidate a rectangle in content coordinates, we need to transform
3080        the rect into view coordinates, so we can then call invalidate(...).
3081
3082        Normally, we would just call contentToView[XY](...), which eventually
3083        calls Math.round(coordinate * mActualScale). However, for invalidates,
3084        we need to account for the slop that occurs with antialiasing. To
3085        address that, we are a little more liberal in the size of the rect that
3086        we invalidate.
3087
3088        This liberal calculation calls floor() for the top/left, and ceil() for
3089        the bottom/right coordinates. This catches the possible extra pixels of
3090        antialiasing that we might have missed with just round().
3091     */
3092
3093    // Called by JNI to invalidate the View, given rectangle coordinates in
3094    // content space
3095    private void viewInvalidate(int l, int t, int r, int b) {
3096        final float scale = mZoomManager.getScale();
3097        final int dy = getTitleHeight();
3098        mWebView.invalidate((int)Math.floor(l * scale),
3099                (int)Math.floor(t * scale) + dy,
3100                (int)Math.ceil(r * scale),
3101                (int)Math.ceil(b * scale) + dy);
3102    }
3103
3104    // Called by JNI to invalidate the View after a delay, given rectangle
3105    // coordinates in content space
3106    private void viewInvalidateDelayed(long delay, int l, int t, int r, int b) {
3107        final float scale = mZoomManager.getScale();
3108        final int dy = getTitleHeight();
3109        mWebView.postInvalidateDelayed(delay,
3110                (int)Math.floor(l * scale),
3111                (int)Math.floor(t * scale) + dy,
3112                (int)Math.ceil(r * scale),
3113                (int)Math.ceil(b * scale) + dy);
3114    }
3115
3116    private void invalidateContentRect(Rect r) {
3117        viewInvalidate(r.left, r.top, r.right, r.bottom);
3118    }
3119
3120    // stop the scroll animation, and don't let a subsequent fling add
3121    // to the existing velocity
3122    private void abortAnimation() {
3123        mScroller.abortAnimation();
3124        mLastVelocity = 0;
3125    }
3126
3127    /* call from webcoreview.draw(), so we're still executing in the UI thread
3128    */
3129    private void recordNewContentSize(int w, int h, boolean updateLayout) {
3130
3131        // premature data from webkit, ignore
3132        if ((w | h) == 0) {
3133            invalidate();
3134            return;
3135        }
3136
3137        // don't abort a scroll animation if we didn't change anything
3138        if (mContentWidth != w || mContentHeight != h) {
3139            // record new dimensions
3140            mContentWidth = w;
3141            mContentHeight = h;
3142            // If history Picture is drawn, don't update scroll. They will be
3143            // updated when we get out of that mode.
3144            if (!mDrawHistory) {
3145                // repin our scroll, taking into account the new content size
3146                updateScrollCoordinates(pinLocX(getScrollX()), pinLocY(getScrollY()));
3147                if (!mScroller.isFinished()) {
3148                    // We are in the middle of a scroll.  Repin the final scroll
3149                    // position.
3150                    mScroller.setFinalX(pinLocX(mScroller.getFinalX()));
3151                    mScroller.setFinalY(pinLocY(mScroller.getFinalY()));
3152                }
3153            }
3154            invalidate();
3155        }
3156        contentSizeChanged(updateLayout);
3157    }
3158
3159    // Used to avoid sending many visible rect messages.
3160    private Rect mLastVisibleRectSent = new Rect();
3161    private Rect mLastGlobalRect = new Rect();
3162    private Rect mVisibleRect = new Rect();
3163    private Rect mGlobalVisibleRect = new Rect();
3164    private Point mScrollOffset = new Point();
3165
3166    Rect sendOurVisibleRect() {
3167        if (mZoomManager.isPreventingWebkitUpdates()) return mLastVisibleRectSent;
3168        calcOurContentVisibleRect(mVisibleRect);
3169        // Rect.equals() checks for null input.
3170        if (!mVisibleRect.equals(mLastVisibleRectSent)) {
3171            if (!mBlockWebkitViewMessages) {
3172                mScrollOffset.set(mVisibleRect.left, mVisibleRect.top);
3173                mWebViewCore.removeMessages(EventHub.SET_SCROLL_OFFSET);
3174                mWebViewCore.sendMessage(EventHub.SET_SCROLL_OFFSET,
3175                        mSendScrollEvent ? 1 : 0, mScrollOffset);
3176            }
3177            mLastVisibleRectSent.set(mVisibleRect);
3178            mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
3179        }
3180        if (mWebView.getGlobalVisibleRect(mGlobalVisibleRect)
3181                && !mGlobalVisibleRect.equals(mLastGlobalRect)) {
3182            if (DebugFlags.WEB_VIEW) {
3183                Log.v(LOGTAG, "sendOurVisibleRect=(" + mGlobalVisibleRect.left + ","
3184                        + mGlobalVisibleRect.top + ",r=" + mGlobalVisibleRect.right + ",b="
3185                        + mGlobalVisibleRect.bottom);
3186            }
3187            // TODO: the global offset is only used by windowRect()
3188            // in ChromeClientAndroid ; other clients such as touch
3189            // and mouse events could return view + screen relative points.
3190            if (!mBlockWebkitViewMessages) {
3191                mWebViewCore.sendMessage(EventHub.SET_GLOBAL_BOUNDS, mGlobalVisibleRect);
3192            }
3193            mLastGlobalRect.set(mGlobalVisibleRect);
3194        }
3195        return mVisibleRect;
3196    }
3197
3198    private Point mGlobalVisibleOffset = new Point();
3199    // Sets r to be the visible rectangle of our webview in view coordinates
3200    private void calcOurVisibleRect(Rect r) {
3201        mWebView.getGlobalVisibleRect(r, mGlobalVisibleOffset);
3202        r.offset(-mGlobalVisibleOffset.x, -mGlobalVisibleOffset.y);
3203    }
3204
3205    // Sets r to be our visible rectangle in content coordinates
3206    private void calcOurContentVisibleRect(Rect r) {
3207        calcOurVisibleRect(r);
3208        r.left = viewToContentX(r.left);
3209        // viewToContentY will remove the total height of the title bar.  Add
3210        // the visible height back in to account for the fact that if the title
3211        // bar is partially visible, the part of the visible rect which is
3212        // displaying our content is displaced by that amount.
3213        r.top = viewToContentY(r.top + getVisibleTitleHeightImpl());
3214        r.right = viewToContentX(r.right);
3215        r.bottom = viewToContentY(r.bottom);
3216    }
3217
3218    private final Rect mTempContentVisibleRect = new Rect();
3219    // Sets r to be our visible rectangle in content coordinates. We use this
3220    // method on the native side to compute the position of the fixed layers.
3221    // Uses floating coordinates (necessary to correctly place elements when
3222    // the scale factor is not 1)
3223    private void calcOurContentVisibleRectF(RectF r) {
3224        calcOurVisibleRect(mTempContentVisibleRect);
3225        viewToContentVisibleRect(r, mTempContentVisibleRect);
3226    }
3227
3228    static class ViewSizeData {
3229        int mWidth;
3230        int mHeight;
3231        float mHeightWidthRatio;
3232        int mActualViewHeight;
3233        int mTextWrapWidth;
3234        int mAnchorX;
3235        int mAnchorY;
3236        float mScale;
3237        boolean mIgnoreHeight;
3238    }
3239
3240    /**
3241     * Compute unzoomed width and height, and if they differ from the last
3242     * values we sent, send them to webkit (to be used as new viewport)
3243     *
3244     * @param force ensures that the message is sent to webkit even if the width
3245     * or height has not changed since the last message
3246     *
3247     * @return true if new values were sent
3248     */
3249    boolean sendViewSizeZoom(boolean force) {
3250        if (mBlockWebkitViewMessages) return false;
3251        if (mZoomManager.isPreventingWebkitUpdates()) return false;
3252
3253        int viewWidth = getViewWidth();
3254        int newWidth = Math.round(viewWidth * mZoomManager.getInvScale());
3255        // This height could be fixed and be different from actual visible height.
3256        int viewHeight = getViewHeightWithTitle() - getTitleHeight();
3257        int newHeight = Math.round(viewHeight * mZoomManager.getInvScale());
3258        // Make the ratio more accurate than (newHeight / newWidth), since the
3259        // latter both are calculated and rounded.
3260        float heightWidthRatio = (float) viewHeight / viewWidth;
3261        /*
3262         * Because the native side may have already done a layout before the
3263         * View system was able to measure us, we have to send a height of 0 to
3264         * remove excess whitespace when we grow our width. This will trigger a
3265         * layout and a change in content size. This content size change will
3266         * mean that contentSizeChanged will either call this method directly or
3267         * indirectly from onSizeChanged.
3268         */
3269        if (newWidth > mLastWidthSent && mWrapContent) {
3270            newHeight = 0;
3271            heightWidthRatio = 0;
3272        }
3273        // Actual visible content height.
3274        int actualViewHeight = Math.round(getViewHeight() * mZoomManager.getInvScale());
3275        // Avoid sending another message if the dimensions have not changed.
3276        if (newWidth != mLastWidthSent || newHeight != mLastHeightSent || force ||
3277                actualViewHeight != mLastActualHeightSent) {
3278            ViewSizeData data = new ViewSizeData();
3279            data.mWidth = newWidth;
3280            data.mHeight = newHeight;
3281            data.mHeightWidthRatio = heightWidthRatio;
3282            data.mActualViewHeight = actualViewHeight;
3283            data.mTextWrapWidth = Math.round(viewWidth / mZoomManager.getTextWrapScale());
3284            data.mScale = mZoomManager.getScale();
3285            data.mIgnoreHeight = mZoomManager.isFixedLengthAnimationInProgress()
3286                    && !mHeightCanMeasure;
3287            data.mAnchorX = mZoomManager.getDocumentAnchorX();
3288            data.mAnchorY = mZoomManager.getDocumentAnchorY();
3289            mWebViewCore.sendMessage(EventHub.VIEW_SIZE_CHANGED, data);
3290            mLastWidthSent = newWidth;
3291            mLastHeightSent = newHeight;
3292            mLastActualHeightSent = actualViewHeight;
3293            mZoomManager.clearDocumentAnchor();
3294            return true;
3295        }
3296        return false;
3297    }
3298
3299    /**
3300     * Update the double-tap zoom.
3301     */
3302    /* package */ void updateDoubleTapZoom(int doubleTapZoom) {
3303        mZoomManager.updateDoubleTapZoom(doubleTapZoom);
3304    }
3305
3306    private int computeRealHorizontalScrollRange() {
3307        if (mDrawHistory) {
3308            return mHistoryWidth;
3309        } else {
3310            // to avoid rounding error caused unnecessary scrollbar, use floor
3311            return (int) Math.floor(mContentWidth * mZoomManager.getScale());
3312        }
3313    }
3314
3315    @Override
3316    public int computeHorizontalScrollRange() {
3317        int range = computeRealHorizontalScrollRange();
3318
3319        // Adjust reported range if overscrolled to compress the scroll bars
3320        final int scrollX = getScrollX();
3321        final int overscrollRight = computeMaxScrollX();
3322        if (scrollX < 0) {
3323            range -= scrollX;
3324        } else if (scrollX > overscrollRight) {
3325            range += scrollX - overscrollRight;
3326        }
3327
3328        return range;
3329    }
3330
3331    @Override
3332    public int computeHorizontalScrollOffset() {
3333        return Math.max(getScrollX(), 0);
3334    }
3335
3336    private int computeRealVerticalScrollRange() {
3337        if (mDrawHistory) {
3338            return mHistoryHeight;
3339        } else {
3340            // to avoid rounding error caused unnecessary scrollbar, use floor
3341            return (int) Math.floor(mContentHeight * mZoomManager.getScale());
3342        }
3343    }
3344
3345    @Override
3346    public int computeVerticalScrollRange() {
3347        int range = computeRealVerticalScrollRange();
3348
3349        // Adjust reported range if overscrolled to compress the scroll bars
3350        final int scrollY = getScrollY();
3351        final int overscrollBottom = computeMaxScrollY();
3352        if (scrollY < 0) {
3353            range -= scrollY;
3354        } else if (scrollY > overscrollBottom) {
3355            range += scrollY - overscrollBottom;
3356        }
3357
3358        return range;
3359    }
3360
3361    @Override
3362    public int computeVerticalScrollOffset() {
3363        return Math.max(getScrollY() - getTitleHeight(), 0);
3364    }
3365
3366    @Override
3367    public int computeVerticalScrollExtent() {
3368        return getViewHeight();
3369    }
3370
3371    @Override
3372    public void onDrawVerticalScrollBar(Canvas canvas,
3373                                           Drawable scrollBar,
3374                                           int l, int t, int r, int b) {
3375        if (getScrollY() < 0) {
3376            t -= getScrollY();
3377        }
3378        scrollBar.setBounds(l, t + getVisibleTitleHeightImpl(), r, b);
3379        scrollBar.draw(canvas);
3380    }
3381
3382    @Override
3383    public void onOverScrolled(int scrollX, int scrollY, boolean clampedX,
3384            boolean clampedY) {
3385        // Special-case layer scrolling so that we do not trigger normal scroll
3386        // updating.
3387        if (mTouchMode == TOUCH_DRAG_TEXT_MODE) {
3388            scrollEditText(scrollX, scrollY);
3389            return;
3390        }
3391        if (mTouchMode == TOUCH_DRAG_LAYER_MODE) {
3392            scrollLayerTo(scrollX, scrollY);
3393            animateHandles();
3394            return;
3395        }
3396        mInOverScrollMode = false;
3397        int maxX = computeMaxScrollX();
3398        int maxY = computeMaxScrollY();
3399        if (maxX == 0) {
3400            // do not over scroll x if the page just fits the screen
3401            scrollX = pinLocX(scrollX);
3402        } else if (scrollX < 0 || scrollX > maxX) {
3403            mInOverScrollMode = true;
3404        }
3405        if (scrollY < 0 || scrollY > maxY) {
3406            mInOverScrollMode = true;
3407        }
3408
3409        int oldX = getScrollX();
3410        int oldY = getScrollY();
3411
3412        mWebViewPrivate.super_scrollTo(scrollX, scrollY);
3413
3414        animateHandles();
3415
3416        if (mOverScrollGlow != null) {
3417            mOverScrollGlow.pullGlow(getScrollX(), getScrollY(), oldX, oldY, maxX, maxY);
3418        }
3419    }
3420
3421    /**
3422     * See {@link WebView#getUrl()}
3423     */
3424    @Override
3425    public String getUrl() {
3426        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
3427        return h != null ? h.getUrl() : null;
3428    }
3429
3430    /**
3431     * See {@link WebView#getOriginalUrl()}
3432     */
3433    @Override
3434    public String getOriginalUrl() {
3435        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
3436        return h != null ? h.getOriginalUrl() : null;
3437    }
3438
3439    /**
3440     * See {@link WebView#getTitle()}
3441     */
3442    @Override
3443    public String getTitle() {
3444        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
3445        return h != null ? h.getTitle() : null;
3446    }
3447
3448    /**
3449     * See {@link WebView#getFavicon()}
3450     */
3451    @Override
3452    public Bitmap getFavicon() {
3453        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
3454        return h != null ? h.getFavicon() : null;
3455    }
3456
3457    /**
3458     * See {@link WebView#getTouchIconUrl()}
3459     */
3460    @Override
3461    public String getTouchIconUrl() {
3462        WebHistoryItemClassic h = mCallbackProxy.getBackForwardList().getCurrentItem();
3463        return h != null ? h.getTouchIconUrl() : null;
3464    }
3465
3466    /**
3467     * See {@link WebView#getProgress()}
3468     */
3469    @Override
3470    public int getProgress() {
3471        return mCallbackProxy.getProgress();
3472    }
3473
3474    /**
3475     * See {@link WebView#getContentHeight()}
3476     */
3477    @Override
3478    public int getContentHeight() {
3479        return mContentHeight;
3480    }
3481
3482    /**
3483     * See {@link WebView#getContentWidth()}
3484     */
3485    @Override
3486    public int getContentWidth() {
3487        return mContentWidth;
3488    }
3489
3490    public int getPageBackgroundColor() {
3491        if (mNativeClass == 0) return Color.WHITE;
3492        return nativeGetBackgroundColor(mNativeClass);
3493    }
3494
3495    /**
3496     * See {@link WebView#pauseTimers()}
3497     */
3498    @Override
3499    public void pauseTimers() {
3500        mWebViewCore.sendMessage(EventHub.PAUSE_TIMERS);
3501    }
3502
3503    /**
3504     * See {@link WebView#resumeTimers()}
3505     */
3506    @Override
3507    public void resumeTimers() {
3508        mWebViewCore.sendMessage(EventHub.RESUME_TIMERS);
3509    }
3510
3511    /**
3512     * See {@link WebView#onPause()}
3513     */
3514    @Override
3515    public void onPause() {
3516        if (!mIsPaused) {
3517            mIsPaused = true;
3518            mWebViewCore.sendMessage(EventHub.ON_PAUSE);
3519            // We want to pause the current playing video when switching out
3520            // from the current WebView/tab.
3521            if (mHTML5VideoViewProxy != null) {
3522                mHTML5VideoViewProxy.pauseAndDispatch();
3523            }
3524            if (mNativeClass != 0) {
3525                nativeSetPauseDrawing(mNativeClass, true);
3526            }
3527
3528            cancelDialogs();
3529            WebCoreThreadWatchdog.pause();
3530        }
3531    }
3532
3533    @Override
3534    public void onWindowVisibilityChanged(int visibility) {
3535        updateDrawingState();
3536    }
3537
3538    void updateDrawingState() {
3539        if (mNativeClass == 0 || mIsPaused) return;
3540        if (mWebView.getWindowVisibility() != View.VISIBLE) {
3541            nativeSetPauseDrawing(mNativeClass, true);
3542        } else if (mWebView.getVisibility() != View.VISIBLE) {
3543            nativeSetPauseDrawing(mNativeClass, true);
3544        } else {
3545            nativeSetPauseDrawing(mNativeClass, false);
3546        }
3547    }
3548
3549    /**
3550     * See {@link WebView#onResume()}
3551     */
3552    @Override
3553    public void onResume() {
3554        if (mIsPaused) {
3555            mIsPaused = false;
3556            mWebViewCore.sendMessage(EventHub.ON_RESUME);
3557            if (mNativeClass != 0) {
3558                nativeSetPauseDrawing(mNativeClass, false);
3559            }
3560        }
3561        // We get a call to onResume for new WebViews (i.e. mIsPaused will be false). We need
3562        // to ensure that the Watchdog thread is running for the new WebView, so call
3563        // it outside the if block above.
3564        WebCoreThreadWatchdog.resume();
3565    }
3566
3567    /**
3568     * See {@link WebView#isPaused()}
3569     */
3570    @Override
3571    public boolean isPaused() {
3572        return mIsPaused;
3573    }
3574
3575    /**
3576     * See {@link WebView#freeMemory()}
3577     */
3578    @Override
3579    public void freeMemory() {
3580        mWebViewCore.sendMessage(EventHub.FREE_MEMORY);
3581    }
3582
3583    /**
3584     * See {@link WebView#clearCache(boolean)}
3585     */
3586    @Override
3587    public void clearCache(boolean includeDiskFiles) {
3588        // Note: this really needs to be a static method as it clears cache for all
3589        // WebView. But we need mWebViewCore to send message to WebCore thread, so
3590        // we can't make this static.
3591        mWebViewCore.sendMessage(EventHub.CLEAR_CACHE,
3592                includeDiskFiles ? 1 : 0, 0);
3593    }
3594
3595    /**
3596     * See {@link WebView#clearFormData()}
3597     */
3598    @Override
3599    public void clearFormData() {
3600        if (mAutoCompletePopup != null) {
3601            mAutoCompletePopup.clearAdapter();
3602        }
3603    }
3604
3605    /**
3606     * See {@link WebView#clearHistory()}
3607     */
3608    @Override
3609    public void clearHistory() {
3610        mCallbackProxy.getBackForwardList().setClearPending();
3611        mWebViewCore.sendMessage(EventHub.CLEAR_HISTORY);
3612    }
3613
3614    /**
3615     * See {@link WebView#clearSslPreferences()}
3616     */
3617    @Override
3618    public void clearSslPreferences() {
3619        mWebViewCore.sendMessage(EventHub.CLEAR_SSL_PREF_TABLE);
3620    }
3621
3622    /**
3623     * See {@link WebView#copyBackForwardList()}
3624     */
3625    @Override
3626    public WebBackForwardListClassic copyBackForwardList() {
3627        return mCallbackProxy.getBackForwardList().clone();
3628    }
3629
3630    /**
3631     * See {@link WebView#setFindListener(WebView.FindListener)}.
3632     * @hide
3633     */
3634     @Override
3635    public void setFindListener(WebView.FindListener listener) {
3636         mFindListener = listener;
3637     }
3638
3639    /**
3640     * See {@link WebView#findNext(boolean)}
3641     */
3642    @Override
3643    public void findNext(boolean forward) {
3644        if (0 == mNativeClass) return; // client isn't initialized
3645        if (mFindRequest != null) {
3646            mWebViewCore.sendMessage(EventHub.FIND_NEXT, forward ? 1 : 0, mFindRequest);
3647        }
3648    }
3649
3650    /**
3651     * See {@link WebView#findAll(String)}
3652     */
3653    @Override
3654    public int findAll(String find) {
3655        return findAllBody(find, false);
3656    }
3657
3658    @Override
3659    public void findAllAsync(String find) {
3660        findAllBody(find, true);
3661    }
3662
3663    private int findAllBody(String find, boolean isAsync) {
3664        if (0 == mNativeClass) return 0; // client isn't initialized
3665        mFindRequest = null;
3666        if (find == null) return 0;
3667        mWebViewCore.removeMessages(EventHub.FIND_ALL);
3668        mFindRequest = new WebViewCore.FindAllRequest(find);
3669        if (isAsync) {
3670            mWebViewCore.sendMessage(EventHub.FIND_ALL, mFindRequest);
3671            return 0; // no need to wait for response
3672        }
3673        synchronized(mFindRequest) {
3674            try {
3675                mWebViewCore.sendMessageAtFrontOfQueue(EventHub.FIND_ALL, mFindRequest);
3676                while (mFindRequest.mMatchCount == -1) {
3677                    mFindRequest.wait();
3678                }
3679            }
3680            catch (InterruptedException e) {
3681                return 0;
3682            }
3683            return mFindRequest.mMatchCount;
3684        }
3685    }
3686
3687    /**
3688     * Start an ActionMode for finding text in this WebView.  Only works if this
3689     *              WebView is attached to the view system.
3690     * @param text If non-null, will be the initial text to search for.
3691     *             Otherwise, the last String searched for in this WebView will
3692     *             be used to start.
3693     * @param showIme If true, show the IME, assuming the user will begin typing.
3694     *             If false and text is non-null, perform a find all.
3695     * @return boolean True if the find dialog is shown, false otherwise.
3696     */
3697    @Override
3698    public boolean showFindDialog(String text, boolean showIme) {
3699        FindActionModeCallback callback = new FindActionModeCallback(mContext);
3700        if (mWebView.getParent() == null || mWebView.startActionMode(callback) == null) {
3701            // Could not start the action mode, so end Find on page
3702            return false;
3703        }
3704        mCachedOverlappingActionModeHeight = -1;
3705        mFindCallback = callback;
3706        setFindIsUp(true);
3707        mFindCallback.setWebView(getWebView());
3708        if (showIme) {
3709            mFindCallback.showSoftInput();
3710        } else if (text != null) {
3711            mFindCallback.setText(text);
3712            mFindCallback.findAll();
3713            return true;
3714        }
3715        if (text == null) {
3716            text = mFindRequest == null ? null : mFindRequest.mSearchText;
3717        }
3718        if (text != null) {
3719            mFindCallback.setText(text);
3720            mFindCallback.findAll();
3721        }
3722        return true;
3723    }
3724
3725    /**
3726     * Keep track of the find callback so that we can remove its titlebar if
3727     * necessary.
3728     */
3729    private FindActionModeCallback mFindCallback;
3730
3731    /**
3732     * Toggle whether the find dialog is showing, for both native and Java.
3733     */
3734    private void setFindIsUp(boolean isUp) {
3735        mFindIsUp = isUp;
3736    }
3737
3738    // Used to know whether the find dialog is open.  Affects whether
3739    // or not we draw the highlights for matches.
3740    private boolean mFindIsUp;
3741
3742    // Keep track of the last find request sent.
3743    private WebViewCore.FindAllRequest mFindRequest = null;
3744
3745    /**
3746     * Return the first substring consisting of the address of a physical
3747     * location. Currently, only addresses in the United States are detected,
3748     * and consist of:
3749     * - a house number
3750     * - a street name
3751     * - a street type (Road, Circle, etc), either spelled out or abbreviated
3752     * - a city name
3753     * - a state or territory, either spelled out or two-letter abbr.
3754     * - an optional 5 digit or 9 digit zip code.
3755     *
3756     * All names must be correctly capitalized, and the zip code, if present,
3757     * must be valid for the state. The street type must be a standard USPS
3758     * spelling or abbreviation. The state or territory must also be spelled
3759     * or abbreviated using USPS standards. The house number may not exceed
3760     * five digits.
3761     * @param addr The string to search for addresses.
3762     *
3763     * @return the address, or if no address is found, return null.
3764     */
3765    public static String findAddress(String addr) {
3766        return findAddress(addr, false);
3767    }
3768
3769    /**
3770     * Return the first substring consisting of the address of a physical
3771     * location. Currently, only addresses in the United States are detected,
3772     * and consist of:
3773     * - a house number
3774     * - a street name
3775     * - a street type (Road, Circle, etc), either spelled out or abbreviated
3776     * - a city name
3777     * - a state or territory, either spelled out or two-letter abbr.
3778     * - an optional 5 digit or 9 digit zip code.
3779     *
3780     * Names are optionally capitalized, and the zip code, if present,
3781     * must be valid for the state. The street type must be a standard USPS
3782     * spelling or abbreviation. The state or territory must also be spelled
3783     * or abbreviated using USPS standards. The house number may not exceed
3784     * five digits.
3785     * @param addr The string to search for addresses.
3786     * @param caseInsensitive addr Set to true to make search ignore case.
3787     *
3788     * @return the address, or if no address is found, return null.
3789     */
3790    public static String findAddress(String addr, boolean caseInsensitive) {
3791        return WebViewCore.nativeFindAddress(addr, caseInsensitive);
3792    }
3793
3794    /**
3795     * See {@link WebView#clearMatches()}
3796     */
3797    @Override
3798    public void clearMatches() {
3799        if (mNativeClass == 0)
3800            return;
3801        mWebViewCore.removeMessages(EventHub.FIND_ALL);
3802        mWebViewCore.sendMessage(EventHub.FIND_ALL, null);
3803    }
3804
3805
3806    /**
3807     * Called when the find ActionMode ends.
3808     */
3809    @Override
3810    public void notifyFindDialogDismissed() {
3811        mFindCallback = null;
3812        mCachedOverlappingActionModeHeight = -1;
3813        if (mWebViewCore == null) {
3814            return;
3815        }
3816        clearMatches();
3817        setFindIsUp(false);
3818        // Now that the dialog has been removed, ensure that we scroll to a
3819        // location that is not beyond the end of the page.
3820        pinScrollTo(getScrollX(), getScrollY(), false, 0);
3821        invalidate();
3822    }
3823
3824    /**
3825     * See {@link WebView#documentHasImages(Message)}
3826     */
3827    @Override
3828    public void documentHasImages(Message response) {
3829        if (response == null) {
3830            return;
3831        }
3832        mWebViewCore.sendMessage(EventHub.DOC_HAS_IMAGES, response);
3833    }
3834
3835    /**
3836     * Request the scroller to abort any ongoing animation
3837     */
3838    public void stopScroll() {
3839        mScroller.forceFinished(true);
3840        mLastVelocity = 0;
3841    }
3842
3843    @Override
3844    public void computeScroll() {
3845        if (mScroller.computeScrollOffset()) {
3846            int oldX = getScrollX();
3847            int oldY = getScrollY();
3848            int x = mScroller.getCurrX();
3849            int y = mScroller.getCurrY();
3850            invalidate();  // So we draw again
3851
3852            if (!mScroller.isFinished()) {
3853                int rangeX = computeMaxScrollX();
3854                int rangeY = computeMaxScrollY();
3855                int overflingDistance = mOverflingDistance;
3856
3857                // Use the layer's scroll data if needed.
3858                if (mTouchMode == TOUCH_DRAG_LAYER_MODE) {
3859                    oldX = mScrollingLayerRect.left;
3860                    oldY = mScrollingLayerRect.top;
3861                    rangeX = mScrollingLayerRect.right;
3862                    rangeY = mScrollingLayerRect.bottom;
3863                    // No overscrolling for layers.
3864                    overflingDistance = 0;
3865                } else if (mTouchMode == TOUCH_DRAG_TEXT_MODE) {
3866                    oldX = getTextScrollX();
3867                    oldY = getTextScrollY();
3868                    rangeX = getMaxTextScrollX();
3869                    rangeY = getMaxTextScrollY();
3870                    overflingDistance = 0;
3871                }
3872
3873                mWebViewPrivate.overScrollBy(x - oldX, y - oldY, oldX, oldY,
3874                        rangeX, rangeY,
3875                        overflingDistance, overflingDistance, false);
3876
3877                if (mOverScrollGlow != null) {
3878                    mOverScrollGlow.absorbGlow(x, y, oldX, oldY, rangeX, rangeY);
3879                }
3880            } else {
3881                if (mTouchMode == TOUCH_DRAG_LAYER_MODE) {
3882                    // Update the layer position instead of WebView.
3883                    scrollLayerTo(x, y);
3884                } else if (mTouchMode == TOUCH_DRAG_TEXT_MODE) {
3885                    scrollEditText(x, y);
3886                } else {
3887                    setScrollXRaw(x);
3888                    setScrollYRaw(y);
3889                }
3890                abortAnimation();
3891                nativeSetIsScrolling(false);
3892                if (!mBlockWebkitViewMessages) {
3893                    WebViewCore.resumePriority();
3894                    if (!mSelectingText) {
3895                        WebViewCore.resumeUpdatePicture(mWebViewCore);
3896                    }
3897                }
3898                if (oldX != getScrollX() || oldY != getScrollY()) {
3899                    sendOurVisibleRect();
3900                }
3901            }
3902        } else {
3903            mWebViewPrivate.super_computeScroll();
3904        }
3905    }
3906
3907    private void scrollLayerTo(int x, int y) {
3908        int dx = mScrollingLayerRect.left - x;
3909        int dy = mScrollingLayerRect.top - y;
3910        if ((dx == 0 && dy == 0) || mNativeClass == 0) {
3911            return;
3912        }
3913        if (mSelectingText) {
3914            if (mSelectCursorBaseLayerId == mCurrentScrollingLayerId) {
3915                mSelectCursorBase.offset(dx, dy);
3916                mSelectCursorBaseTextQuad.offset(dx, dy);
3917            }
3918            if (mSelectCursorExtentLayerId == mCurrentScrollingLayerId) {
3919                mSelectCursorExtent.offset(dx, dy);
3920                mSelectCursorExtentTextQuad.offset(dx, dy);
3921            }
3922        }
3923        if (mAutoCompletePopup != null &&
3924                mCurrentScrollingLayerId == mEditTextLayerId) {
3925            mEditTextContentBounds.offset(dx, dy);
3926            mAutoCompletePopup.resetRect();
3927        }
3928        nativeScrollLayer(mNativeClass, mCurrentScrollingLayerId, x, y);
3929        mScrollingLayerRect.left = x;
3930        mScrollingLayerRect.top = y;
3931        mWebViewCore.sendMessage(WebViewCore.EventHub.SCROLL_LAYER, mCurrentScrollingLayerId,
3932                mScrollingLayerRect);
3933        mWebViewPrivate.onScrollChanged(getScrollX(), getScrollY(), getScrollX(), getScrollY());
3934        invalidate();
3935    }
3936
3937    private static int computeDuration(int dx, int dy) {
3938        int distance = Math.max(Math.abs(dx), Math.abs(dy));
3939        int duration = distance * 1000 / STD_SPEED;
3940        return Math.min(duration, MAX_DURATION);
3941    }
3942
3943    // helper to pin the scrollBy parameters (already in view coordinates)
3944    // returns true if the scroll was changed
3945    private boolean pinScrollBy(int dx, int dy, boolean animate, int animationDuration) {
3946        return pinScrollTo(getScrollX() + dx, getScrollY() + dy, animate, animationDuration);
3947    }
3948    // helper to pin the scrollTo parameters (already in view coordinates)
3949    // returns true if the scroll was changed
3950    private boolean pinScrollTo(int x, int y, boolean animate, int animationDuration) {
3951        abortAnimation();
3952        x = pinLocX(x);
3953        y = pinLocY(y);
3954        int dx = x - getScrollX();
3955        int dy = y - getScrollY();
3956
3957        if ((dx | dy) == 0) {
3958            return false;
3959        }
3960        if (animate) {
3961            //        Log.d(LOGTAG, "startScroll: " + dx + " " + dy);
3962            mScroller.startScroll(getScrollX(), getScrollY(), dx, dy,
3963                    animationDuration > 0 ? animationDuration : computeDuration(dx, dy));
3964            invalidate();
3965        } else {
3966            mWebView.scrollTo(x, y);
3967        }
3968        return true;
3969    }
3970
3971    // Scale from content to view coordinates, and pin.
3972    // Also called by jni webview.cpp
3973    private boolean setContentScrollBy(int cx, int cy, boolean animate) {
3974        if (mDrawHistory) {
3975            // disallow WebView to change the scroll position as History Picture
3976            // is used in the view system.
3977            // TODO: as we switchOutDrawHistory when trackball or navigation
3978            // keys are hit, this should be safe. Right?
3979            return false;
3980        }
3981        cx = contentToViewDimension(cx);
3982        cy = contentToViewDimension(cy);
3983        if (mHeightCanMeasure) {
3984            // move our visible rect according to scroll request
3985            if (cy != 0) {
3986                Rect tempRect = new Rect();
3987                calcOurVisibleRect(tempRect);
3988                tempRect.offset(cx, cy);
3989                mWebView.requestRectangleOnScreen(tempRect);
3990            }
3991            // FIXME: We scroll horizontally no matter what because currently
3992            // ScrollView and ListView will not scroll horizontally.
3993            // FIXME: Why do we only scroll horizontally if there is no
3994            // vertical scroll?
3995//                Log.d(LOGTAG, "setContentScrollBy cy=" + cy);
3996            return cy == 0 && cx != 0 && pinScrollBy(cx, 0, animate, 0);
3997        } else {
3998            return pinScrollBy(cx, cy, animate, 0);
3999        }
4000    }
4001
4002    /**
4003     * Called by CallbackProxy when the page starts loading.
4004     * @param url The URL of the page which has started loading.
4005     */
4006    /* package */ void onPageStarted(String url) {
4007        // every time we start a new page, we want to reset the
4008        // WebView certificate:  if the new site is secure, we
4009        // will reload it and get a new certificate set;
4010        // if the new site is not secure, the certificate must be
4011        // null, and that will be the case
4012        mWebView.setCertificate(null);
4013
4014        if (isAccessibilityInjectionEnabled()) {
4015            getAccessibilityInjector().onPageStarted(url);
4016        }
4017
4018        // Don't start out editing.
4019        mIsEditingText = false;
4020    }
4021
4022    /**
4023     * Called by CallbackProxy when the page finishes loading.
4024     * @param url The URL of the page which has finished loading.
4025     */
4026    /* package */ void onPageFinished(String url) {
4027        mZoomManager.onPageFinished(url);
4028
4029        if (isAccessibilityInjectionEnabled()) {
4030            getAccessibilityInjector().onPageFinished(url);
4031        }
4032    }
4033
4034    // scale from content to view coordinates, and pin
4035    private void contentScrollTo(int cx, int cy, boolean animate) {
4036        if (mDrawHistory) {
4037            // disallow WebView to change the scroll position as History Picture
4038            // is used in the view system.
4039            return;
4040        }
4041        int vx = contentToViewX(cx);
4042        int vy = contentToViewY(cy);
4043        pinScrollTo(vx, vy, animate, 0);
4044    }
4045
4046    /**
4047     * These are from webkit, and are in content coordinate system (unzoomed)
4048     */
4049    private void contentSizeChanged(boolean updateLayout) {
4050        // suppress 0,0 since we usually see real dimensions soon after
4051        // this avoids drawing the prev content in a funny place. If we find a
4052        // way to consolidate these notifications, this check may become
4053        // obsolete
4054        if ((mContentWidth | mContentHeight) == 0) {
4055            return;
4056        }
4057
4058        if (mHeightCanMeasure) {
4059            if (mWebView.getMeasuredHeight() != contentToViewDimension(mContentHeight)
4060                    || updateLayout) {
4061                mWebView.requestLayout();
4062            }
4063        } else if (mWidthCanMeasure) {
4064            if (mWebView.getMeasuredWidth() != contentToViewDimension(mContentWidth)
4065                    || updateLayout) {
4066                mWebView.requestLayout();
4067            }
4068        } else {
4069            // If we don't request a layout, try to send our view size to the
4070            // native side to ensure that WebCore has the correct dimensions.
4071            sendViewSizeZoom(false);
4072        }
4073    }
4074
4075    /**
4076     * See {@link WebView#setWebViewClient(WebViewClient)}
4077     */
4078    @Override
4079    public void setWebViewClient(WebViewClient client) {
4080        mCallbackProxy.setWebViewClient(client);
4081    }
4082
4083    /**
4084     * Gets the WebViewClient
4085     * @return the current WebViewClient instance.
4086     *
4087     * This is an implementation detail.
4088     */
4089    public WebViewClient getWebViewClient() {
4090        return mCallbackProxy.getWebViewClient();
4091    }
4092
4093    /**
4094     * See {@link WebView#setDownloadListener(DownloadListener)}
4095     */
4096    @Override
4097    public void setDownloadListener(DownloadListener listener) {
4098        mCallbackProxy.setDownloadListener(listener);
4099    }
4100
4101    /**
4102     * See {@link WebView#setWebChromeClient(WebChromeClient)}
4103     */
4104    @Override
4105    public void setWebChromeClient(WebChromeClient client) {
4106        mCallbackProxy.setWebChromeClient(client);
4107    }
4108
4109    /**
4110     * Gets the chrome handler.
4111     * @return the current WebChromeClient instance.
4112     *
4113     * This is an implementation detail.
4114     */
4115    public WebChromeClient getWebChromeClient() {
4116        return mCallbackProxy.getWebChromeClient();
4117    }
4118
4119    /**
4120     * Set the back/forward list client. This is an implementation of
4121     * WebBackForwardListClient for handling new items and changes in the
4122     * history index.
4123     * @param client An implementation of WebBackForwardListClient.
4124     */
4125    public void setWebBackForwardListClient(WebBackForwardListClient client) {
4126        mCallbackProxy.setWebBackForwardListClient(client);
4127    }
4128
4129    /**
4130     * Gets the WebBackForwardListClient.
4131     */
4132    public WebBackForwardListClient getWebBackForwardListClient() {
4133        return mCallbackProxy.getWebBackForwardListClient();
4134    }
4135
4136    /**
4137     * See {@link WebView#setPictureListener(PictureListener)}
4138     */
4139    @Override
4140    @Deprecated
4141    public void setPictureListener(PictureListener listener) {
4142        mPictureListener = listener;
4143    }
4144
4145    /* FIXME: Debug only! Remove for SDK! */
4146    public void externalRepresentation(Message callback) {
4147        mWebViewCore.sendMessage(EventHub.REQUEST_EXT_REPRESENTATION, callback);
4148    }
4149
4150    /* FIXME: Debug only! Remove for SDK! */
4151    public void documentAsText(Message callback) {
4152        mWebViewCore.sendMessage(EventHub.REQUEST_DOC_AS_TEXT, callback);
4153    }
4154
4155    /**
4156     * See {@link WebView#addJavascriptInterface(Object, String)}
4157     */
4158    @Override
4159    public void addJavascriptInterface(Object object, String name) {
4160
4161        if (object == null) {
4162            return;
4163        }
4164        WebViewCore.JSInterfaceData arg = new WebViewCore.JSInterfaceData();
4165
4166        arg.mObject = object;
4167        arg.mInterfaceName = name;
4168
4169        // starting with JELLY_BEAN_MR1, annotations are mandatory for enabling access to
4170        // methods that are accessible from JS.
4171        if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
4172            arg.mRequireAnnotation = true;
4173        } else {
4174            arg.mRequireAnnotation = false;
4175        }
4176        mWebViewCore.sendMessage(EventHub.ADD_JS_INTERFACE, arg);
4177    }
4178
4179    /**
4180     * See {@link WebView#removeJavascriptInterface(String)}
4181     */
4182    @Override
4183    public void removeJavascriptInterface(String interfaceName) {
4184        if (mWebViewCore != null) {
4185            WebViewCore.JSInterfaceData arg = new WebViewCore.JSInterfaceData();
4186            arg.mInterfaceName = interfaceName;
4187            mWebViewCore.sendMessage(EventHub.REMOVE_JS_INTERFACE, arg);
4188        }
4189    }
4190
4191    /**
4192     * See {@link WebView#getSettings()}
4193     * Note this returns WebSettingsClassic, a sub-class of WebSettings, which can be used
4194     * to access extension APIs.
4195     */
4196    @Override
4197    public WebSettingsClassic getSettings() {
4198        return (mWebViewCore != null) ? mWebViewCore.getSettings() : null;
4199    }
4200
4201    /**
4202     * See {@link WebView#getPluginList()}
4203     */
4204    @Deprecated
4205    public static synchronized PluginList getPluginList() {
4206        return new PluginList();
4207    }
4208
4209    /**
4210     * See {@link WebView#refreshPlugins(boolean)}
4211     */
4212    @Deprecated
4213    public void refreshPlugins(boolean reloadOpenPages) {
4214    }
4215
4216    //-------------------------------------------------------------------------
4217    // Override View methods
4218    //-------------------------------------------------------------------------
4219
4220    @Override
4221    protected void finalize() throws Throwable {
4222        try {
4223            destroy();
4224        } finally {
4225            super.finalize();
4226        }
4227    }
4228
4229    private void drawContent(Canvas canvas) {
4230        if (mDrawHistory) {
4231            canvas.scale(mZoomManager.getScale(), mZoomManager.getScale());
4232            canvas.drawPicture(mHistoryPicture);
4233            return;
4234        }
4235        if (mNativeClass == 0) return;
4236
4237        boolean animateZoom = mZoomManager.isFixedLengthAnimationInProgress();
4238        boolean animateScroll = ((!mScroller.isFinished()
4239                || mVelocityTracker != null)
4240                && (mTouchMode != TOUCH_DRAG_MODE ||
4241                mHeldMotionless != MOTIONLESS_TRUE));
4242        if (mTouchMode == TOUCH_DRAG_MODE) {
4243            if (mHeldMotionless == MOTIONLESS_PENDING) {
4244                mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
4245                mHeldMotionless = MOTIONLESS_FALSE;
4246            }
4247            if (mHeldMotionless == MOTIONLESS_FALSE) {
4248                mPrivateHandler.sendMessageDelayed(mPrivateHandler
4249                        .obtainMessage(DRAG_HELD_MOTIONLESS), MOTIONLESS_TIME);
4250                mHeldMotionless = MOTIONLESS_PENDING;
4251            }
4252        }
4253        int saveCount = canvas.save();
4254        if (animateZoom) {
4255            mZoomManager.animateZoom(canvas);
4256        } else if (!canvas.isHardwareAccelerated()) {
4257            canvas.scale(mZoomManager.getScale(), mZoomManager.getScale());
4258        }
4259
4260        boolean UIAnimationsRunning = false;
4261        // Currently for each draw we compute the animation values;
4262        // We may in the future decide to do that independently.
4263        if (mNativeClass != 0 && !canvas.isHardwareAccelerated()
4264                && nativeEvaluateLayersAnimations(mNativeClass)) {
4265            UIAnimationsRunning = true;
4266            // If we have unfinished (or unstarted) animations,
4267            // we ask for a repaint. We only need to do this in software
4268            // rendering (with hardware rendering we already have a different
4269            // method of requesting a repaint)
4270            mWebViewCore.sendMessage(EventHub.NOTIFY_ANIMATION_STARTED);
4271            invalidate();
4272        }
4273
4274        // decide which adornments to draw
4275        int extras = DRAW_EXTRAS_NONE;
4276        if (!mFindIsUp && mShowTextSelectionExtra) {
4277            extras = DRAW_EXTRAS_SELECTION;
4278        }
4279
4280        calcOurContentVisibleRectF(mVisibleContentRect);
4281        if (canvas.isHardwareAccelerated()) {
4282            Rect invScreenRect = mIsWebViewVisible ? mInvScreenRect : null;
4283            Rect screenRect = mIsWebViewVisible ? mScreenRect : null;
4284
4285            int functor = nativeCreateDrawGLFunction(mNativeClass, invScreenRect,
4286                    screenRect, mVisibleContentRect, getScale(), extras);
4287            ((HardwareCanvas) canvas).callDrawGLFunction(functor);
4288            if (mHardwareAccelSkia != getSettings().getHardwareAccelSkiaEnabled()) {
4289                mHardwareAccelSkia = getSettings().getHardwareAccelSkiaEnabled();
4290                nativeUseHardwareAccelSkia(mHardwareAccelSkia);
4291            }
4292
4293        } else {
4294            DrawFilter df = null;
4295            if (mZoomManager.isZoomAnimating() || UIAnimationsRunning) {
4296                df = mZoomFilter;
4297            } else if (animateScroll) {
4298                df = mScrollFilter;
4299            }
4300            canvas.setDrawFilter(df);
4301            nativeDraw(canvas, mVisibleContentRect, mBackgroundColor, extras);
4302            canvas.setDrawFilter(null);
4303        }
4304
4305        canvas.restoreToCount(saveCount);
4306        drawTextSelectionHandles(canvas);
4307
4308        if (extras == DRAW_EXTRAS_CURSOR_RING) {
4309            if (mTouchMode == TOUCH_SHORTPRESS_START_MODE) {
4310                mTouchMode = TOUCH_SHORTPRESS_MODE;
4311            }
4312        }
4313    }
4314
4315    /**
4316     * Draw the background when beyond bounds
4317     * @param canvas Canvas to draw into
4318     */
4319    private void drawOverScrollBackground(Canvas canvas) {
4320        if (mOverScrollBackground == null) {
4321            mOverScrollBackground = new Paint();
4322            Bitmap bm = BitmapFactory.decodeResource(
4323                    mContext.getResources(),
4324                    com.android.internal.R.drawable.status_bar_background);
4325            mOverScrollBackground.setShader(new BitmapShader(bm,
4326                    Shader.TileMode.REPEAT, Shader.TileMode.REPEAT));
4327            mOverScrollBorder = new Paint();
4328            mOverScrollBorder.setStyle(Paint.Style.STROKE);
4329            mOverScrollBorder.setStrokeWidth(0);
4330            mOverScrollBorder.setColor(0xffbbbbbb);
4331        }
4332
4333        int top = 0;
4334        int right = computeRealHorizontalScrollRange();
4335        int bottom = top + computeRealVerticalScrollRange();
4336        // first draw the background and anchor to the top of the view
4337        canvas.save();
4338        canvas.translate(getScrollX(), getScrollY());
4339        canvas.clipRect(-getScrollX(), top - getScrollY(), right - getScrollX(), bottom
4340                - getScrollY(), Region.Op.DIFFERENCE);
4341        canvas.drawPaint(mOverScrollBackground);
4342        canvas.restore();
4343        // then draw the border
4344        canvas.drawRect(-1, top - 1, right, bottom, mOverScrollBorder);
4345        // next clip the region for the content
4346        canvas.clipRect(0, top, right, bottom);
4347    }
4348
4349    @Override
4350    public void onDraw(Canvas canvas) {
4351        if (inFullScreenMode()) {
4352            return; // no need to draw anything if we aren't visible.
4353        }
4354        // if mNativeClass is 0, the WebView is either destroyed or not
4355        // initialized. In either case, just draw the background color and return
4356        if (mNativeClass == 0) {
4357            canvas.drawColor(mBackgroundColor);
4358            return;
4359        }
4360
4361        // if both mContentWidth and mContentHeight are 0, it means there is no
4362        // valid Picture passed to WebView yet. This can happen when WebView
4363        // just starts. Draw the background and return.
4364        if ((mContentWidth | mContentHeight) == 0 && mHistoryPicture == null) {
4365            canvas.drawColor(mBackgroundColor);
4366            return;
4367        }
4368
4369        if (canvas.isHardwareAccelerated()) {
4370            mZoomManager.setHardwareAccelerated();
4371        } else {
4372            mWebViewCore.resumeWebKitDraw();
4373        }
4374
4375        int saveCount = canvas.save();
4376        if (mInOverScrollMode && !getSettings()
4377                .getUseWebViewBackgroundForOverscrollBackground()) {
4378            drawOverScrollBackground(canvas);
4379        }
4380
4381        canvas.translate(0, getTitleHeight());
4382        drawContent(canvas);
4383        canvas.restoreToCount(saveCount);
4384
4385        if (AUTO_REDRAW_HACK && mAutoRedraw) {
4386            invalidate();
4387        }
4388        mWebViewCore.signalRepaintDone();
4389
4390        if (mOverScrollGlow != null && mOverScrollGlow.drawEdgeGlows(canvas)) {
4391            invalidate();
4392        }
4393
4394        if (mFocusTransition != null) {
4395            mFocusTransition.draw(canvas);
4396        } else if (shouldDrawHighlightRect()) {
4397            RegionIterator iter = new RegionIterator(mTouchHighlightRegion);
4398            Rect r = new Rect();
4399            while (iter.next(r)) {
4400                canvas.drawRect(r, mTouchHightlightPaint);
4401            }
4402        }
4403        if (DEBUG_TOUCH_HIGHLIGHT) {
4404            if (getSettings().getNavDump()) {
4405                if ((mTouchHighlightX | mTouchHighlightY) != 0) {
4406                    if (mTouchCrossHairColor == null) {
4407                        mTouchCrossHairColor = new Paint();
4408                        mTouchCrossHairColor.setColor(Color.RED);
4409                    }
4410                    canvas.drawLine(mTouchHighlightX - mNavSlop,
4411                            mTouchHighlightY - mNavSlop, mTouchHighlightX
4412                                    + mNavSlop + 1, mTouchHighlightY + mNavSlop
4413                                    + 1, mTouchCrossHairColor);
4414                    canvas.drawLine(mTouchHighlightX + mNavSlop + 1,
4415                            mTouchHighlightY - mNavSlop, mTouchHighlightX
4416                                    - mNavSlop,
4417                            mTouchHighlightY + mNavSlop + 1,
4418                            mTouchCrossHairColor);
4419                }
4420            }
4421        }
4422    }
4423
4424    private void removeTouchHighlight() {
4425        setTouchHighlightRects(null);
4426    }
4427
4428    @Override
4429    public void setLayoutParams(ViewGroup.LayoutParams params) {
4430        if (params.height == AbsoluteLayout.LayoutParams.WRAP_CONTENT) {
4431            mWrapContent = true;
4432        }
4433        mWebViewPrivate.super_setLayoutParams(params);
4434    }
4435
4436    @Override
4437    public boolean performLongClick() {
4438        // performLongClick() is the result of a delayed message. If we switch
4439        // to windows overview, the WebView will be temporarily removed from the
4440        // view system. In that case, do nothing.
4441        if (mWebView.getParent() == null) return false;
4442
4443        // A multi-finger gesture can look like a long press; make sure we don't take
4444        // long press actions if we're scaling.
4445        final ScaleGestureDetector detector = mZoomManager.getScaleGestureDetector();
4446        if (detector != null && detector.isInProgress()) {
4447            return false;
4448        }
4449
4450        if (mSelectingText) return false; // long click does nothing on selection
4451        /* if long click brings up a context menu, the super function
4452         * returns true and we're done. Otherwise, nothing happened when
4453         * the user clicked. */
4454        if (mWebViewPrivate.super_performLongClick()) {
4455            return true;
4456        }
4457        /* In the case where the application hasn't already handled the long
4458         * click action, look for a word under the  click. If one is found,
4459         * animate the text selection into view.
4460         * FIXME: no animation code yet */
4461        final boolean isSelecting = selectText();
4462        if (isSelecting) {
4463            mWebView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4464        } else if (focusCandidateIsEditableText()) {
4465            mSelectCallback = new SelectActionModeCallback();
4466            mSelectCallback.setWebView(this);
4467            mSelectCallback.setTextSelected(false);
4468            mWebView.startActionMode(mSelectCallback);
4469        }
4470        return isSelecting;
4471    }
4472
4473    /**
4474     * Select the word at the last click point.
4475     *
4476     * This is an implementation detail.
4477     */
4478    public boolean selectText() {
4479        int x = viewToContentX(mLastTouchX + getScrollX());
4480        int y = viewToContentY(mLastTouchY + getScrollY());
4481        return selectText(x, y);
4482    }
4483
4484    /**
4485     * Select the word at the indicated content coordinates.
4486     */
4487    boolean selectText(int x, int y) {
4488        if (mWebViewCore == null) {
4489            return false;
4490        }
4491        mWebViewCore.sendMessage(EventHub.SELECT_WORD_AT, x, y);
4492        return true;
4493    }
4494
4495    private int mOrientation = Configuration.ORIENTATION_UNDEFINED;
4496
4497    @Override
4498    public void onConfigurationChanged(Configuration newConfig) {
4499        mCachedOverlappingActionModeHeight = -1;
4500        if (mSelectingText && mOrientation != newConfig.orientation) {
4501            selectionDone();
4502        }
4503        mOrientation = newConfig.orientation;
4504        if (mWebViewCore != null && !mBlockWebkitViewMessages) {
4505            mWebViewCore.sendMessage(EventHub.CLEAR_CONTENT);
4506        }
4507    }
4508
4509    /**
4510     * Keep track of the Callback so we can end its ActionMode or remove its
4511     * titlebar.
4512     */
4513    private SelectActionModeCallback mSelectCallback;
4514
4515    void setBaseLayer(int layer, boolean showVisualIndicator,
4516            boolean isPictureAfterFirstLayout) {
4517        if (mNativeClass == 0)
4518            return;
4519        boolean queueFull;
4520        final int scrollingLayer = (mTouchMode == TOUCH_DRAG_LAYER_MODE)
4521                ? mCurrentScrollingLayerId : 0;
4522        queueFull = nativeSetBaseLayer(mNativeClass, layer,
4523                                       showVisualIndicator, isPictureAfterFirstLayout,
4524                                       scrollingLayer);
4525
4526        if (queueFull) {
4527            mWebViewCore.pauseWebKitDraw();
4528        } else {
4529            mWebViewCore.resumeWebKitDraw();
4530        }
4531
4532        if (mHTML5VideoViewProxy != null) {
4533            mHTML5VideoViewProxy.setBaseLayer(layer);
4534        }
4535    }
4536
4537    int getBaseLayer() {
4538        if (mNativeClass == 0) {
4539            return 0;
4540        }
4541        return nativeGetBaseLayer(mNativeClass);
4542    }
4543
4544    private void onZoomAnimationStart() {
4545    }
4546
4547    private void onZoomAnimationEnd() {
4548        mPrivateHandler.sendEmptyMessage(RELOCATE_AUTO_COMPLETE_POPUP);
4549    }
4550
4551    void onFixedLengthZoomAnimationStart() {
4552        WebViewCore.pauseUpdatePicture(getWebViewCore());
4553        onZoomAnimationStart();
4554    }
4555
4556    void onFixedLengthZoomAnimationEnd() {
4557        if (!mBlockWebkitViewMessages && !mSelectingText) {
4558            WebViewCore.resumeUpdatePicture(mWebViewCore);
4559        }
4560        onZoomAnimationEnd();
4561    }
4562
4563    private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG |
4564                                         Paint.DITHER_FLAG |
4565                                         Paint.SUBPIXEL_TEXT_FLAG;
4566    private static final int SCROLL_BITS = Paint.FILTER_BITMAP_FLAG |
4567                                           Paint.DITHER_FLAG;
4568
4569    private final DrawFilter mZoomFilter =
4570            new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG);
4571    // If we need to trade better quality for speed, set mScrollFilter to null
4572    private final DrawFilter mScrollFilter =
4573            new PaintFlagsDrawFilter(SCROLL_BITS, 0);
4574
4575    private class SelectionHandleAlpha {
4576        private int mAlpha = 0;
4577        private int mTargetAlpha = 0;
4578
4579        public void setAlpha(int alpha) {
4580            mAlpha = alpha;
4581            // TODO: Use partial invalidate
4582            invalidate();
4583        }
4584
4585        public int getAlpha() {
4586            return mAlpha;
4587        }
4588
4589        public void setTargetAlpha(int alpha) {
4590            mTargetAlpha = alpha;
4591        }
4592
4593        public int getTargetAlpha() {
4594            return mTargetAlpha;
4595        }
4596
4597    }
4598
4599    private void startSelectingText() {
4600        mSelectingText = true;
4601        mShowTextSelectionExtra = true;
4602        animateHandles();
4603    }
4604
4605    private void animateHandle(boolean canShow, ObjectAnimator animator,
4606            Point selectionPoint, int selectionLayerId,
4607            SelectionHandleAlpha alpha) {
4608        boolean isVisible = canShow && mSelectingText
4609                && ((mSelectionStarted && mSelectDraggingCursor == selectionPoint)
4610                || isHandleVisible(selectionPoint, selectionLayerId));
4611        int targetValue = isVisible ? 255 : 0;
4612        if (targetValue != alpha.getTargetAlpha()) {
4613            alpha.setTargetAlpha(targetValue);
4614            animator.setIntValues(targetValue);
4615            animator.setDuration(SELECTION_HANDLE_ANIMATION_MS);
4616            animator.start();
4617        }
4618    }
4619
4620    private void animateHandles() {
4621        boolean canShowBase = mSelectingText;
4622        boolean canShowExtent = mSelectingText && !mIsCaretSelection;
4623        animateHandle(canShowBase, mBaseHandleAlphaAnimator, mSelectCursorBase,
4624                mSelectCursorBaseLayerId, mBaseAlpha);
4625        animateHandle(canShowExtent, mExtentHandleAlphaAnimator,
4626                mSelectCursorExtent, mSelectCursorExtentLayerId,
4627                mExtentAlpha);
4628    }
4629
4630    private void endSelectingText() {
4631        mSelectingText = false;
4632        mShowTextSelectionExtra = false;
4633        animateHandles();
4634    }
4635
4636    private void ensureSelectionHandles() {
4637        if (mSelectHandleCenter == null) {
4638            mSelectHandleCenter = mContext.getResources().getDrawable(
4639                    com.android.internal.R.drawable.text_select_handle_middle).mutate();
4640            mSelectHandleLeft = mContext.getResources().getDrawable(
4641                    com.android.internal.R.drawable.text_select_handle_left).mutate();
4642            mSelectHandleRight = mContext.getResources().getDrawable(
4643                    com.android.internal.R.drawable.text_select_handle_right).mutate();
4644            // All handles have the same height, so we can save effort with
4645            // this assumption.
4646            mSelectOffset = new Point(0,
4647                    -mSelectHandleLeft.getIntrinsicHeight());
4648        }
4649    }
4650
4651    private void drawHandle(Point point, int handleId, Rect bounds,
4652            int alpha, Canvas canvas) {
4653        int offset;
4654        int width;
4655        int height;
4656        Drawable drawable;
4657        boolean isLeft = nativeIsHandleLeft(mNativeClass, handleId);
4658        if (isLeft) {
4659            drawable = mSelectHandleLeft;
4660            width = mSelectHandleLeft.getIntrinsicWidth();
4661            height = mSelectHandleLeft.getIntrinsicHeight();
4662            // Magic formula copied from TextView
4663            offset = (width * 3) / 4;
4664        } else {
4665            drawable = mSelectHandleRight;
4666            width = mSelectHandleRight.getIntrinsicWidth();
4667            height = mSelectHandleRight.getIntrinsicHeight();
4668            // Magic formula copied from TextView
4669            offset = width / 4;
4670        }
4671        int x = contentToViewDimension(point.x);
4672        int y = contentToViewDimension(point.y);
4673        bounds.set(x - offset, y, x - offset + width, y + height);
4674        drawable.setBounds(bounds);
4675        drawable.setAlpha(alpha);
4676        drawable.draw(canvas);
4677    }
4678
4679    private void drawTextSelectionHandles(Canvas canvas) {
4680        if (mBaseAlpha.getAlpha() == 0 && mExtentAlpha.getAlpha() == 0) {
4681            return;
4682        }
4683        ensureSelectionHandles();
4684        if (mIsCaretSelection) {
4685            // Caret handle is centered
4686            int x = contentToViewDimension(mSelectCursorBase.x) -
4687                    (mSelectHandleCenter.getIntrinsicWidth() / 2);
4688            int y = contentToViewDimension(mSelectCursorBase.y);
4689            mSelectHandleBaseBounds.set(x, y,
4690                    x + mSelectHandleCenter.getIntrinsicWidth(),
4691                    y + mSelectHandleCenter.getIntrinsicHeight());
4692            mSelectHandleCenter.setBounds(mSelectHandleBaseBounds);
4693            mSelectHandleCenter.setAlpha(mBaseAlpha.getAlpha());
4694            mSelectHandleCenter.draw(canvas);
4695        } else {
4696            drawHandle(mSelectCursorBase, HANDLE_ID_BASE,
4697                    mSelectHandleBaseBounds, mBaseAlpha.getAlpha(), canvas);
4698            drawHandle(mSelectCursorExtent, HANDLE_ID_EXTENT,
4699                    mSelectHandleExtentBounds, mExtentAlpha.getAlpha(), canvas);
4700        }
4701    }
4702
4703    private boolean isHandleVisible(Point selectionPoint, int layerId) {
4704        boolean isVisible = true;
4705        if (mIsEditingText) {
4706            isVisible = mEditTextContentBounds.contains(selectionPoint.x,
4707                    selectionPoint.y);
4708        }
4709        if (isVisible) {
4710            isVisible = nativeIsPointVisible(mNativeClass, layerId,
4711                    selectionPoint.x, selectionPoint.y);
4712        }
4713        return isVisible;
4714    }
4715
4716    /**
4717     * Takes an int[4] array as an output param with the values being
4718     * startX, startY, endX, endY
4719     */
4720    private void getSelectionHandles(int[] handles) {
4721        handles[0] = mSelectCursorBase.x;
4722        handles[1] = mSelectCursorBase.y;
4723        handles[2] = mSelectCursorExtent.x;
4724        handles[3] = mSelectCursorExtent.y;
4725    }
4726
4727    // draw history
4728    private boolean mDrawHistory = false;
4729    private Picture mHistoryPicture = null;
4730    private int mHistoryWidth = 0;
4731    private int mHistoryHeight = 0;
4732
4733    // Only check the flag, can be called from WebCore thread
4734    boolean drawHistory() {
4735        return mDrawHistory;
4736    }
4737
4738    int getHistoryPictureWidth() {
4739        return (mHistoryPicture != null) ? mHistoryPicture.getWidth() : 0;
4740    }
4741
4742    // Should only be called in UI thread
4743    void switchOutDrawHistory() {
4744        if (null == mWebViewCore) return; // CallbackProxy may trigger this
4745        if (mDrawHistory && (getProgress() == 100 || nativeHasContent())) {
4746            mDrawHistory = false;
4747            mHistoryPicture = null;
4748            invalidate();
4749            int oldScrollX = getScrollX();
4750            int oldScrollY = getScrollY();
4751            setScrollXRaw(pinLocX(getScrollX()));
4752            setScrollYRaw(pinLocY(getScrollY()));
4753            if (oldScrollX != getScrollX() || oldScrollY != getScrollY()) {
4754                mWebViewPrivate.onScrollChanged(getScrollX(), getScrollY(), oldScrollX, oldScrollY);
4755            } else {
4756                sendOurVisibleRect();
4757            }
4758        }
4759    }
4760
4761    /**
4762     *  Delete text from start to end in the focused textfield. If there is no
4763     *  focus, or if start == end, silently fail.  If start and end are out of
4764     *  order, swap them.
4765     *  @param  start   Beginning of selection to delete.
4766     *  @param  end     End of selection to delete.
4767     */
4768    /* package */ void deleteSelection(int start, int end) {
4769        mTextGeneration++;
4770        WebViewCore.TextSelectionData data
4771                = new WebViewCore.TextSelectionData(start, end, 0);
4772        mWebViewCore.sendMessage(EventHub.DELETE_SELECTION, mTextGeneration, 0,
4773                data);
4774    }
4775
4776    /**
4777     *  Set the selection to (start, end) in the focused textfield. If start and
4778     *  end are out of order, swap them.
4779     *  @param  start   Beginning of selection.
4780     *  @param  end     End of selection.
4781     */
4782    /* package */ void setSelection(int start, int end) {
4783        if (mWebViewCore != null) {
4784            mWebViewCore.sendMessage(EventHub.SET_SELECTION, start, end);
4785        }
4786    }
4787
4788    @Override
4789    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4790        if (mInputConnection == null) {
4791            mInputConnection = new WebViewInputConnection();
4792            mAutoCompletePopup = new AutoCompletePopup(this, mInputConnection);
4793        }
4794        mInputConnection.setupEditorInfo(outAttrs);
4795        return mInputConnection;
4796    }
4797
4798    private void relocateAutoCompletePopup() {
4799        if (mAutoCompletePopup != null) {
4800            mAutoCompletePopup.resetRect();
4801            mAutoCompletePopup.setText(mInputConnection.getEditable());
4802        }
4803    }
4804
4805    /**
4806     * Called in response to a message from webkit telling us that the soft
4807     * keyboard should be launched.
4808     */
4809    private void displaySoftKeyboard(boolean isTextView) {
4810        InputMethodManager imm = (InputMethodManager)
4811                mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
4812
4813        // bring it back to the default level scale so that user can enter text
4814        boolean zoom = mZoomManager.getScale() < mZoomManager.getDefaultScale();
4815        if (zoom) {
4816            mZoomManager.setZoomCenter(mLastTouchX, mLastTouchY);
4817            mZoomManager.setZoomScale(mZoomManager.getDefaultScale(), false);
4818        }
4819        // Used by plugins and contentEditable.
4820        // Also used if the navigation cache is out of date, and
4821        // does not recognize that a textfield is in focus.  In that
4822        // case, use WebView as the targeted view.
4823        // see http://b/issue?id=2457459
4824        imm.showSoftInput(mWebView, 0);
4825    }
4826
4827    // Called by WebKit to instruct the UI to hide the keyboard
4828    private void hideSoftKeyboard() {
4829        InputMethodManager imm = InputMethodManager.peekInstance();
4830        if (imm != null && (imm.isActive(mWebView))) {
4831            imm.hideSoftInputFromWindow(mWebView.getWindowToken(), 0);
4832        }
4833    }
4834
4835    /**
4836     * Called by AutoCompletePopup to find saved form data associated with the
4837     * textfield
4838     * @param name Name of the textfield.
4839     * @param nodePointer Pointer to the node of the textfield, so it can be
4840     *          compared to the currently focused textfield when the data is
4841     *          retrieved.
4842     * @param autoFillable true if WebKit has determined this field is part of
4843     *          a form that can be auto filled.
4844     * @param autoComplete true if the attribute "autocomplete" is set to true
4845     *          on the textfield.
4846     */
4847    /* package */ void requestFormData(String name, int nodePointer,
4848            boolean autoFillable, boolean autoComplete) {
4849        if (mWebViewCore.getSettings().getSaveFormData()) {
4850            Message update = mPrivateHandler.obtainMessage(REQUEST_FORM_DATA);
4851            update.arg1 = nodePointer;
4852            RequestFormData updater = new RequestFormData(name, getUrl(),
4853                    update, autoFillable, autoComplete);
4854            Thread t = new Thread(updater);
4855            t.start();
4856        }
4857    }
4858
4859    /*
4860     * This class requests an Adapter for the AutoCompletePopup which shows past
4861     * entries stored in the database.  It is a Runnable so that it can be done
4862     * in its own thread, without slowing down the UI.
4863     */
4864    private class RequestFormData implements Runnable {
4865        private String mName;
4866        private String mUrl;
4867        private Message mUpdateMessage;
4868        private boolean mAutoFillable;
4869        private boolean mAutoComplete;
4870        private WebSettingsClassic mWebSettings;
4871
4872        public RequestFormData(String name, String url, Message msg,
4873                boolean autoFillable, boolean autoComplete) {
4874            mName = name;
4875            mUrl = WebTextView.urlForAutoCompleteData(url);
4876            mUpdateMessage = msg;
4877            mAutoFillable = autoFillable;
4878            mAutoComplete = autoComplete;
4879            mWebSettings = getSettings();
4880        }
4881
4882        @Override
4883        public void run() {
4884            ArrayList<String> pastEntries = new ArrayList<String>();
4885
4886            if (mAutoFillable) {
4887                // Note that code inside the adapter click handler in AutoCompletePopup depends
4888                // on the AutoFill item being at the top of the drop down list. If you change
4889                // the order, make sure to do it there too!
4890                if (mWebSettings != null && mWebSettings.getAutoFillProfile() != null) {
4891                    pastEntries.add(mWebView.getResources().getText(
4892                            com.android.internal.R.string.autofill_this_form).toString() +
4893                            " " +
4894                    mAutoFillData.getPreviewString());
4895                    mAutoCompletePopup.setIsAutoFillProfileSet(true);
4896                } else {
4897                    // There is no autofill profile set up yet, so add an option that
4898                    // will invite the user to set their profile up.
4899                    pastEntries.add(mWebView.getResources().getText(
4900                            com.android.internal.R.string.setup_autofill).toString());
4901                    mAutoCompletePopup.setIsAutoFillProfileSet(false);
4902                }
4903            }
4904
4905            if (mAutoComplete) {
4906                pastEntries.addAll(mDatabase.getFormData(mUrl, mName));
4907            }
4908
4909            if (pastEntries.size() > 0) {
4910                ArrayAdapter<String> adapter = new ArrayAdapter<String>(
4911                        mContext,
4912                        com.android.internal.R.layout.web_text_view_dropdown,
4913                        pastEntries);
4914                mUpdateMessage.obj = adapter;
4915                mUpdateMessage.sendToTarget();
4916            }
4917        }
4918    }
4919
4920    /**
4921     * Dump the display tree to "/sdcard/displayTree.txt"
4922     *
4923     * debug only
4924     */
4925    public void dumpDisplayTree() {
4926        nativeDumpDisplayTree(getUrl());
4927    }
4928
4929    /**
4930     * Dump the dom tree to adb shell if "toFile" is False, otherwise dump it to
4931     * "/sdcard/domTree.txt"
4932     *
4933     * debug only
4934     */
4935    public void dumpDomTree(boolean toFile) {
4936        mWebViewCore.sendMessage(EventHub.DUMP_DOMTREE, toFile ? 1 : 0, 0);
4937    }
4938
4939    /**
4940     * Dump the render tree to adb shell if "toFile" is False, otherwise dump it
4941     * to "/sdcard/renderTree.txt"
4942     *
4943     * debug only
4944     */
4945    public void dumpRenderTree(boolean toFile) {
4946        mWebViewCore.sendMessage(EventHub.DUMP_RENDERTREE, toFile ? 1 : 0, 0);
4947    }
4948
4949    /**
4950     * Called by DRT on UI thread, need to proxy to WebCore thread.
4951     *
4952     * debug only
4953     */
4954    public void setUseMockDeviceOrientation() {
4955        mWebViewCore.sendMessage(EventHub.SET_USE_MOCK_DEVICE_ORIENTATION);
4956    }
4957
4958    /**
4959     * Sets use of the Geolocation mock client. Also resets that client. Called
4960     * by DRT on UI thread, need to proxy to WebCore thread.
4961     *
4962     * debug only
4963     */
4964    public void setUseMockGeolocation() {
4965        mWebViewCore.sendMessage(EventHub.SET_USE_MOCK_GEOLOCATION);
4966    }
4967
4968    /**
4969     * Called by DRT on WebCore thread.
4970     *
4971     * debug only
4972     */
4973    public void setMockGeolocationPosition(double latitude, double longitude, double accuracy) {
4974        mWebViewCore.setMockGeolocationPosition(latitude, longitude, accuracy);
4975    }
4976
4977    /**
4978     * Called by DRT on WebCore thread.
4979     *
4980     * debug only
4981     */
4982    public void setMockGeolocationError(int code, String message) {
4983        mWebViewCore.setMockGeolocationError(code, message);
4984    }
4985
4986    /**
4987     * Called by DRT on WebCore thread.
4988     *
4989     * debug only
4990     */
4991    public void setMockGeolocationPermission(boolean allow) {
4992        mWebViewCore.setMockGeolocationPermission(allow);
4993    }
4994
4995    /**
4996     * Called by DRT on WebCore thread.
4997     *
4998     * debug only
4999     */
5000    public void setMockDeviceOrientation(boolean canProvideAlpha, double alpha,
5001            boolean canProvideBeta, double beta, boolean canProvideGamma, double gamma) {
5002        mWebViewCore.setMockDeviceOrientation(canProvideAlpha, alpha, canProvideBeta, beta,
5003                canProvideGamma, gamma);
5004    }
5005
5006    // This is used to determine long press with the center key.  Does not
5007    // affect long press with the trackball/touch.
5008    private boolean mGotCenterDown = false;
5009
5010    @Override
5011    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
5012        if (mBlockWebkitViewMessages) {
5013            return false;
5014        }
5015        // send complex characters to webkit for use by JS and plugins
5016        if (keyCode == KeyEvent.KEYCODE_UNKNOWN && event.getCharacters() != null) {
5017            // pass the key to DOM
5018            sendBatchableInputMessage(EventHub.KEY_DOWN, 0, 0, event);
5019            sendBatchableInputMessage(EventHub.KEY_UP, 0, 0, event);
5020            // return true as DOM handles the key
5021            return true;
5022        }
5023        return false;
5024    }
5025
5026    private boolean isEnterActionKey(int keyCode) {
5027        return keyCode == KeyEvent.KEYCODE_DPAD_CENTER
5028                || keyCode == KeyEvent.KEYCODE_ENTER
5029                || keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER;
5030    }
5031
5032    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
5033        if (mAutoCompletePopup != null) {
5034            return mAutoCompletePopup.onKeyPreIme(keyCode, event);
5035        }
5036        return false;
5037    }
5038
5039    @Override
5040    public boolean onKeyDown(int keyCode, KeyEvent event) {
5041        if (DebugFlags.WEB_VIEW) {
5042            Log.v(LOGTAG, "keyDown at " + System.currentTimeMillis()
5043                    + "keyCode=" + keyCode
5044                    + ", " + event + ", unicode=" + event.getUnicodeChar());
5045        }
5046        if (mIsCaretSelection) {
5047            selectionDone();
5048        }
5049        if (mBlockWebkitViewMessages) {
5050            return false;
5051        }
5052
5053        // don't implement accelerator keys here; defer to host application
5054        if (event.isCtrlPressed()) {
5055            return false;
5056        }
5057
5058        if (mNativeClass == 0) {
5059            return false;
5060        }
5061
5062        // do this hack up front, so it always works, regardless of touch-mode
5063        if (AUTO_REDRAW_HACK && (keyCode == KeyEvent.KEYCODE_CALL)) {
5064            mAutoRedraw = !mAutoRedraw;
5065            if (mAutoRedraw) {
5066                invalidate();
5067            }
5068            return true;
5069        }
5070
5071        // Bubble up the key event if
5072        // 1. it is a system key; or
5073        // 2. the host application wants to handle it;
5074        if (event.isSystem()
5075                || mCallbackProxy.uiOverrideKeyEvent(event)) {
5076            return false;
5077        }
5078
5079        // See if the accessibility injector needs to handle this event.
5080        if (isAccessibilityInjectionEnabled()
5081                && getAccessibilityInjector().handleKeyEventIfNecessary(event)) {
5082            return true;
5083        }
5084
5085        if (keyCode == KeyEvent.KEYCODE_PAGE_UP) {
5086            if (event.hasNoModifiers()) {
5087                pageUp(false);
5088                return true;
5089            } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
5090                pageUp(true);
5091                return true;
5092            }
5093        }
5094
5095        if (keyCode == KeyEvent.KEYCODE_PAGE_DOWN) {
5096            if (event.hasNoModifiers()) {
5097                pageDown(false);
5098                return true;
5099            } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
5100                pageDown(true);
5101                return true;
5102            }
5103        }
5104
5105        if (keyCode == KeyEvent.KEYCODE_MOVE_HOME && event.hasNoModifiers()) {
5106            pageUp(true);
5107            return true;
5108        }
5109
5110        if (keyCode == KeyEvent.KEYCODE_MOVE_END && event.hasNoModifiers()) {
5111            pageDown(true);
5112            return true;
5113        }
5114
5115        if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
5116                && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
5117            switchOutDrawHistory();
5118        }
5119
5120        if (isEnterActionKey(keyCode)) {
5121            switchOutDrawHistory();
5122            if (event.getRepeatCount() == 0) {
5123                if (mSelectingText) {
5124                    return true; // discard press if copy in progress
5125                }
5126                mGotCenterDown = true;
5127                mPrivateHandler.sendMessageDelayed(mPrivateHandler
5128                        .obtainMessage(LONG_PRESS_CENTER), LONG_PRESS_TIMEOUT);
5129            }
5130        }
5131
5132        if (getSettings().getNavDump()) {
5133            switch (keyCode) {
5134                case KeyEvent.KEYCODE_4:
5135                    dumpDisplayTree();
5136                    break;
5137                case KeyEvent.KEYCODE_5:
5138                case KeyEvent.KEYCODE_6:
5139                    dumpDomTree(keyCode == KeyEvent.KEYCODE_5);
5140                    break;
5141                case KeyEvent.KEYCODE_7:
5142                case KeyEvent.KEYCODE_8:
5143                    dumpRenderTree(keyCode == KeyEvent.KEYCODE_7);
5144                    break;
5145            }
5146        }
5147
5148        // pass the key to DOM
5149        sendKeyEvent(event);
5150        // return true as DOM handles the key
5151        return true;
5152    }
5153
5154    @Override
5155    public boolean onKeyUp(int keyCode, KeyEvent event) {
5156        if (DebugFlags.WEB_VIEW) {
5157            Log.v(LOGTAG, "keyUp at " + System.currentTimeMillis()
5158                    + ", " + event + ", unicode=" + event.getUnicodeChar());
5159        }
5160        if (mBlockWebkitViewMessages) {
5161            return false;
5162        }
5163
5164        if (mNativeClass == 0) {
5165            return false;
5166        }
5167
5168        // special CALL handling when cursor node's href is "tel:XXX"
5169        if (keyCode == KeyEvent.KEYCODE_CALL
5170                && mInitialHitTestResult != null
5171                && mInitialHitTestResult.getType() == HitTestResult.PHONE_TYPE) {
5172            String text = mInitialHitTestResult.getExtra();
5173            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(text));
5174            mContext.startActivity(intent);
5175            return true;
5176        }
5177
5178        // Bubble up the key event if
5179        // 1. it is a system key; or
5180        // 2. the host application wants to handle it;
5181        if (event.isSystem()
5182                || mCallbackProxy.uiOverrideKeyEvent(event)) {
5183            return false;
5184        }
5185
5186        // See if the accessibility injector needs to handle this event.
5187        if (isAccessibilityInjectionEnabled()
5188                && getAccessibilityInjector().handleKeyEventIfNecessary(event)) {
5189            return true;
5190        }
5191
5192        if (isEnterActionKey(keyCode)) {
5193            // remove the long press message first
5194            mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
5195            mGotCenterDown = false;
5196
5197            if (mSelectingText) {
5198                copySelection();
5199                selectionDone();
5200                return true; // discard press if copy in progress
5201            }
5202        }
5203
5204        // pass the key to DOM
5205        sendKeyEvent(event);
5206        // return true as DOM handles the key
5207        return true;
5208    }
5209
5210    private boolean startSelectActionMode() {
5211        mSelectCallback = new SelectActionModeCallback();
5212        mSelectCallback.setTextSelected(!mIsCaretSelection);
5213        mSelectCallback.setWebView(this);
5214        if (mWebView.startActionMode(mSelectCallback) == null) {
5215            // There is no ActionMode, so do not allow the user to modify a
5216            // selection.
5217            selectionDone();
5218            return false;
5219        }
5220        mWebView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
5221        return true;
5222    }
5223
5224    private void showPasteWindow() {
5225        ClipboardManager cm = (ClipboardManager)(mContext
5226                .getSystemService(Context.CLIPBOARD_SERVICE));
5227        if (cm.hasPrimaryClip()) {
5228            Point cursorPoint = new Point(contentToViewX(mSelectCursorBase.x),
5229                    contentToViewY(mSelectCursorBase.y));
5230            Point cursorTop = calculateBaseCaretTop();
5231            cursorTop.set(contentToViewX(cursorTop.x),
5232                    contentToViewY(cursorTop.y));
5233
5234            int[] location = new int[2];
5235            mWebView.getLocationInWindow(location);
5236            int offsetX = location[0] - getScrollX();
5237            int offsetY = location[1] - getScrollY();
5238            cursorPoint.offset(offsetX, offsetY);
5239            cursorTop.offset(offsetX, offsetY);
5240            if (mPasteWindow == null) {
5241                mPasteWindow = new PastePopupWindow();
5242            }
5243            mPasteWindow.show(cursorPoint, cursorTop, location[0], location[1]);
5244        }
5245    }
5246
5247    /**
5248     * Given segment AB, this finds the point C along AB that is closest to
5249     * point and then returns it scale along AB. The scale factor is AC/AB.
5250     *
5251     * @param x The x coordinate of the point near segment AB that determines
5252     * the scale factor.
5253     * @param y The y coordinate of the point near segment AB that determines
5254     * the scale factor.
5255     * @param a The first point of the line segment.
5256     * @param b The second point of the line segment.
5257     * @return The scale factor AC/AB, where C is the point on AB closest to
5258     *         point.
5259     */
5260    private static float scaleAlongSegment(int x, int y, PointF a, PointF b) {
5261        // The bottom line of the text box is line AB
5262        float abX = b.x - a.x;
5263        float abY = b.y - a.y;
5264        float ab2 = (abX * abX) + (abY * abY);
5265
5266        // The line from first point in text bounds to bottom is AP
5267        float apX = x - a.x;
5268        float apY = y - a.y;
5269        float abDotAP = (apX * abX) + (apY * abY);
5270        float scale = abDotAP / ab2;
5271        return scale;
5272    }
5273
5274    private Point calculateBaseCaretTop() {
5275        return calculateCaretTop(mSelectCursorBase, mSelectCursorBaseTextQuad);
5276    }
5277
5278    private Point calculateDraggingCaretTop() {
5279        return calculateCaretTop(mSelectDraggingCursor, mSelectDraggingTextQuad);
5280    }
5281
5282    /**
5283     * Assuming arbitrary shape of a quadralateral forming text bounds, this
5284     * calculates the top of a caret.
5285     */
5286    private static Point calculateCaretTop(Point base, QuadF quad) {
5287        float scale = scaleAlongSegment(base.x, base.y, quad.p4, quad.p3);
5288        int x = Math.round(scaleCoordinate(scale, quad.p1.x, quad.p2.x));
5289        int y = Math.round(scaleCoordinate(scale, quad.p1.y, quad.p2.y));
5290        return new Point(x, y);
5291    }
5292
5293    private void hidePasteButton() {
5294        if (mPasteWindow != null) {
5295            mPasteWindow.hide();
5296        }
5297    }
5298
5299    private void syncSelectionCursors() {
5300        mSelectCursorBaseLayerId =
5301                nativeGetHandleLayerId(mNativeClass, HANDLE_ID_BASE,
5302                        mSelectCursorBase, mSelectCursorBaseTextQuad);
5303        mSelectCursorExtentLayerId =
5304                nativeGetHandleLayerId(mNativeClass, HANDLE_ID_EXTENT,
5305                        mSelectCursorExtent, mSelectCursorExtentTextQuad);
5306    }
5307
5308    private boolean setupWebkitSelect() {
5309        syncSelectionCursors();
5310        if (!mIsCaretSelection && !startSelectActionMode()) {
5311            selectionDone();
5312            return false;
5313        }
5314        startSelectingText();
5315        mTouchMode = TOUCH_DRAG_MODE;
5316        return true;
5317    }
5318
5319    private void updateWebkitSelection(boolean isSnapped) {
5320        int handleId = (mSelectDraggingCursor == mSelectCursorBase)
5321                ? HANDLE_ID_BASE : HANDLE_ID_EXTENT;
5322        int x = mSelectDraggingCursor.x;
5323        int y = mSelectDraggingCursor.y;
5324        if (isSnapped) {
5325            // "center" the cursor in the snapping quad
5326            Point top = calculateDraggingCaretTop();
5327            x = Math.round((top.x + x) / 2);
5328            y = Math.round((top.y + y) / 2);
5329        }
5330        mWebViewCore.removeMessages(EventHub.SELECT_TEXT);
5331        mWebViewCore.sendMessageAtFrontOfQueue(EventHub.SELECT_TEXT,
5332                x, y, (Integer)handleId);
5333    }
5334
5335    private void resetCaretTimer() {
5336        mPrivateHandler.removeMessages(CLEAR_CARET_HANDLE);
5337        if (!mSelectionStarted) {
5338            mPrivateHandler.sendEmptyMessageDelayed(CLEAR_CARET_HANDLE,
5339                    CARET_HANDLE_STAMINA_MS);
5340        }
5341    }
5342
5343    /**
5344     * Select all of the text in this WebView.
5345     *
5346     * This is an implementation detail.
5347     */
5348    public void selectAll() {
5349        mWebViewCore.sendMessage(EventHub.SELECT_ALL);
5350    }
5351
5352    /**
5353     * Called when the selection has been removed.
5354     */
5355    void selectionDone() {
5356        if (mSelectingText) {
5357            hidePasteButton();
5358            endSelectingText();
5359            // finish is idempotent, so this is fine even if selectionDone was
5360            // called by mSelectCallback.onDestroyActionMode
5361            if (mSelectCallback != null) {
5362                mSelectCallback.finish();
5363                mSelectCallback = null;
5364            }
5365            invalidate(); // redraw without selection
5366            mAutoScrollX = 0;
5367            mAutoScrollY = 0;
5368            mSentAutoScrollMessage = false;
5369        }
5370    }
5371
5372    /**
5373     * Copy the selection to the clipboard
5374     *
5375     * This is an implementation detail.
5376     */
5377    public boolean copySelection() {
5378        boolean copiedSomething = false;
5379        String selection = getSelection();
5380        if (selection != null && selection != "") {
5381            if (DebugFlags.WEB_VIEW) {
5382                Log.v(LOGTAG, "copySelection \"" + selection + "\"");
5383            }
5384            Toast.makeText(mContext
5385                    , com.android.internal.R.string.text_copied
5386                    , Toast.LENGTH_SHORT).show();
5387            copiedSomething = true;
5388            ClipboardManager cm = (ClipboardManager)mContext
5389                    .getSystemService(Context.CLIPBOARD_SERVICE);
5390            cm.setText(selection);
5391            int[] handles = new int[4];
5392            getSelectionHandles(handles);
5393            mWebViewCore.sendMessage(EventHub.COPY_TEXT, handles);
5394        }
5395        invalidate(); // remove selection region and pointer
5396        return copiedSomething;
5397    }
5398
5399    /**
5400     * Cut the selected text into the clipboard
5401     *
5402     * This is an implementation detail
5403     */
5404    public void cutSelection() {
5405        copySelection();
5406        int[] handles = new int[4];
5407        getSelectionHandles(handles);
5408        mWebViewCore.sendMessage(EventHub.DELETE_TEXT, handles);
5409    }
5410
5411    /**
5412     * Paste text from the clipboard to the cursor position.
5413     *
5414     * This is an implementation detail
5415     */
5416    public void pasteFromClipboard() {
5417        ClipboardManager cm = (ClipboardManager)mContext
5418                .getSystemService(Context.CLIPBOARD_SERVICE);
5419        ClipData clipData = cm.getPrimaryClip();
5420        if (clipData != null) {
5421            ClipData.Item clipItem = clipData.getItemAt(0);
5422            CharSequence pasteText = clipItem.getText();
5423            if (mInputConnection != null) {
5424                mInputConnection.replaceSelection(pasteText);
5425            }
5426        }
5427    }
5428
5429    /**
5430     * Returns the currently highlighted text as a string.
5431     */
5432    String getSelection() {
5433        if (mNativeClass == 0) return "";
5434        return nativeGetSelection();
5435    }
5436
5437    @Override
5438    public void onAttachedToWindow() {
5439        if (mWebView.hasWindowFocus()) setActive(true);
5440
5441        if (isAccessibilityInjectionEnabled()) {
5442            getAccessibilityInjector().toggleAccessibilityFeedback(true);
5443        }
5444
5445        updateHwAccelerated();
5446    }
5447
5448    @Override
5449    public void onDetachedFromWindow() {
5450        clearHelpers();
5451        mZoomManager.dismissZoomPicker();
5452        if (mWebView.hasWindowFocus()) setActive(false);
5453
5454        if (isAccessibilityInjectionEnabled()) {
5455            getAccessibilityInjector().toggleAccessibilityFeedback(false);
5456        }
5457
5458        updateHwAccelerated();
5459
5460        ensureFunctorDetached();
5461    }
5462
5463    @Override
5464    public void onVisibilityChanged(View changedView, int visibility) {
5465        // The zoomManager may be null if the webview is created from XML that
5466        // specifies the view's visibility param as not visible (see http://b/2794841)
5467        if (visibility != View.VISIBLE && mZoomManager != null) {
5468            mZoomManager.dismissZoomPicker();
5469        }
5470        updateDrawingState();
5471    }
5472
5473    void setActive(boolean active) {
5474        if (active) {
5475            if (mWebView.hasFocus()) {
5476                // If our window regained focus, and we have focus, then begin
5477                // drawing the cursor ring
5478                mDrawCursorRing = true;
5479                setFocusControllerActive(true);
5480            } else {
5481                mDrawCursorRing = false;
5482                setFocusControllerActive(false);
5483            }
5484        } else {
5485            if (!mZoomManager.isZoomPickerVisible()) {
5486                /*
5487                 * The external zoom controls come in their own window, so our
5488                 * window loses focus. Our policy is to not draw the cursor ring
5489                 * if our window is not focused, but this is an exception since
5490                 * the user can still navigate the web page with the zoom
5491                 * controls showing.
5492                 */
5493                mDrawCursorRing = false;
5494            }
5495            mKeysPressed.clear();
5496            mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5497            mTouchMode = TOUCH_DONE_MODE;
5498            setFocusControllerActive(false);
5499        }
5500        invalidate();
5501    }
5502
5503    // To avoid drawing the cursor ring, and remove the TextView when our window
5504    // loses focus.
5505    @Override
5506    public void onWindowFocusChanged(boolean hasWindowFocus) {
5507        setActive(hasWindowFocus);
5508        if (hasWindowFocus) {
5509            JWebCoreJavaBridge.setActiveWebView(this);
5510            if (mPictureUpdatePausedForFocusChange) {
5511                WebViewCore.resumeUpdatePicture(mWebViewCore);
5512                mPictureUpdatePausedForFocusChange = false;
5513            }
5514        } else {
5515            JWebCoreJavaBridge.removeActiveWebView(this);
5516            final WebSettings settings = getSettings();
5517            if (settings != null && settings.enableSmoothTransition() &&
5518                    mWebViewCore != null && !WebViewCore.isUpdatePicturePaused(mWebViewCore)) {
5519                WebViewCore.pauseUpdatePicture(mWebViewCore);
5520                mPictureUpdatePausedForFocusChange = true;
5521            }
5522        }
5523    }
5524
5525    /*
5526     * Pass a message to WebCore Thread, telling the WebCore::Page's
5527     * FocusController to be  "inactive" so that it will
5528     * not draw the blinking cursor.  It gets set to "active" to draw the cursor
5529     * in WebViewCore.cpp, when the WebCore thread receives key events/clicks.
5530     */
5531    /* package */ void setFocusControllerActive(boolean active) {
5532        if (mWebViewCore == null) return;
5533        mWebViewCore.sendMessage(EventHub.SET_ACTIVE, active ? 1 : 0, 0);
5534        // Need to send this message after the document regains focus.
5535        if (active && mListBoxMessage != null) {
5536            mWebViewCore.sendMessage(mListBoxMessage);
5537            mListBoxMessage = null;
5538        }
5539    }
5540
5541    @Override
5542    public void onFocusChanged(boolean focused, int direction,
5543            Rect previouslyFocusedRect) {
5544        if (DebugFlags.WEB_VIEW) {
5545            Log.v(LOGTAG, "MT focusChanged " + focused + ", " + direction);
5546        }
5547        if (focused) {
5548            mDrawCursorRing = true;
5549            setFocusControllerActive(true);
5550        } else {
5551            mDrawCursorRing = false;
5552            setFocusControllerActive(false);
5553            mKeysPressed.clear();
5554        }
5555        if (!mTouchHighlightRegion.isEmpty()) {
5556            mWebView.invalidate(mTouchHighlightRegion.getBounds());
5557        }
5558    }
5559
5560    // updateRectsForGL() happens almost every draw call, in order to avoid creating
5561    // any object in this code path, we move the local variable out to be a private
5562    // final member, and we marked them as mTemp*.
5563    private final Point mTempVisibleRectOffset = new Point();
5564    private final Rect mTempVisibleRect = new Rect();
5565
5566    void updateRectsForGL() {
5567        // Use the getGlobalVisibleRect() to get the intersection among the parents
5568        // visible == false means we're clipped - send a null rect down to indicate that
5569        // we should not draw
5570        boolean visible = mWebView.getGlobalVisibleRect(mTempVisibleRect, mTempVisibleRectOffset);
5571        mInvScreenRect.set(mTempVisibleRect);
5572        if (visible) {
5573            // Then need to invert the Y axis, just for GL
5574            View rootView = mWebView.getRootView();
5575            int rootViewHeight = rootView.getHeight();
5576            mScreenRect.set(mInvScreenRect);
5577            int savedWebViewBottom = mInvScreenRect.bottom;
5578            mInvScreenRect.bottom = rootViewHeight - mInvScreenRect.top - getVisibleTitleHeightImpl();
5579            mInvScreenRect.top = rootViewHeight - savedWebViewBottom;
5580            mIsWebViewVisible = true;
5581        } else {
5582            mIsWebViewVisible = false;
5583        }
5584
5585        mTempVisibleRect.offset(-mTempVisibleRectOffset.x, -mTempVisibleRectOffset.y);
5586        viewToContentVisibleRect(mVisibleContentRect, mTempVisibleRect);
5587
5588        nativeUpdateDrawGLFunction(mNativeClass, mIsWebViewVisible ? mInvScreenRect : null,
5589                mIsWebViewVisible ? mScreenRect : null,
5590                mVisibleContentRect, getScale());
5591    }
5592
5593    // Input : viewRect, rect in view/screen coordinate.
5594    // Output: contentRect, rect in content/document coordinate.
5595    private void viewToContentVisibleRect(RectF contentRect, Rect viewRect) {
5596        contentRect.left = viewToContentXf(viewRect.left) / mWebView.getScaleX();
5597        // viewToContentY will remove the total height of the title bar.  Add
5598        // the visible height back in to account for the fact that if the title
5599        // bar is partially visible, the part of the visible rect which is
5600        // displaying our content is displaced by that amount.
5601        contentRect.top = viewToContentYf(viewRect.top + getVisibleTitleHeightImpl())
5602                / mWebView.getScaleY();
5603        contentRect.right = viewToContentXf(viewRect.right) / mWebView.getScaleX();
5604        contentRect.bottom = viewToContentYf(viewRect.bottom) / mWebView.getScaleY();
5605    }
5606
5607    @Override
5608    public boolean setFrame(int left, int top, int right, int bottom) {
5609        boolean changed = mWebViewPrivate.super_setFrame(left, top, right, bottom);
5610        if (!changed && mHeightCanMeasure) {
5611            // When mHeightCanMeasure is true, we will set mLastHeightSent to 0
5612            // in WebViewCore after we get the first layout. We do call
5613            // requestLayout() when we get contentSizeChanged(). But the View
5614            // system won't call onSizeChanged if the dimension is not changed.
5615            // In this case, we need to call sendViewSizeZoom() explicitly to
5616            // notify the WebKit about the new dimensions.
5617            sendViewSizeZoom(false);
5618        }
5619        updateRectsForGL();
5620        return changed;
5621    }
5622
5623    @Override
5624    public void onSizeChanged(int w, int h, int ow, int oh) {
5625        // adjust the max viewport width depending on the view dimensions. This
5626        // is to ensure the scaling is not going insane. So do not shrink it if
5627        // the view size is temporarily smaller, e.g. when soft keyboard is up.
5628        int newMaxViewportWidth = (int) (Math.max(w, h) / mZoomManager.getDefaultMinZoomScale());
5629        if (newMaxViewportWidth > sMaxViewportWidth) {
5630            sMaxViewportWidth = newMaxViewportWidth;
5631        }
5632
5633        mZoomManager.onSizeChanged(w, h, ow, oh);
5634
5635        if (mLoadedPicture != null && mDelaySetPicture == null) {
5636            // Size changes normally result in a new picture
5637            // Re-set the loaded picture to simulate that
5638            // However, do not update the base layer as that hasn't changed
5639            setNewPicture(mLoadedPicture, false);
5640        }
5641        if (mIsEditingText) {
5642            scrollEditIntoView();
5643        }
5644        relocateAutoCompletePopup();
5645    }
5646
5647    /**
5648     * Scrolls the edit field into view using the minimum scrolling necessary.
5649     * If the edit field is too large to fit in the visible window, the caret
5650     * dimensions are used so that at least the caret is visible.
5651     * A buffer of EDIT_RECT_BUFFER in view pixels is used to offset the
5652     * edit rectangle to ensure a margin with the edge of the screen.
5653     */
5654    private void scrollEditIntoView() {
5655        Rect visibleRect = new Rect(viewToContentX(getScrollX()),
5656                viewToContentY(getScrollY()),
5657                viewToContentX(getScrollX() + getWidth()),
5658                viewToContentY(getScrollY() + getViewHeightWithTitle()));
5659        if (visibleRect.contains(mEditTextContentBounds)) {
5660            return; // no need to scroll
5661        }
5662        syncSelectionCursors();
5663        nativeFindMaxVisibleRect(mNativeClass, mEditTextLayerId, visibleRect);
5664        final int buffer = Math.max(1, viewToContentDimension(EDIT_RECT_BUFFER));
5665        Rect showRect = new Rect(
5666                Math.max(0, mEditTextContentBounds.left - buffer),
5667                Math.max(0, mEditTextContentBounds.top - buffer),
5668                mEditTextContentBounds.right + buffer,
5669                mEditTextContentBounds.bottom + buffer);
5670        Point caretTop = calculateBaseCaretTop();
5671        if (visibleRect.width() < mEditTextContentBounds.width()) {
5672            // The whole edit won't fit in the width, so use the caret rect
5673            if (mSelectCursorBase.x < caretTop.x) {
5674                showRect.left = Math.max(0, mSelectCursorBase.x - buffer);
5675                showRect.right = caretTop.x + buffer;
5676            } else {
5677                showRect.left = Math.max(0, caretTop.x - buffer);
5678                showRect.right = mSelectCursorBase.x + buffer;
5679            }
5680        }
5681        if (visibleRect.height() < mEditTextContentBounds.height()) {
5682            // The whole edit won't fit in the height, so use the caret rect
5683            if (mSelectCursorBase.y > caretTop.y) {
5684                showRect.top = Math.max(0, caretTop.y - buffer);
5685                showRect.bottom = mSelectCursorBase.y + buffer;
5686            } else {
5687                showRect.top = Math.max(0, mSelectCursorBase.y - buffer);
5688                showRect.bottom = caretTop.y + buffer;
5689            }
5690        }
5691
5692        if (visibleRect.contains(showRect)) {
5693            return; // no need to scroll
5694        }
5695
5696        int scrollX = viewToContentX(getScrollX());
5697        if (visibleRect.left > showRect.left) {
5698            // We are scrolled too far
5699            scrollX += showRect.left - visibleRect.left;
5700        } else if (visibleRect.right < showRect.right) {
5701            // We aren't scrolled enough to include the right
5702            scrollX += showRect.right - visibleRect.right;
5703        }
5704        int scrollY = viewToContentY(getScrollY());
5705        if (visibleRect.top > showRect.top) {
5706            scrollY += showRect.top - visibleRect.top;
5707        } else if (visibleRect.bottom < showRect.bottom) {
5708            scrollY += showRect.bottom - visibleRect.bottom;
5709        }
5710
5711        contentScrollTo(scrollX, scrollY, false);
5712    }
5713
5714    @Override
5715    public void onScrollChanged(int l, int t, int oldl, int oldt) {
5716        if (!mInOverScrollMode) {
5717            sendOurVisibleRect();
5718            // update WebKit if visible title bar height changed. The logic is same
5719            // as getVisibleTitleHeightImpl.
5720            int titleHeight = getTitleHeight();
5721            if (Math.max(titleHeight - t, 0) != Math.max(titleHeight - oldt, 0)) {
5722                sendViewSizeZoom(false);
5723            }
5724        }
5725    }
5726
5727    @Override
5728    public boolean dispatchKeyEvent(KeyEvent event) {
5729        switch (event.getAction()) {
5730            case KeyEvent.ACTION_DOWN:
5731                mKeysPressed.add(Integer.valueOf(event.getKeyCode()));
5732                break;
5733            case KeyEvent.ACTION_MULTIPLE:
5734                // Always accept the action.
5735                break;
5736            case KeyEvent.ACTION_UP:
5737                int location = mKeysPressed.indexOf(Integer.valueOf(event.getKeyCode()));
5738                if (location == -1) {
5739                    // We did not receive the key down for this key, so do not
5740                    // handle the key up.
5741                    return false;
5742                } else {
5743                    // We did receive the key down.  Handle the key up, and
5744                    // remove it from our pressed keys.
5745                    mKeysPressed.remove(location);
5746                }
5747                break;
5748            default:
5749                // Accept the action.  This should not happen, unless a new
5750                // action is added to KeyEvent.
5751                break;
5752        }
5753        return mWebViewPrivate.super_dispatchKeyEvent(event);
5754    }
5755
5756    private static final int SNAP_BOUND = 16;
5757    private static int sChannelDistance = 16;
5758    private int mFirstTouchX = -1; // the first touched point
5759    private int mFirstTouchY = -1;
5760    private int mDistanceX = 0;
5761    private int mDistanceY = 0;
5762
5763    private boolean inFullScreenMode() {
5764        return mFullScreenHolder != null;
5765    }
5766
5767    private void dismissFullScreenMode() {
5768        if (inFullScreenMode()) {
5769            mFullScreenHolder.hide();
5770            mFullScreenHolder = null;
5771            invalidate();
5772        }
5773    }
5774
5775    void onPinchToZoomAnimationStart() {
5776        // cancel the single touch handling
5777        cancelTouch();
5778        onZoomAnimationStart();
5779    }
5780
5781    void onPinchToZoomAnimationEnd(ScaleGestureDetector detector) {
5782        onZoomAnimationEnd();
5783        // start a drag, TOUCH_PINCH_DRAG, can't use TOUCH_INIT_MODE as
5784        // it may trigger the unwanted click, can't use TOUCH_DRAG_MODE
5785        // as it may trigger the unwanted fling.
5786        mTouchMode = TOUCH_PINCH_DRAG;
5787        mConfirmMove = true;
5788        startTouch(detector.getFocusX(), detector.getFocusY(), mLastTouchTime);
5789    }
5790
5791    // See if there is a layer at x, y and switch to TOUCH_DRAG_LAYER_MODE if a
5792    // layer is found.
5793    private void startScrollingLayer(float x, float y) {
5794        if (mNativeClass == 0)
5795            return;
5796
5797        int contentX = viewToContentX((int) x + getScrollX());
5798        int contentY = viewToContentY((int) y + getScrollY());
5799        mCurrentScrollingLayerId = nativeScrollableLayer(mNativeClass,
5800                contentX, contentY, mScrollingLayerRect, mScrollingLayerBounds);
5801        if (mCurrentScrollingLayerId != 0) {
5802            mTouchMode = TOUCH_DRAG_LAYER_MODE;
5803        }
5804    }
5805
5806    // 1/(density * density) used to compute the distance between points.
5807    // Computed in init().
5808    private float DRAG_LAYER_INVERSE_DENSITY_SQUARED;
5809
5810    // The distance between two points reported in onTouchEvent scaled by the
5811    // density of the screen.
5812    private static final int DRAG_LAYER_FINGER_DISTANCE = 20000;
5813
5814    @Override
5815    public boolean onHoverEvent(MotionEvent event) {
5816        if (mNativeClass == 0) {
5817            return false;
5818        }
5819        int x = viewToContentX((int) event.getX() + getScrollX());
5820        int y = viewToContentY((int) event.getY() + getScrollY());
5821        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, x, y);
5822        mWebViewPrivate.super_onHoverEvent(event);
5823        return true;
5824    }
5825
5826    @Override
5827    public boolean onTouchEvent(MotionEvent ev) {
5828        if (mNativeClass == 0 || (!mWebView.isClickable() && !mWebView.isLongClickable())) {
5829            return false;
5830        }
5831
5832        if (mInputDispatcher == null) {
5833            return false;
5834        }
5835
5836        if (mWebView.isFocusable() && mWebView.isFocusableInTouchMode()
5837                && !mWebView.isFocused()) {
5838            mWebView.requestFocus();
5839        }
5840
5841        if (mInputDispatcher.postPointerEvent(ev, getScrollX(),
5842                getScrollY() - getTitleHeight(), mZoomManager.getInvScale())) {
5843            mInputDispatcher.dispatchUiEvents();
5844            return true;
5845        } else {
5846            Log.w(LOGTAG, "mInputDispatcher rejected the event!");
5847            return false;
5848        }
5849    }
5850
5851    /*
5852    * Common code for single touch and multi-touch.
5853    * (x, y) denotes current focus point, which is the touch point for single touch
5854    * and the middle point for multi-touch.
5855    */
5856    private void handleTouchEventCommon(MotionEvent event, int action, int x, int y) {
5857        ScaleGestureDetector detector = mZoomManager.getScaleGestureDetector();
5858
5859        long eventTime = event.getEventTime();
5860
5861        // Due to the touch screen edge effect, a touch closer to the edge
5862        // always snapped to the edge. As getViewWidth() can be different from
5863        // getWidth() due to the scrollbar, adjusting the point to match
5864        // getViewWidth(). Same applied to the height.
5865        x = Math.min(x, getViewWidth() - 1);
5866        y = Math.min(y, getViewHeightWithTitle() - 1);
5867
5868        int deltaX = mLastTouchX - x;
5869        int deltaY = mLastTouchY - y;
5870        int contentX = viewToContentX(x + getScrollX());
5871        int contentY = viewToContentY(y + getScrollY());
5872
5873        switch (action) {
5874            case MotionEvent.ACTION_DOWN: {
5875                mConfirmMove = false;
5876
5877                // Channel Scrolling
5878                mFirstTouchX = x;
5879                mFirstTouchY = y;
5880                mDistanceX = mDistanceY = 0;
5881
5882                if (!mEditTextScroller.isFinished()) {
5883                    mEditTextScroller.abortAnimation();
5884                }
5885                if (!mScroller.isFinished()) {
5886                    // stop the current scroll animation, but if this is
5887                    // the start of a fling, allow it to add to the current
5888                    // fling's velocity
5889                    mScroller.abortAnimation();
5890                    mTouchMode = TOUCH_DRAG_START_MODE;
5891                    mConfirmMove = true;
5892                    nativeSetIsScrolling(false);
5893                } else if (mPrivateHandler.hasMessages(RELEASE_SINGLE_TAP)) {
5894                    mPrivateHandler.removeMessages(RELEASE_SINGLE_TAP);
5895                    removeTouchHighlight();
5896                    if (deltaX * deltaX + deltaY * deltaY < mDoubleTapSlopSquare) {
5897                        mTouchMode = TOUCH_DOUBLE_TAP_MODE;
5898                    } else {
5899                        mTouchMode = TOUCH_INIT_MODE;
5900                    }
5901                } else { // the normal case
5902                    mTouchMode = TOUCH_INIT_MODE;
5903                    if (mLogEvent && eventTime - mLastTouchUpTime < 1000) {
5904                        EventLog.writeEvent(EventLogTags.BROWSER_DOUBLE_TAP_DURATION,
5905                                (eventTime - mLastTouchUpTime), eventTime);
5906                    }
5907                    mSelectionStarted = false;
5908                    if (mSelectingText) {
5909                        ensureSelectionHandles();
5910                        int shiftedY = y - getTitleHeight() + getScrollY();
5911                        int shiftedX = x + getScrollX();
5912                        if (mSelectHandleBaseBounds.contains(shiftedX, shiftedY)) {
5913                            mSelectionStarted = true;
5914                            mSelectDraggingCursor = mSelectCursorBase;
5915                            mSelectDraggingTextQuad = mSelectCursorBaseTextQuad;
5916                            if (mIsCaretSelection) {
5917                                mPrivateHandler.removeMessages(CLEAR_CARET_HANDLE);
5918                                hidePasteButton();
5919                            }
5920                        } else if (mSelectHandleExtentBounds
5921                                .contains(shiftedX, shiftedY)) {
5922                            mSelectionStarted = true;
5923                            mSelectDraggingCursor = mSelectCursorExtent;
5924                            mSelectDraggingTextQuad = mSelectCursorExtentTextQuad;
5925                        } else if (mIsCaretSelection) {
5926                            selectionDone();
5927                        }
5928                        if (DebugFlags.WEB_VIEW) {
5929                            Log.v(LOGTAG, "select=" + contentX + "," + contentY);
5930                        }
5931                    }
5932                }
5933                // Trigger the link
5934                if (!mSelectingText && (mTouchMode == TOUCH_INIT_MODE
5935                        || mTouchMode == TOUCH_DOUBLE_TAP_MODE)) {
5936                    mPrivateHandler.sendEmptyMessageDelayed(
5937                            SWITCH_TO_SHORTPRESS, TAP_TIMEOUT);
5938                    mPrivateHandler.sendEmptyMessageDelayed(
5939                            SWITCH_TO_LONGPRESS, LONG_PRESS_TIMEOUT);
5940                }
5941                startTouch(x, y, eventTime);
5942                if (mIsEditingText) {
5943                    mTouchInEditText = mEditTextContentBounds
5944                            .contains(contentX, contentY);
5945                }
5946                break;
5947            }
5948            case MotionEvent.ACTION_MOVE: {
5949                if (!mConfirmMove && (deltaX * deltaX + deltaY * deltaY)
5950                        >= mTouchSlopSquare) {
5951                    mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
5952                    mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5953                    mConfirmMove = true;
5954                    if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
5955                        mTouchMode = TOUCH_INIT_MODE;
5956                    }
5957                    removeTouchHighlight();
5958                }
5959                if (mSelectingText && mSelectionStarted) {
5960                    if (DebugFlags.WEB_VIEW) {
5961                        Log.v(LOGTAG, "extend=" + contentX + "," + contentY);
5962                    }
5963                    ViewParent parent = mWebView.getParent();
5964                    if (parent != null) {
5965                        parent.requestDisallowInterceptTouchEvent(true);
5966                    }
5967                    if (deltaX != 0 || deltaY != 0) {
5968                        int handleX = contentX +
5969                                viewToContentDimension(mSelectOffset.x);
5970                        int handleY = contentY +
5971                                viewToContentDimension(mSelectOffset.y);
5972                        mSelectDraggingCursor.set(handleX, handleY);
5973                        boolean inCursorText =
5974                                mSelectDraggingTextQuad.containsPoint(handleX, handleY);
5975                        boolean inEditBounds = mEditTextContentBounds
5976                                .contains(handleX, handleY);
5977                        if (mIsEditingText && !inEditBounds) {
5978                            beginScrollEdit();
5979                        } else {
5980                            endScrollEdit();
5981                        }
5982                        boolean snapped = false;
5983                        if (inCursorText || (mIsEditingText && !inEditBounds)) {
5984                            snapDraggingCursor();
5985                            snapped = true;
5986                        }
5987                        updateWebkitSelection(snapped);
5988                        if (!inCursorText && mIsEditingText && inEditBounds) {
5989                            // Visually snap even if we have moved the handle.
5990                            snapDraggingCursor();
5991                        }
5992                        mLastTouchX = x;
5993                        mLastTouchY = y;
5994                        invalidate();
5995                    }
5996                    break;
5997                }
5998
5999                if (mTouchMode == TOUCH_DONE_MODE) {
6000                    // no dragging during scroll zoom animation, or when prevent
6001                    // default is yes
6002                    break;
6003                }
6004                if (mVelocityTracker == null) {
6005                    Log.e(LOGTAG, "Got null mVelocityTracker when "
6006                            + " mTouchMode = " + mTouchMode);
6007                } else {
6008                    mVelocityTracker.addMovement(event);
6009                }
6010
6011                if (mTouchMode != TOUCH_DRAG_MODE &&
6012                        mTouchMode != TOUCH_DRAG_LAYER_MODE &&
6013                        mTouchMode != TOUCH_DRAG_TEXT_MODE) {
6014
6015                    if (!mConfirmMove) {
6016                        break;
6017                    }
6018
6019                    if ((detector == null || !detector.isInProgress())
6020                            && SNAP_NONE == mSnapScrollMode) {
6021                        int ax = Math.abs(x - mFirstTouchX);
6022                        int ay = Math.abs(y - mFirstTouchY);
6023                        if (ax < SNAP_BOUND && ay < SNAP_BOUND) {
6024                            break;
6025                        } else if (ax < SNAP_BOUND) {
6026                            mSnapScrollMode = SNAP_Y;
6027                        } else if (ay < SNAP_BOUND) {
6028                            mSnapScrollMode = SNAP_X;
6029                        }
6030                    }
6031
6032                    mTouchMode = TOUCH_DRAG_MODE;
6033                    mLastTouchX = x;
6034                    mLastTouchY = y;
6035                    deltaX = 0;
6036                    deltaY = 0;
6037
6038                    startScrollingLayer(x, y);
6039                    startDrag();
6040                }
6041
6042                // do pan
6043                boolean keepScrollBarsVisible = false;
6044                if (deltaX == 0 && deltaY == 0) {
6045                    keepScrollBarsVisible = true;
6046                } else {
6047                    if (mSnapScrollMode == SNAP_X || mSnapScrollMode == SNAP_Y) {
6048                        mDistanceX += Math.abs(deltaX);
6049                        mDistanceY += Math.abs(deltaY);
6050                        if (mSnapScrollMode == SNAP_X) {
6051                            if (mDistanceY > sChannelDistance) {
6052                                mSnapScrollMode = SNAP_NONE;
6053                            } else if (mDistanceX > sChannelDistance) {
6054                                mDistanceX = mDistanceY = 0;
6055                        }
6056                    } else {
6057                            if (mDistanceX > sChannelDistance) {
6058                                mSnapScrollMode = SNAP_NONE;
6059                            } else if (mDistanceY > sChannelDistance) {
6060                                mDistanceX = mDistanceY = 0;
6061                            }
6062                        }
6063                    }
6064                    if (mSnapScrollMode != SNAP_NONE) {
6065                        if ((mSnapScrollMode & SNAP_X) == SNAP_X) {
6066                            deltaY = 0;
6067                        } else {
6068                            deltaX = 0;
6069                        }
6070                    }
6071                    if (deltaX * deltaX + deltaY * deltaY > mTouchSlopSquare) {
6072                        mHeldMotionless = MOTIONLESS_FALSE;
6073                    } else {
6074                        mHeldMotionless = MOTIONLESS_TRUE;
6075                        keepScrollBarsVisible = true;
6076                    }
6077
6078                    mLastTouchTime = eventTime;
6079                    boolean allDrag = doDrag(deltaX, deltaY);
6080                    if (allDrag) {
6081                        mLastTouchX = x;
6082                        mLastTouchY = y;
6083                    } else {
6084                        int contentDeltaX = (int)Math.floor(deltaX * mZoomManager.getInvScale());
6085                        int roundedDeltaX = contentToViewDimension(contentDeltaX);
6086                        int contentDeltaY = (int)Math.floor(deltaY * mZoomManager.getInvScale());
6087                        int roundedDeltaY = contentToViewDimension(contentDeltaY);
6088                        mLastTouchX -= roundedDeltaX;
6089                        mLastTouchY -= roundedDeltaY;
6090                    }
6091                }
6092
6093                break;
6094            }
6095            case MotionEvent.ACTION_UP: {
6096                mFirstTouchX  = mFirstTouchY = -1;
6097                if (mIsEditingText && mSelectionStarted) {
6098                    endScrollEdit();
6099                    mPrivateHandler.sendEmptyMessageDelayed(SCROLL_HANDLE_INTO_VIEW,
6100                            TEXT_SCROLL_FIRST_SCROLL_MS);
6101                    if (!mConfirmMove && mIsCaretSelection) {
6102                        showPasteWindow();
6103                        stopTouch();
6104                        break;
6105                    }
6106                }
6107                mLastTouchUpTime = eventTime;
6108                if (mSentAutoScrollMessage) {
6109                    mAutoScrollX = mAutoScrollY = 0;
6110                }
6111                switch (mTouchMode) {
6112                    case TOUCH_DOUBLE_TAP_MODE: // double tap
6113                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
6114                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
6115                        mTouchMode = TOUCH_DONE_MODE;
6116                        break;
6117                    case TOUCH_INIT_MODE: // tap
6118                    case TOUCH_SHORTPRESS_START_MODE:
6119                    case TOUCH_SHORTPRESS_MODE:
6120                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
6121                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
6122                        if (!mConfirmMove) {
6123                            if (mSelectingText) {
6124                                // tapping on selection or controls does nothing
6125                                if (!mSelectionStarted) {
6126                                    selectionDone();
6127                                }
6128                                break;
6129                            }
6130                            // only trigger double tap if the WebView is
6131                            // scalable
6132                            if (mTouchMode == TOUCH_INIT_MODE
6133                                    && (canZoomIn() || canZoomOut())) {
6134                                mPrivateHandler.sendEmptyMessageDelayed(
6135                                        RELEASE_SINGLE_TAP, ViewConfiguration
6136                                                .getDoubleTapTimeout());
6137                            }
6138                            break;
6139                        }
6140                    case TOUCH_DRAG_MODE:
6141                    case TOUCH_DRAG_LAYER_MODE:
6142                    case TOUCH_DRAG_TEXT_MODE:
6143                        mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
6144                        // if the user waits a while w/o moving before the
6145                        // up, we don't want to do a fling
6146                        if (eventTime - mLastTouchTime <= MIN_FLING_TIME) {
6147                            if (mVelocityTracker == null) {
6148                                Log.e(LOGTAG, "Got null mVelocityTracker");
6149                            } else {
6150                                mVelocityTracker.addMovement(event);
6151                            }
6152                            // set to MOTIONLESS_IGNORE so that it won't keep
6153                            // removing and sending message in
6154                            // drawCoreAndCursorRing()
6155                            mHeldMotionless = MOTIONLESS_IGNORE;
6156                            doFling();
6157                            break;
6158                        } else {
6159                            if (mScroller.springBack(getScrollX(), getScrollY(), 0,
6160                                    computeMaxScrollX(), 0,
6161                                    computeMaxScrollY())) {
6162                                invalidate();
6163                            }
6164                        }
6165                        // redraw in high-quality, as we're done dragging
6166                        mHeldMotionless = MOTIONLESS_TRUE;
6167                        invalidate();
6168                        // fall through
6169                    case TOUCH_DRAG_START_MODE:
6170                        // TOUCH_DRAG_START_MODE should not happen for the real
6171                        // device as we almost certain will get a MOVE. But this
6172                        // is possible on emulator.
6173                        mLastVelocity = 0;
6174                        WebViewCore.resumePriority();
6175                        if (!mSelectingText) {
6176                            WebViewCore.resumeUpdatePicture(mWebViewCore);
6177                        }
6178                        break;
6179                }
6180                stopTouch();
6181                break;
6182            }
6183            case MotionEvent.ACTION_CANCEL: {
6184                if (mTouchMode == TOUCH_DRAG_MODE) {
6185                    mScroller.springBack(getScrollX(), getScrollY(), 0,
6186                            computeMaxScrollX(), 0, computeMaxScrollY());
6187                    invalidate();
6188                }
6189                cancelTouch();
6190                break;
6191            }
6192        }
6193    }
6194
6195    /**
6196     * Returns the text scroll speed in content pixels per millisecond based on
6197     * the touch location.
6198     * @param coordinate The x or y touch coordinate in content space
6199     * @param min The minimum coordinate (x or y) of the edit content bounds
6200     * @param max The maximum coordinate (x or y) of the edit content bounds
6201     */
6202    private static float getTextScrollSpeed(int coordinate, int min, int max) {
6203        if (coordinate < min) {
6204            return (coordinate - min) * TEXT_SCROLL_RATE;
6205        } else if (coordinate >= max) {
6206            return (coordinate - max + 1) * TEXT_SCROLL_RATE;
6207        } else {
6208            return 0.0f;
6209        }
6210    }
6211
6212    private static int getSelectionCoordinate(int coordinate, int min, int max) {
6213        return Math.max(Math.min(coordinate, max), min);
6214    }
6215
6216    private void beginScrollEdit() {
6217        if (mLastEditScroll == 0) {
6218            mLastEditScroll = SystemClock.uptimeMillis() -
6219                    TEXT_SCROLL_FIRST_SCROLL_MS;
6220            scrollEditWithCursor();
6221        }
6222    }
6223
6224    private void scrollDraggedSelectionHandleIntoView() {
6225        if (mSelectDraggingCursor == null) {
6226            return;
6227        }
6228        int x = mSelectDraggingCursor.x;
6229        int y = mSelectDraggingCursor.y;
6230        if (!mEditTextContentBounds.contains(x,y)) {
6231            int left = Math.min(0, x - mEditTextContentBounds.left - EDIT_RECT_BUFFER);
6232            int right = Math.max(0, x - mEditTextContentBounds.right + EDIT_RECT_BUFFER);
6233            int deltaX = left + right;
6234            int above = Math.min(0, y - mEditTextContentBounds.top - EDIT_RECT_BUFFER);
6235            int below = Math.max(0, y - mEditTextContentBounds.bottom + EDIT_RECT_BUFFER);
6236            int deltaY = above + below;
6237            if (deltaX != 0 || deltaY != 0) {
6238                int scrollX = getTextScrollX() + deltaX;
6239                int scrollY = getTextScrollY() + deltaY;
6240                scrollX = clampBetween(scrollX, 0, getMaxTextScrollX());
6241                scrollY = clampBetween(scrollY, 0, getMaxTextScrollY());
6242                scrollEditText(scrollX, scrollY);
6243            }
6244        }
6245    }
6246
6247    private void endScrollEdit() {
6248        mLastEditScroll = 0;
6249    }
6250
6251    private static int clampBetween(int value, int min, int max) {
6252        return Math.max(min, Math.min(value, max));
6253    }
6254
6255    private static int getTextScrollDelta(float speed, long deltaT) {
6256        float distance = speed * deltaT;
6257        int intDistance = (int)Math.floor(distance);
6258        float probability = distance - intDistance;
6259        if (Math.random() < probability) {
6260            intDistance++;
6261        }
6262        return intDistance;
6263    }
6264    /**
6265     * Scrolls edit text a distance based on the last touch point,
6266     * the last scroll time, and the edit text content bounds.
6267     */
6268    private void scrollEditWithCursor() {
6269        if (mLastEditScroll != 0) {
6270            int x = viewToContentX(mLastTouchX + getScrollX() + mSelectOffset.x);
6271            float scrollSpeedX = getTextScrollSpeed(x, mEditTextContentBounds.left,
6272                    mEditTextContentBounds.right);
6273            int y = viewToContentY(mLastTouchY + getScrollY() + mSelectOffset.y);
6274            float scrollSpeedY = getTextScrollSpeed(y, mEditTextContentBounds.top,
6275                    mEditTextContentBounds.bottom);
6276            if (scrollSpeedX == 0.0f && scrollSpeedY == 0.0f) {
6277                endScrollEdit();
6278            } else {
6279                long currentTime = SystemClock.uptimeMillis();
6280                long timeSinceLastUpdate = currentTime - mLastEditScroll;
6281                int deltaX = getTextScrollDelta(scrollSpeedX, timeSinceLastUpdate);
6282                int deltaY = getTextScrollDelta(scrollSpeedY, timeSinceLastUpdate);
6283                int scrollX = getTextScrollX() + deltaX;
6284                scrollX = clampBetween(scrollX, 0, getMaxTextScrollX());
6285                int scrollY = getTextScrollY() + deltaY;
6286                scrollY = clampBetween(scrollY, 0, getMaxTextScrollY());
6287
6288                mLastEditScroll = currentTime;
6289                if (scrollX == getTextScrollX() && scrollY == getTextScrollY()) {
6290                    // By probability no text scroll this time. Try again later.
6291                    mPrivateHandler.sendEmptyMessageDelayed(SCROLL_EDIT_TEXT,
6292                            TEXT_SCROLL_FIRST_SCROLL_MS);
6293                } else {
6294                    int selectionX = getSelectionCoordinate(x,
6295                            mEditTextContentBounds.left, mEditTextContentBounds.right);
6296                    int selectionY = getSelectionCoordinate(y,
6297                            mEditTextContentBounds.top, mEditTextContentBounds.bottom);
6298                    int oldX = mSelectDraggingCursor.x;
6299                    int oldY = mSelectDraggingCursor.y;
6300                    mSelectDraggingCursor.set(selectionX, selectionY);
6301                    updateWebkitSelection(false);
6302                    scrollEditText(scrollX, scrollY);
6303                    mSelectDraggingCursor.set(oldX, oldY);
6304                }
6305            }
6306        }
6307    }
6308
6309    private void startTouch(float x, float y, long eventTime) {
6310        // Remember where the motion event started
6311        mStartTouchX = mLastTouchX = Math.round(x);
6312        mStartTouchY = mLastTouchY = Math.round(y);
6313        mLastTouchTime = eventTime;
6314        mVelocityTracker = VelocityTracker.obtain();
6315        mSnapScrollMode = SNAP_NONE;
6316    }
6317
6318    private void startDrag() {
6319        WebViewCore.reducePriority();
6320        // to get better performance, pause updating the picture
6321        WebViewCore.pauseUpdatePicture(mWebViewCore);
6322        nativeSetIsScrolling(true);
6323
6324        if (mHorizontalScrollBarMode != SCROLLBAR_ALWAYSOFF
6325                || mVerticalScrollBarMode != SCROLLBAR_ALWAYSOFF) {
6326            mZoomManager.invokeZoomPicker();
6327        }
6328    }
6329
6330    private boolean doDrag(int deltaX, int deltaY) {
6331        boolean allDrag = true;
6332        if ((deltaX | deltaY) != 0) {
6333            int oldX = getScrollX();
6334            int oldY = getScrollY();
6335            int rangeX = computeMaxScrollX();
6336            int rangeY = computeMaxScrollY();
6337            final int contentX = (int)Math.floor(deltaX * mZoomManager.getInvScale());
6338            final int contentY = (int)Math.floor(deltaY * mZoomManager.getInvScale());
6339
6340            // Assume page scrolling and change below if we're wrong
6341            mTouchMode = TOUCH_DRAG_MODE;
6342
6343            // Check special scrolling before going to main page scrolling.
6344            if (mIsEditingText && mTouchInEditText && canTextScroll(deltaX, deltaY)) {
6345                // Edit text scrolling
6346                oldX = getTextScrollX();
6347                rangeX = getMaxTextScrollX();
6348                deltaX = contentX;
6349                oldY = getTextScrollY();
6350                rangeY = getMaxTextScrollY();
6351                deltaY = contentY;
6352                mTouchMode = TOUCH_DRAG_TEXT_MODE;
6353                allDrag = false;
6354            } else if (mCurrentScrollingLayerId != 0) {
6355                // Check the scrolling bounds to see if we will actually do any
6356                // scrolling.  The rectangle is in document coordinates.
6357                final int maxX = mScrollingLayerRect.right;
6358                final int maxY = mScrollingLayerRect.bottom;
6359                final int resultX = clampBetween(maxX, 0,
6360                        mScrollingLayerRect.left + contentX);
6361                final int resultY = clampBetween(maxY, 0,
6362                        mScrollingLayerRect.top + contentY);
6363
6364                if (resultX != mScrollingLayerRect.left
6365                        || resultY != mScrollingLayerRect.top
6366                        || (contentX | contentY) == 0) {
6367                    // In case we switched to dragging the page.
6368                    mTouchMode = TOUCH_DRAG_LAYER_MODE;
6369                    deltaX = contentX;
6370                    deltaY = contentY;
6371                    oldX = mScrollingLayerRect.left;
6372                    oldY = mScrollingLayerRect.top;
6373                    rangeX = maxX;
6374                    rangeY = maxY;
6375                    allDrag = false;
6376                }
6377            }
6378
6379            if (mOverScrollGlow != null) {
6380                mOverScrollGlow.setOverScrollDeltas(deltaX, deltaY);
6381            }
6382
6383            mWebViewPrivate.overScrollBy(deltaX, deltaY, oldX, oldY,
6384                    rangeX, rangeY,
6385                    mOverscrollDistance, mOverscrollDistance, true);
6386            if (mOverScrollGlow != null && mOverScrollGlow.isAnimating()) {
6387                invalidate();
6388            }
6389        }
6390        mZoomManager.keepZoomPickerVisible();
6391        return allDrag;
6392    }
6393
6394    private void stopTouch() {
6395        if (mScroller.isFinished() && !mSelectingText
6396                && (mTouchMode == TOUCH_DRAG_MODE
6397                || mTouchMode == TOUCH_DRAG_LAYER_MODE)) {
6398            WebViewCore.resumePriority();
6399            WebViewCore.resumeUpdatePicture(mWebViewCore);
6400            nativeSetIsScrolling(false);
6401        }
6402
6403        // we also use mVelocityTracker == null to tell us that we are
6404        // not "moving around", so we can take the slower/prettier
6405        // mode in the drawing code
6406        if (mVelocityTracker != null) {
6407            mVelocityTracker.recycle();
6408            mVelocityTracker = null;
6409        }
6410
6411        // Release any pulled glows
6412        if (mOverScrollGlow != null) {
6413            mOverScrollGlow.releaseAll();
6414        }
6415
6416        if (mSelectingText) {
6417            mSelectionStarted = false;
6418            syncSelectionCursors();
6419            if (mIsCaretSelection) {
6420                resetCaretTimer();
6421            }
6422            invalidate();
6423        }
6424    }
6425
6426    private void cancelTouch() {
6427        // we also use mVelocityTracker == null to tell us that we are
6428        // not "moving around", so we can take the slower/prettier
6429        // mode in the drawing code
6430        if (mVelocityTracker != null) {
6431            mVelocityTracker.recycle();
6432            mVelocityTracker = null;
6433        }
6434
6435        if ((mTouchMode == TOUCH_DRAG_MODE
6436                || mTouchMode == TOUCH_DRAG_LAYER_MODE) && !mSelectingText) {
6437            WebViewCore.resumePriority();
6438            WebViewCore.resumeUpdatePicture(mWebViewCore);
6439            nativeSetIsScrolling(false);
6440        }
6441        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
6442        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
6443        mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
6444        removeTouchHighlight();
6445        mHeldMotionless = MOTIONLESS_TRUE;
6446        mTouchMode = TOUCH_DONE_MODE;
6447    }
6448
6449    private void snapDraggingCursor() {
6450        float scale = scaleAlongSegment(
6451                mSelectDraggingCursor.x, mSelectDraggingCursor.y,
6452                mSelectDraggingTextQuad.p4, mSelectDraggingTextQuad.p3);
6453        // clamp scale to ensure point is on the bottom segment
6454        scale = Math.max(0.0f, scale);
6455        scale = Math.min(scale, 1.0f);
6456        float newX = scaleCoordinate(scale,
6457                mSelectDraggingTextQuad.p4.x, mSelectDraggingTextQuad.p3.x);
6458        float newY = scaleCoordinate(scale,
6459                mSelectDraggingTextQuad.p4.y, mSelectDraggingTextQuad.p3.y);
6460        int x = Math.round(newX);
6461        int y = Math.round(newY);
6462        if (mIsEditingText) {
6463            x = clampBetween(x, mEditTextContentBounds.left,
6464                    mEditTextContentBounds.right);
6465            y = clampBetween(y, mEditTextContentBounds.top,
6466                    mEditTextContentBounds.bottom);
6467        }
6468        mSelectDraggingCursor.set(x, y);
6469    }
6470
6471    private static float scaleCoordinate(float scale, float coord1, float coord2) {
6472        float diff = coord2 - coord1;
6473        return coord1 + (scale * diff);
6474    }
6475
6476    @Override
6477    public boolean onGenericMotionEvent(MotionEvent event) {
6478        if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
6479            switch (event.getAction()) {
6480                case MotionEvent.ACTION_SCROLL: {
6481                    final float vscroll;
6482                    final float hscroll;
6483                    if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
6484                        vscroll = 0;
6485                        hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
6486                    } else {
6487                        vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
6488                        hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
6489                    }
6490                    if (hscroll != 0 || vscroll != 0) {
6491                        final int vdelta = (int) (vscroll *
6492                                mWebViewPrivate.getVerticalScrollFactor());
6493                        final int hdelta = (int) (hscroll *
6494                                mWebViewPrivate.getHorizontalScrollFactor());
6495
6496                        abortAnimation();
6497                        int oldTouchMode = mTouchMode;
6498                        startScrollingLayer(event.getX(), event.getY());
6499                        doDrag(hdelta, vdelta);
6500                        mTouchMode = oldTouchMode;
6501                        return true;
6502                    }
6503                }
6504            }
6505        }
6506        return mWebViewPrivate.super_onGenericMotionEvent(event);
6507    }
6508
6509    private long mTrackballFirstTime = 0;
6510    private long mTrackballLastTime = 0;
6511    private float mTrackballRemainsX = 0.0f;
6512    private float mTrackballRemainsY = 0.0f;
6513    private int mTrackballXMove = 0;
6514    private int mTrackballYMove = 0;
6515    private boolean mSelectingText = false;
6516    private boolean mShowTextSelectionExtra = false;
6517    private boolean mSelectionStarted = false;
6518    private static final int TRACKBALL_KEY_TIMEOUT = 1000;
6519    private static final int TRACKBALL_TIMEOUT = 200;
6520    private static final int TRACKBALL_WAIT = 100;
6521    private static final int TRACKBALL_SCALE = 400;
6522    private static final int TRACKBALL_SCROLL_COUNT = 5;
6523    private static final int TRACKBALL_MOVE_COUNT = 10;
6524    private static final int TRACKBALL_MULTIPLIER = 3;
6525    private static final int SELECT_CURSOR_OFFSET = 16;
6526    private static final int SELECT_SCROLL = 5;
6527    private int mSelectX = 0;
6528    private int mSelectY = 0;
6529    private boolean mTrackballDown = false;
6530    private long mTrackballUpTime = 0;
6531    private long mLastCursorTime = 0;
6532    private Rect mLastCursorBounds;
6533    private SelectionHandleAlpha mBaseAlpha = new SelectionHandleAlpha();
6534    private SelectionHandleAlpha mExtentAlpha = new SelectionHandleAlpha();
6535    private ObjectAnimator mBaseHandleAlphaAnimator =
6536            ObjectAnimator.ofInt(mBaseAlpha, "alpha", 0);
6537    private ObjectAnimator mExtentHandleAlphaAnimator =
6538            ObjectAnimator.ofInt(mExtentAlpha, "alpha", 0);
6539
6540    // Set by default; BrowserActivity clears to interpret trackball data
6541    // directly for movement. Currently, the framework only passes
6542    // arrow key events, not trackball events, from one child to the next
6543    private boolean mMapTrackballToArrowKeys = true;
6544
6545    private DrawData mDelaySetPicture;
6546    private DrawData mLoadedPicture;
6547
6548    @Override
6549    public void setMapTrackballToArrowKeys(boolean setMap) {
6550        mMapTrackballToArrowKeys = setMap;
6551    }
6552
6553    void resetTrackballTime() {
6554        mTrackballLastTime = 0;
6555    }
6556
6557    @Override
6558    public boolean onTrackballEvent(MotionEvent ev) {
6559        long time = ev.getEventTime();
6560        if ((ev.getMetaState() & KeyEvent.META_ALT_ON) != 0) {
6561            if (ev.getY() > 0) pageDown(true);
6562            if (ev.getY() < 0) pageUp(true);
6563            return true;
6564        }
6565        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
6566            if (mSelectingText) {
6567                return true; // discard press if copy in progress
6568            }
6569            mTrackballDown = true;
6570            if (mNativeClass == 0) {
6571                return false;
6572            }
6573            if (DebugFlags.WEB_VIEW) {
6574                Log.v(LOGTAG, "onTrackballEvent down ev=" + ev
6575                        + " time=" + time
6576                        + " mLastCursorTime=" + mLastCursorTime);
6577            }
6578            if (mWebView.isInTouchMode()) mWebView.requestFocusFromTouch();
6579            return false; // let common code in onKeyDown at it
6580        }
6581        if (ev.getAction() == MotionEvent.ACTION_UP) {
6582            // LONG_PRESS_CENTER is set in common onKeyDown
6583            mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
6584            mTrackballDown = false;
6585            mTrackballUpTime = time;
6586            if (mSelectingText) {
6587                copySelection();
6588                selectionDone();
6589                return true; // discard press if copy in progress
6590            }
6591            if (DebugFlags.WEB_VIEW) {
6592                Log.v(LOGTAG, "onTrackballEvent up ev=" + ev
6593                        + " time=" + time
6594                );
6595            }
6596            return false; // let common code in onKeyUp at it
6597        }
6598        if ((mMapTrackballToArrowKeys && (ev.getMetaState() & KeyEvent.META_SHIFT_ON) == 0) ||
6599                AccessibilityManager.getInstance(mContext).isEnabled()) {
6600            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent gmail quit");
6601            return false;
6602        }
6603        if (mTrackballDown) {
6604            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent down quit");
6605            return true; // discard move if trackball is down
6606        }
6607        if (time - mTrackballUpTime < TRACKBALL_TIMEOUT) {
6608            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent up timeout quit");
6609            return true;
6610        }
6611        // TODO: alternatively we can do panning as touch does
6612        switchOutDrawHistory();
6613        if (time - mTrackballLastTime > TRACKBALL_TIMEOUT) {
6614            if (DebugFlags.WEB_VIEW) {
6615                Log.v(LOGTAG, "onTrackballEvent time="
6616                        + time + " last=" + mTrackballLastTime);
6617            }
6618            mTrackballFirstTime = time;
6619            mTrackballXMove = mTrackballYMove = 0;
6620        }
6621        mTrackballLastTime = time;
6622        if (DebugFlags.WEB_VIEW) {
6623            Log.v(LOGTAG, "onTrackballEvent ev=" + ev + " time=" + time);
6624        }
6625        mTrackballRemainsX += ev.getX();
6626        mTrackballRemainsY += ev.getY();
6627        doTrackball(time, ev.getMetaState());
6628        return true;
6629    }
6630
6631    private int scaleTrackballX(float xRate, int width) {
6632        int xMove = (int) (xRate / TRACKBALL_SCALE * width);
6633        int nextXMove = xMove;
6634        if (xMove > 0) {
6635            if (xMove > mTrackballXMove) {
6636                xMove -= mTrackballXMove;
6637            }
6638        } else if (xMove < mTrackballXMove) {
6639            xMove -= mTrackballXMove;
6640        }
6641        mTrackballXMove = nextXMove;
6642        return xMove;
6643    }
6644
6645    private int scaleTrackballY(float yRate, int height) {
6646        int yMove = (int) (yRate / TRACKBALL_SCALE * height);
6647        int nextYMove = yMove;
6648        if (yMove > 0) {
6649            if (yMove > mTrackballYMove) {
6650                yMove -= mTrackballYMove;
6651            }
6652        } else if (yMove < mTrackballYMove) {
6653            yMove -= mTrackballYMove;
6654        }
6655        mTrackballYMove = nextYMove;
6656        return yMove;
6657    }
6658
6659    private int keyCodeToSoundsEffect(int keyCode) {
6660        switch(keyCode) {
6661            case KeyEvent.KEYCODE_DPAD_UP:
6662                return SoundEffectConstants.NAVIGATION_UP;
6663            case KeyEvent.KEYCODE_DPAD_RIGHT:
6664                return SoundEffectConstants.NAVIGATION_RIGHT;
6665            case KeyEvent.KEYCODE_DPAD_DOWN:
6666                return SoundEffectConstants.NAVIGATION_DOWN;
6667            case KeyEvent.KEYCODE_DPAD_LEFT:
6668                return SoundEffectConstants.NAVIGATION_LEFT;
6669        }
6670        return 0;
6671    }
6672
6673    private void doTrackball(long time, int metaState) {
6674        int elapsed = (int) (mTrackballLastTime - mTrackballFirstTime);
6675        if (elapsed == 0) {
6676            elapsed = TRACKBALL_TIMEOUT;
6677        }
6678        float xRate = mTrackballRemainsX * 1000 / elapsed;
6679        float yRate = mTrackballRemainsY * 1000 / elapsed;
6680        int viewWidth = getViewWidth();
6681        int viewHeight = getViewHeight();
6682        float ax = Math.abs(xRate);
6683        float ay = Math.abs(yRate);
6684        float maxA = Math.max(ax, ay);
6685        if (DebugFlags.WEB_VIEW) {
6686            Log.v(LOGTAG, "doTrackball elapsed=" + elapsed
6687                    + " xRate=" + xRate
6688                    + " yRate=" + yRate
6689                    + " mTrackballRemainsX=" + mTrackballRemainsX
6690                    + " mTrackballRemainsY=" + mTrackballRemainsY);
6691        }
6692        int width = mContentWidth - viewWidth;
6693        int height = mContentHeight - viewHeight;
6694        if (width < 0) width = 0;
6695        if (height < 0) height = 0;
6696        ax = Math.abs(mTrackballRemainsX * TRACKBALL_MULTIPLIER);
6697        ay = Math.abs(mTrackballRemainsY * TRACKBALL_MULTIPLIER);
6698        maxA = Math.max(ax, ay);
6699        int count = Math.max(0, (int) maxA);
6700        int oldScrollX = getScrollX();
6701        int oldScrollY = getScrollY();
6702        if (count > 0) {
6703            int selectKeyCode = ax < ay ? mTrackballRemainsY < 0 ?
6704                    KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN :
6705                    mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT :
6706                    KeyEvent.KEYCODE_DPAD_RIGHT;
6707            count = Math.min(count, TRACKBALL_MOVE_COUNT);
6708            if (DebugFlags.WEB_VIEW) {
6709                Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode
6710                        + " count=" + count
6711                        + " mTrackballRemainsX=" + mTrackballRemainsX
6712                        + " mTrackballRemainsY=" + mTrackballRemainsY);
6713            }
6714            if (mNativeClass != 0) {
6715                for (int i = 0; i < count; i++) {
6716                    letPageHandleNavKey(selectKeyCode, time, true, metaState);
6717                }
6718                letPageHandleNavKey(selectKeyCode, time, false, metaState);
6719            }
6720            mTrackballRemainsX = mTrackballRemainsY = 0;
6721        }
6722        if (count >= TRACKBALL_SCROLL_COUNT) {
6723            int xMove = scaleTrackballX(xRate, width);
6724            int yMove = scaleTrackballY(yRate, height);
6725            if (DebugFlags.WEB_VIEW) {
6726                Log.v(LOGTAG, "doTrackball pinScrollBy"
6727                        + " count=" + count
6728                        + " xMove=" + xMove + " yMove=" + yMove
6729                        + " mScrollX-oldScrollX=" + (getScrollX()-oldScrollX)
6730                        + " mScrollY-oldScrollY=" + (getScrollY()-oldScrollY)
6731                        );
6732            }
6733            if (Math.abs(getScrollX() - oldScrollX) > Math.abs(xMove)) {
6734                xMove = 0;
6735            }
6736            if (Math.abs(getScrollY() - oldScrollY) > Math.abs(yMove)) {
6737                yMove = 0;
6738            }
6739            if (xMove != 0 || yMove != 0) {
6740                pinScrollBy(xMove, yMove, true, 0);
6741            }
6742        }
6743    }
6744
6745    /**
6746     * Compute the maximum horizontal scroll position. Used by {@link OverScrollGlow}.
6747     * @return Maximum horizontal scroll position within real content
6748     */
6749    int computeMaxScrollX() {
6750        return Math.max(computeRealHorizontalScrollRange() - getViewWidth(), 0);
6751    }
6752
6753    /**
6754     * Compute the maximum vertical scroll position. Used by {@link OverScrollGlow}.
6755     * @return Maximum vertical scroll position within real content
6756     */
6757    int computeMaxScrollY() {
6758        return Math.max(computeRealVerticalScrollRange() + getTitleHeight()
6759                - getViewHeightWithTitle(), 0);
6760    }
6761
6762    boolean updateScrollCoordinates(int x, int y) {
6763        int oldX = getScrollX();
6764        int oldY = getScrollY();
6765        setScrollXRaw(x);
6766        setScrollYRaw(y);
6767        if (oldX != getScrollX() || oldY != getScrollY()) {
6768            mWebViewPrivate.onScrollChanged(getScrollX(), getScrollY(), oldX, oldY);
6769            return true;
6770        } else {
6771            return false;
6772        }
6773    }
6774
6775    @Override
6776    public void flingScroll(int vx, int vy) {
6777        mScroller.fling(getScrollX(), getScrollY(), vx, vy, 0, computeMaxScrollX(), 0,
6778                computeMaxScrollY(), mOverflingDistance, mOverflingDistance);
6779        invalidate();
6780    }
6781
6782    private void doFling() {
6783        if (mVelocityTracker == null) {
6784            return;
6785        }
6786        int maxX = computeMaxScrollX();
6787        int maxY = computeMaxScrollY();
6788
6789        mVelocityTracker.computeCurrentVelocity(1000, mMaximumFling);
6790        int vx = (int) mVelocityTracker.getXVelocity();
6791        int vy = (int) mVelocityTracker.getYVelocity();
6792
6793        int scrollX = getScrollX();
6794        int scrollY = getScrollY();
6795        int overscrollDistance = mOverscrollDistance;
6796        int overflingDistance = mOverflingDistance;
6797
6798        // Use the layer's scroll data if applicable.
6799        if (mTouchMode == TOUCH_DRAG_LAYER_MODE) {
6800            scrollX = mScrollingLayerRect.left;
6801            scrollY = mScrollingLayerRect.top;
6802            maxX = mScrollingLayerRect.right;
6803            maxY = mScrollingLayerRect.bottom;
6804            // No overscrolling for layers.
6805            overscrollDistance = overflingDistance = 0;
6806        } else if (mTouchMode == TOUCH_DRAG_TEXT_MODE) {
6807            scrollX = getTextScrollX();
6808            scrollY = getTextScrollY();
6809            maxX = getMaxTextScrollX();
6810            maxY = getMaxTextScrollY();
6811            // No overscrolling for edit text.
6812            overscrollDistance = overflingDistance = 0;
6813        }
6814
6815        if (mSnapScrollMode != SNAP_NONE) {
6816            if ((mSnapScrollMode & SNAP_X) == SNAP_X) {
6817                vy = 0;
6818            } else {
6819                vx = 0;
6820            }
6821        }
6822        if ((maxX == 0 && vy == 0) || (maxY == 0 && vx == 0)) {
6823            WebViewCore.resumePriority();
6824            if (!mSelectingText) {
6825                WebViewCore.resumeUpdatePicture(mWebViewCore);
6826            }
6827            if (mScroller.springBack(scrollX, scrollY, 0, maxX, 0, maxY)) {
6828                invalidate();
6829            }
6830            return;
6831        }
6832        float currentVelocity = mScroller.getCurrVelocity();
6833        float velocity = (float) Math.hypot(vx, vy);
6834        if (mLastVelocity > 0 && currentVelocity > 0 && velocity
6835                > mLastVelocity * MINIMUM_VELOCITY_RATIO_FOR_ACCELERATION) {
6836            float deltaR = (float) (Math.abs(Math.atan2(mLastVelY, mLastVelX)
6837                    - Math.atan2(vy, vx)));
6838            final float circle = (float) (Math.PI) * 2.0f;
6839            if (deltaR > circle * 0.9f || deltaR < circle * 0.1f) {
6840                vx += currentVelocity * mLastVelX / mLastVelocity;
6841                vy += currentVelocity * mLastVelY / mLastVelocity;
6842                velocity = (float) Math.hypot(vx, vy);
6843                if (DebugFlags.WEB_VIEW) {
6844                    Log.v(LOGTAG, "doFling vx= " + vx + " vy=" + vy);
6845                }
6846            } else if (DebugFlags.WEB_VIEW) {
6847                Log.v(LOGTAG, "doFling missed " + deltaR / circle);
6848            }
6849        } else if (DebugFlags.WEB_VIEW) {
6850            Log.v(LOGTAG, "doFling start last=" + mLastVelocity
6851                    + " current=" + currentVelocity
6852                    + " vx=" + vx + " vy=" + vy
6853                    + " maxX=" + maxX + " maxY=" + maxY
6854                    + " scrollX=" + scrollX + " scrollY=" + scrollY
6855                    + " layer=" + mCurrentScrollingLayerId);
6856        }
6857
6858        // Allow sloppy flings without overscrolling at the edges.
6859        if ((scrollX == 0 || scrollX == maxX) && Math.abs(vx) < Math.abs(vy)) {
6860            vx = 0;
6861        }
6862        if ((scrollY == 0 || scrollY == maxY) && Math.abs(vy) < Math.abs(vx)) {
6863            vy = 0;
6864        }
6865
6866        if (overscrollDistance < overflingDistance) {
6867            if ((vx > 0 && scrollX == -overscrollDistance) ||
6868                    (vx < 0 && scrollX == maxX + overscrollDistance)) {
6869                vx = 0;
6870            }
6871            if ((vy > 0 && scrollY == -overscrollDistance) ||
6872                    (vy < 0 && scrollY == maxY + overscrollDistance)) {
6873                vy = 0;
6874            }
6875        }
6876
6877        mLastVelX = vx;
6878        mLastVelY = vy;
6879        mLastVelocity = velocity;
6880
6881        // no horizontal overscroll if the content just fits
6882        mScroller.fling(scrollX, scrollY, -vx, -vy, 0, maxX, 0, maxY,
6883                maxX == 0 ? 0 : overflingDistance, overflingDistance);
6884
6885        invalidate();
6886    }
6887
6888    /**
6889     * See {@link WebView#getZoomControls()}
6890     */
6891    @Override
6892    @Deprecated
6893    public View getZoomControls() {
6894        if (!getSettings().supportZoom()) {
6895            Log.w(LOGTAG, "This WebView doesn't support zoom.");
6896            return null;
6897        }
6898        return mZoomManager.getExternalZoomPicker();
6899    }
6900
6901    void dismissZoomControl() {
6902        mZoomManager.dismissZoomPicker();
6903    }
6904
6905    float getDefaultZoomScale() {
6906        return mZoomManager.getDefaultScale();
6907    }
6908
6909    /**
6910     * Return the overview scale of the WebView
6911     * @return The overview scale.
6912     */
6913    float getZoomOverviewScale() {
6914        return mZoomManager.getZoomOverviewScale();
6915    }
6916
6917    /**
6918     * See {@link WebView#canZoomIn()}
6919     */
6920    @Override
6921    public boolean canZoomIn() {
6922        return mZoomManager.canZoomIn();
6923    }
6924
6925    /**
6926     * See {@link WebView#canZoomOut()}
6927     */
6928    @Override
6929    public boolean canZoomOut() {
6930        return mZoomManager.canZoomOut();
6931    }
6932
6933    /**
6934     * See {@link WebView#zoomIn()}
6935     */
6936    @Override
6937    public boolean zoomIn() {
6938        return mZoomManager.zoomIn();
6939    }
6940
6941    /**
6942     * See {@link WebView#zoomOut()}
6943     */
6944    @Override
6945    public boolean zoomOut() {
6946        return mZoomManager.zoomOut();
6947    }
6948
6949    /*
6950     * Return true if the rect (e.g. plugin) is fully visible and maximized
6951     * inside the WebView.
6952     */
6953    boolean isRectFitOnScreen(Rect rect) {
6954        final int rectWidth = rect.width();
6955        final int rectHeight = rect.height();
6956        final int viewWidth = getViewWidth();
6957        final int viewHeight = getViewHeightWithTitle();
6958        float scale = Math.min((float) viewWidth / rectWidth, (float) viewHeight / rectHeight);
6959        scale = mZoomManager.computeScaleWithLimits(scale);
6960        return !mZoomManager.willScaleTriggerZoom(scale)
6961                && contentToViewX(rect.left) >= getScrollX()
6962                && contentToViewX(rect.right) <= getScrollX() + viewWidth
6963                && contentToViewY(rect.top) >= getScrollY()
6964                && contentToViewY(rect.bottom) <= getScrollY() + viewHeight;
6965    }
6966
6967    /*
6968     * Maximize and center the rectangle, specified in the document coordinate
6969     * space, inside the WebView. If the zoom doesn't need to be changed, do an
6970     * animated scroll to center it. If the zoom needs to be changed, find the
6971     * zoom center and do a smooth zoom transition. The rect is in document
6972     * coordinates
6973     */
6974    void centerFitRect(Rect rect) {
6975        final int rectWidth = rect.width();
6976        final int rectHeight = rect.height();
6977        final int viewWidth = getViewWidth();
6978        final int viewHeight = getViewHeightWithTitle();
6979        float scale = Math.min((float) viewWidth / rectWidth, (float) viewHeight
6980                / rectHeight);
6981        scale = mZoomManager.computeScaleWithLimits(scale);
6982        if (!mZoomManager.willScaleTriggerZoom(scale)) {
6983            pinScrollTo(contentToViewX(rect.left + rectWidth / 2) - viewWidth / 2,
6984                    contentToViewY(rect.top + rectHeight / 2) - viewHeight / 2,
6985                    true, 0);
6986        } else {
6987            float actualScale = mZoomManager.getScale();
6988            float oldScreenX = rect.left * actualScale - getScrollX();
6989            float rectViewX = rect.left * scale;
6990            float rectViewWidth = rectWidth * scale;
6991            float newMaxWidth = mContentWidth * scale;
6992            float newScreenX = (viewWidth - rectViewWidth) / 2;
6993            // pin the newX to the WebView
6994            if (newScreenX > rectViewX) {
6995                newScreenX = rectViewX;
6996            } else if (newScreenX > (newMaxWidth - rectViewX - rectViewWidth)) {
6997                newScreenX = viewWidth - (newMaxWidth - rectViewX);
6998            }
6999            float zoomCenterX = (oldScreenX * scale - newScreenX * actualScale)
7000                    / (scale - actualScale);
7001            float oldScreenY = rect.top * actualScale + getTitleHeight()
7002                    - getScrollY();
7003            float rectViewY = rect.top * scale + getTitleHeight();
7004            float rectViewHeight = rectHeight * scale;
7005            float newMaxHeight = mContentHeight * scale + getTitleHeight();
7006            float newScreenY = (viewHeight - rectViewHeight) / 2;
7007            // pin the newY to the WebView
7008            if (newScreenY > rectViewY) {
7009                newScreenY = rectViewY;
7010            } else if (newScreenY > (newMaxHeight - rectViewY - rectViewHeight)) {
7011                newScreenY = viewHeight - (newMaxHeight - rectViewY);
7012            }
7013            float zoomCenterY = (oldScreenY * scale - newScreenY * actualScale)
7014                    / (scale - actualScale);
7015            mZoomManager.setZoomCenter(zoomCenterX, zoomCenterY);
7016            mZoomManager.startZoomAnimation(scale, false);
7017        }
7018    }
7019
7020    // Called by JNI to handle a touch on a node representing an email address,
7021    // address, or phone number
7022    private void overrideLoading(String url) {
7023        mCallbackProxy.uiOverrideUrlLoading(url);
7024    }
7025
7026    @Override
7027    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
7028        // Check if we are destroyed
7029        if (mWebViewCore == null) return false;
7030        // FIXME: If a subwindow is showing find, and the user touches the
7031        // background window, it can steal focus.
7032        if (mFindIsUp) return false;
7033        boolean result = false;
7034        result = mWebViewPrivate.super_requestFocus(direction, previouslyFocusedRect);
7035        if (mWebViewCore.getSettings().getNeedInitialFocus()
7036                && !mWebView.isInTouchMode()) {
7037            // For cases such as GMail, where we gain focus from a direction,
7038            // we want to move to the first available link.
7039            // FIXME: If there are no visible links, we may not want to
7040            int fakeKeyDirection = 0;
7041            switch(direction) {
7042                case View.FOCUS_UP:
7043                    fakeKeyDirection = KeyEvent.KEYCODE_DPAD_UP;
7044                    break;
7045                case View.FOCUS_DOWN:
7046                    fakeKeyDirection = KeyEvent.KEYCODE_DPAD_DOWN;
7047                    break;
7048                case View.FOCUS_LEFT:
7049                    fakeKeyDirection = KeyEvent.KEYCODE_DPAD_LEFT;
7050                    break;
7051                case View.FOCUS_RIGHT:
7052                    fakeKeyDirection = KeyEvent.KEYCODE_DPAD_RIGHT;
7053                    break;
7054                default:
7055                    return result;
7056            }
7057            mWebViewCore.sendMessage(EventHub.SET_INITIAL_FOCUS, fakeKeyDirection);
7058        }
7059        return result;
7060    }
7061
7062    @Override
7063    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
7064        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
7065        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
7066        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
7067        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
7068
7069        int measuredHeight = heightSize;
7070        int measuredWidth = widthSize;
7071
7072        // Grab the content size from WebViewCore.
7073        int contentHeight = contentToViewDimension(mContentHeight);
7074        int contentWidth = contentToViewDimension(mContentWidth);
7075
7076//        Log.d(LOGTAG, "------- measure " + heightMode);
7077
7078        if (heightMode != MeasureSpec.EXACTLY) {
7079            mHeightCanMeasure = true;
7080            measuredHeight = contentHeight;
7081            if (heightMode == MeasureSpec.AT_MOST) {
7082                // If we are larger than the AT_MOST height, then our height can
7083                // no longer be measured and we should scroll internally.
7084                if (measuredHeight > heightSize) {
7085                    measuredHeight = heightSize;
7086                    mHeightCanMeasure = false;
7087                    measuredHeight |= View.MEASURED_STATE_TOO_SMALL;
7088                }
7089            }
7090        } else {
7091            mHeightCanMeasure = false;
7092        }
7093        if (mNativeClass != 0) {
7094            nativeSetHeightCanMeasure(mHeightCanMeasure);
7095        }
7096        // For the width, always use the given size unless unspecified.
7097        if (widthMode == MeasureSpec.UNSPECIFIED) {
7098            mWidthCanMeasure = true;
7099            measuredWidth = contentWidth;
7100        } else {
7101            if (measuredWidth < contentWidth) {
7102                measuredWidth |= View.MEASURED_STATE_TOO_SMALL;
7103            }
7104            mWidthCanMeasure = false;
7105        }
7106
7107        synchronized (this) {
7108            mWebViewPrivate.setMeasuredDimension(measuredWidth, measuredHeight);
7109        }
7110    }
7111
7112    @Override
7113    public boolean requestChildRectangleOnScreen(View child,
7114                                                 Rect rect,
7115                                                 boolean immediate) {
7116        if (mNativeClass == 0) {
7117            return false;
7118        }
7119        // don't scroll while in zoom animation. When it is done, we will adjust
7120        // the necessary components
7121        if (mZoomManager.isFixedLengthAnimationInProgress()) {
7122            return false;
7123        }
7124
7125        rect.offset(child.getLeft() - child.getScrollX(),
7126                child.getTop() - child.getScrollY());
7127
7128        Rect content = new Rect(viewToContentX(getScrollX()),
7129                viewToContentY(getScrollY()),
7130                viewToContentX(getScrollX() + getWidth()
7131                - mWebView.getVerticalScrollbarWidth()),
7132                viewToContentY(getScrollY() + getViewHeightWithTitle()));
7133        int screenTop = contentToViewY(content.top);
7134        int screenBottom = contentToViewY(content.bottom);
7135        int height = screenBottom - screenTop;
7136        int scrollYDelta = 0;
7137
7138        if (rect.bottom > screenBottom) {
7139            int oneThirdOfScreenHeight = height / 3;
7140            if (rect.height() > 2 * oneThirdOfScreenHeight) {
7141                // If the rectangle is too tall to fit in the bottom two thirds
7142                // of the screen, place it at the top.
7143                scrollYDelta = rect.top - screenTop;
7144            } else {
7145                // If the rectangle will still fit on screen, we want its
7146                // top to be in the top third of the screen.
7147                scrollYDelta = rect.top - (screenTop + oneThirdOfScreenHeight);
7148            }
7149        } else if (rect.top < screenTop) {
7150            scrollYDelta = rect.top - screenTop;
7151        }
7152
7153        int screenLeft = contentToViewX(content.left);
7154        int screenRight = contentToViewX(content.right);
7155        int width = screenRight - screenLeft;
7156        int scrollXDelta = 0;
7157
7158        if (rect.right > screenRight && rect.left > screenLeft) {
7159            if (rect.width() > width) {
7160                scrollXDelta += (rect.left - screenLeft);
7161            } else {
7162                scrollXDelta += (rect.right - screenRight);
7163            }
7164        } else if (rect.left < screenLeft) {
7165            scrollXDelta -= (screenLeft - rect.left);
7166        }
7167
7168        if ((scrollYDelta | scrollXDelta) != 0) {
7169            return pinScrollBy(scrollXDelta, scrollYDelta, !immediate, 0);
7170        }
7171
7172        return false;
7173    }
7174
7175    /* package */ void replaceTextfieldText(int oldStart, int oldEnd,
7176            String replace, int newStart, int newEnd) {
7177        WebViewCore.ReplaceTextData arg = new WebViewCore.ReplaceTextData();
7178        arg.mReplace = replace;
7179        arg.mNewStart = newStart;
7180        arg.mNewEnd = newEnd;
7181        mTextGeneration++;
7182        arg.mTextGeneration = mTextGeneration;
7183        sendBatchableInputMessage(EventHub.REPLACE_TEXT, oldStart, oldEnd, arg);
7184    }
7185
7186    /* package */ void passToJavaScript(String currentText, KeyEvent event) {
7187        // check if mWebViewCore has been destroyed
7188        if (mWebViewCore == null) {
7189            return;
7190        }
7191        WebViewCore.JSKeyData arg = new WebViewCore.JSKeyData();
7192        arg.mEvent = event;
7193        arg.mCurrentText = currentText;
7194        // Increase our text generation number, and pass it to webcore thread
7195        mTextGeneration++;
7196        mWebViewCore.sendMessage(EventHub.PASS_TO_JS, mTextGeneration, 0, arg);
7197        // WebKit's document state is not saved until about to leave the page.
7198        // To make sure the host application, like Browser, has the up to date
7199        // document state when it goes to background, we force to save the
7200        // document state.
7201        mWebViewCore.removeMessages(EventHub.SAVE_DOCUMENT_STATE);
7202        mWebViewCore.sendMessageDelayed(EventHub.SAVE_DOCUMENT_STATE, null, 1000);
7203    }
7204
7205    public synchronized WebViewCore getWebViewCore() {
7206        return mWebViewCore;
7207    }
7208
7209    private boolean canTextScroll(int directionX, int directionY) {
7210        int scrollX = getTextScrollX();
7211        int scrollY = getTextScrollY();
7212        int maxScrollX = getMaxTextScrollX();
7213        int maxScrollY = getMaxTextScrollY();
7214        boolean canScrollX = (directionX > 0)
7215                ? (scrollX < maxScrollX)
7216                : (scrollX > 0);
7217        boolean canScrollY = (directionY > 0)
7218                ? (scrollY < maxScrollY)
7219                : (scrollY > 0);
7220        return canScrollX || canScrollY;
7221    }
7222
7223    private int getTextScrollX() {
7224        return -mEditTextContent.left;
7225    }
7226
7227    private int getTextScrollY() {
7228        return -mEditTextContent.top;
7229    }
7230
7231    private int getMaxTextScrollX() {
7232        return Math.max(0, mEditTextContent.width() - mEditTextContentBounds.width());
7233    }
7234
7235    private int getMaxTextScrollY() {
7236        return Math.max(0, mEditTextContent.height() - mEditTextContentBounds.height());
7237    }
7238
7239    //-------------------------------------------------------------------------
7240    // Methods can be called from a separate thread, like WebViewCore
7241    // If it needs to call the View system, it has to send message.
7242    //-------------------------------------------------------------------------
7243
7244    /**
7245     * General handler to receive message coming from webkit thread
7246     */
7247    class PrivateHandler extends Handler implements WebViewInputDispatcher.UiCallbacks {
7248        @Override
7249        public void handleMessage(Message msg) {
7250            // exclude INVAL_RECT_MSG_ID since it is frequently output
7251            if (DebugFlags.WEB_VIEW && msg.what != INVAL_RECT_MSG_ID) {
7252                if (msg.what >= FIRST_PRIVATE_MSG_ID
7253                        && msg.what <= LAST_PRIVATE_MSG_ID) {
7254                    Log.v(LOGTAG, HandlerPrivateDebugString[msg.what
7255                            - FIRST_PRIVATE_MSG_ID]);
7256                } else if (msg.what >= FIRST_PACKAGE_MSG_ID
7257                        && msg.what <= LAST_PACKAGE_MSG_ID) {
7258                    Log.v(LOGTAG, HandlerPackageDebugString[msg.what
7259                            - FIRST_PACKAGE_MSG_ID]);
7260                } else {
7261                    Log.v(LOGTAG, Integer.toString(msg.what));
7262                }
7263            }
7264            if (mWebViewCore == null) {
7265                // after WebView's destroy() is called, skip handling messages.
7266                return;
7267            }
7268            if (mBlockWebkitViewMessages
7269                    && msg.what != WEBCORE_INITIALIZED_MSG_ID) {
7270                // Blocking messages from webkit
7271                return;
7272            }
7273            switch (msg.what) {
7274                case REMEMBER_PASSWORD: {
7275                    mDatabase.setUsernamePassword(
7276                            msg.getData().getString("host"),
7277                            msg.getData().getString("username"),
7278                            msg.getData().getString("password"));
7279                    ((Message) msg.obj).sendToTarget();
7280                    break;
7281                }
7282                case NEVER_REMEMBER_PASSWORD: {
7283                    mDatabase.setUsernamePassword(msg.getData().getString("host"), null, null);
7284                    ((Message) msg.obj).sendToTarget();
7285                    break;
7286                }
7287                case SCROLL_SELECT_TEXT: {
7288                    if (mAutoScrollX == 0 && mAutoScrollY == 0) {
7289                        mSentAutoScrollMessage = false;
7290                        break;
7291                    }
7292                    if (mCurrentScrollingLayerId == 0) {
7293                        pinScrollBy(mAutoScrollX, mAutoScrollY, true, 0);
7294                    } else {
7295                        scrollLayerTo(mScrollingLayerRect.left + mAutoScrollX,
7296                                mScrollingLayerRect.top + mAutoScrollY);
7297                    }
7298                    sendEmptyMessageDelayed(
7299                            SCROLL_SELECT_TEXT, SELECT_SCROLL_INTERVAL);
7300                    break;
7301                }
7302                case SCROLL_TO_MSG_ID: {
7303                    // arg1 = animate, arg2 = onlyIfImeIsShowing
7304                    // obj = Point(x, y)
7305                    if (msg.arg2 == 1) {
7306                        // This scroll is intended to bring the textfield into
7307                        // view, but is only necessary if the IME is showing
7308                        InputMethodManager imm = InputMethodManager.peekInstance();
7309                        if (imm == null || !imm.isAcceptingText()
7310                                || !imm.isActive(mWebView)) {
7311                            break;
7312                        }
7313                    }
7314                    final Point p = (Point) msg.obj;
7315                    contentScrollTo(p.x, p.y, msg.arg1 == 1);
7316                    break;
7317                }
7318                case UPDATE_ZOOM_RANGE: {
7319                    WebViewCore.ViewState viewState = (WebViewCore.ViewState) msg.obj;
7320                    // mScrollX contains the new minPrefWidth
7321                    mZoomManager.updateZoomRange(viewState, getViewWidth(), viewState.mScrollX);
7322                    break;
7323                }
7324                case UPDATE_ZOOM_DENSITY: {
7325                    final float density = (Float) msg.obj;
7326                    mZoomManager.updateDefaultZoomDensity(density);
7327                    break;
7328                }
7329                case NEW_PICTURE_MSG_ID: {
7330                    // called for new content
7331                    final WebViewCore.DrawData draw = (WebViewCore.DrawData) msg.obj;
7332                    setNewPicture(draw, true);
7333                    break;
7334                }
7335                case WEBCORE_INITIALIZED_MSG_ID:
7336                    // nativeCreate sets mNativeClass to a non-zero value
7337                    String drawableDir = BrowserFrame.getRawResFilename(
7338                            BrowserFrame.DRAWABLEDIR, mContext);
7339                    nativeCreate(msg.arg1, drawableDir, ActivityManager.isHighEndGfx());
7340                    if (mDelaySetPicture != null) {
7341                        setNewPicture(mDelaySetPicture, true);
7342                        mDelaySetPicture = null;
7343                    }
7344                    if (mIsPaused) {
7345                        nativeSetPauseDrawing(mNativeClass, true);
7346                    }
7347                    mInputDispatcher = new WebViewInputDispatcher(this,
7348                            mWebViewCore.getInputDispatcherCallbacks());
7349                    break;
7350                case UPDATE_TEXTFIELD_TEXT_MSG_ID:
7351                    // Make sure that the textfield is currently focused
7352                    // and representing the same node as the pointer.
7353                    if (msg.arg2 == mTextGeneration) {
7354                        String text = (String) msg.obj;
7355                        if (null == text) {
7356                            text = "";
7357                        }
7358                        if (mInputConnection != null &&
7359                                mFieldPointer == msg.arg1) {
7360                            mInputConnection.setTextAndKeepSelection(text);
7361                        }
7362                    }
7363                    break;
7364                case UPDATE_TEXT_SELECTION_MSG_ID:
7365                    updateTextSelectionFromMessage(msg.arg1, msg.arg2,
7366                            (WebViewCore.TextSelectionData) msg.obj);
7367                    break;
7368                case TAKE_FOCUS:
7369                    int direction = msg.arg1;
7370                    View focusSearch = mWebView.focusSearch(direction);
7371                    if (focusSearch != null && focusSearch != mWebView) {
7372                        focusSearch.requestFocus();
7373                    }
7374                    break;
7375                case CLEAR_TEXT_ENTRY:
7376                    hideSoftKeyboard();
7377                    break;
7378                case INVAL_RECT_MSG_ID: {
7379                    Rect r = (Rect)msg.obj;
7380                    if (r == null) {
7381                        invalidate();
7382                    } else {
7383                        // we need to scale r from content into view coords,
7384                        // which viewInvalidate() does for us
7385                        viewInvalidate(r.left, r.top, r.right, r.bottom);
7386                    }
7387                    break;
7388                }
7389                case REQUEST_FORM_DATA:
7390                    if (mFieldPointer == msg.arg1) {
7391                        ArrayAdapter<String> adapter = (ArrayAdapter<String>)msg.obj;
7392                        mAutoCompletePopup.setAdapter(adapter);
7393                    }
7394                    break;
7395
7396                case LONG_PRESS_CENTER:
7397                    // as this is shared by keydown and trackballdown, reset all
7398                    // the states
7399                    mGotCenterDown = false;
7400                    mTrackballDown = false;
7401                    mWebView.performLongClick();
7402                    break;
7403
7404                case WEBCORE_NEED_TOUCH_EVENTS:
7405                    mInputDispatcher.setWebKitWantsTouchEvents(msg.arg1 != 0);
7406                    break;
7407
7408                case REQUEST_KEYBOARD:
7409                    if (msg.arg1 == 0) {
7410                        hideSoftKeyboard();
7411                    } else {
7412                        displaySoftKeyboard(false);
7413                    }
7414                    break;
7415
7416                case DRAG_HELD_MOTIONLESS:
7417                    mHeldMotionless = MOTIONLESS_TRUE;
7418                    invalidate();
7419                    break;
7420
7421                case SCREEN_ON:
7422                    mWebView.setKeepScreenOn(msg.arg1 == 1);
7423                    break;
7424
7425                case EXIT_FULLSCREEN_VIDEO:
7426                    if (mHTML5VideoViewProxy != null) {
7427                        mHTML5VideoViewProxy.exitFullScreenVideo();
7428                    }
7429                    break;
7430
7431                case SHOW_FULLSCREEN: {
7432                    View view = (View) msg.obj;
7433                    int orientation = msg.arg1;
7434                    int npp = msg.arg2;
7435
7436                    if (inFullScreenMode()) {
7437                        Log.w(LOGTAG, "Should not have another full screen.");
7438                        dismissFullScreenMode();
7439                    }
7440                    mFullScreenHolder = new PluginFullScreenHolder(WebViewClassic.this, orientation, npp);
7441                    mFullScreenHolder.setContentView(view);
7442                    mFullScreenHolder.show();
7443                    invalidate();
7444
7445                    break;
7446                }
7447                case HIDE_FULLSCREEN:
7448                    dismissFullScreenMode();
7449                    break;
7450
7451                case SHOW_RECT_MSG_ID: {
7452                    WebViewCore.ShowRectData data = (WebViewCore.ShowRectData) msg.obj;
7453                    int left = contentToViewX(data.mLeft);
7454                    int width = contentToViewDimension(data.mWidth);
7455                    int maxWidth = contentToViewDimension(data.mContentWidth);
7456                    int viewWidth = getViewWidth();
7457                    int x = (int) (left + data.mXPercentInDoc * width -
7458                                   data.mXPercentInView * viewWidth);
7459                    if (DebugFlags.WEB_VIEW) {
7460                        Log.v(LOGTAG, "showRectMsg=(left=" + left + ",width=" +
7461                              width + ",maxWidth=" + maxWidth +
7462                              ",viewWidth=" + viewWidth + ",x="
7463                              + x + ",xPercentInDoc=" + data.mXPercentInDoc +
7464                              ",xPercentInView=" + data.mXPercentInView+ ")");
7465                    }
7466                    // use the passing content width to cap x as the current
7467                    // mContentWidth may not be updated yet
7468                    x = Math.max(0,
7469                            (Math.min(maxWidth, x + viewWidth)) - viewWidth);
7470                    int top = contentToViewY(data.mTop);
7471                    int height = contentToViewDimension(data.mHeight);
7472                    int maxHeight = contentToViewDimension(data.mContentHeight);
7473                    int viewHeight = getViewHeight();
7474                    int y = (int) (top + data.mYPercentInDoc * height -
7475                                   data.mYPercentInView * viewHeight);
7476                    if (DebugFlags.WEB_VIEW) {
7477                        Log.v(LOGTAG, "showRectMsg=(top=" + top + ",height=" +
7478                              height + ",maxHeight=" + maxHeight +
7479                              ",viewHeight=" + viewHeight + ",y="
7480                              + y + ",yPercentInDoc=" + data.mYPercentInDoc +
7481                              ",yPercentInView=" + data.mYPercentInView+ ")");
7482                    }
7483                    // use the passing content height to cap y as the current
7484                    // mContentHeight may not be updated yet
7485                    y = Math.max(0,
7486                            (Math.min(maxHeight, y + viewHeight) - viewHeight));
7487                    // We need to take into account the visible title height
7488                    // when scrolling since y is an absolute view position.
7489                    y = Math.max(0, y - getVisibleTitleHeightImpl());
7490                    mWebView.scrollTo(x, y);
7491                    }
7492                    break;
7493
7494                case CENTER_FIT_RECT:
7495                    centerFitRect((Rect)msg.obj);
7496                    break;
7497
7498                case SET_SCROLLBAR_MODES:
7499                    mHorizontalScrollBarMode = msg.arg1;
7500                    mVerticalScrollBarMode = msg.arg2;
7501                    break;
7502
7503                case FOCUS_NODE_CHANGED:
7504                    mIsEditingText = (msg.arg1 == mFieldPointer);
7505                    if (mAutoCompletePopup != null && !mIsEditingText) {
7506                        mAutoCompletePopup.clearAdapter();
7507                    }
7508                    // fall through to HIT_TEST_RESULT
7509                case HIT_TEST_RESULT:
7510                    WebKitHitTest hit = (WebKitHitTest) msg.obj;
7511                    mFocusedNode = hit;
7512                    setTouchHighlightRects(hit);
7513                    setHitTestResult(hit);
7514                    break;
7515
7516                case SAVE_WEBARCHIVE_FINISHED:
7517                    SaveWebArchiveMessage saveMessage = (SaveWebArchiveMessage)msg.obj;
7518                    if (saveMessage.mCallback != null) {
7519                        saveMessage.mCallback.onReceiveValue(saveMessage.mResultFile);
7520                    }
7521                    break;
7522
7523                case SET_AUTOFILLABLE:
7524                    mAutoFillData = (WebViewCore.AutoFillData) msg.obj;
7525                    if (mInputConnection != null) {
7526                        mInputConnection.setAutoFillable(mAutoFillData.getQueryId());
7527                        mAutoCompletePopup.setAutoFillQueryId(mAutoFillData.getQueryId());
7528                    }
7529                    break;
7530
7531                case AUTOFILL_COMPLETE:
7532                    if (mAutoCompletePopup != null) {
7533                        ArrayList<String> pastEntries = new ArrayList<String>();
7534                        mAutoCompletePopup.setAdapter(new ArrayAdapter<String>(
7535                                mContext,
7536                                com.android.internal.R.layout.web_text_view_dropdown,
7537                                pastEntries));
7538                    }
7539                    break;
7540
7541                case COPY_TO_CLIPBOARD:
7542                    copyToClipboard((String) msg.obj);
7543                    break;
7544
7545                case INIT_EDIT_FIELD:
7546                    if (mInputConnection != null) {
7547                        TextFieldInitData initData = (TextFieldInitData) msg.obj;
7548                        mTextGeneration = 0;
7549                        mFieldPointer = initData.mFieldPointer;
7550                        mInputConnection.initEditorInfo(initData);
7551                        mInputConnection.setTextAndKeepSelection(initData.mText);
7552                        mEditTextContentBounds.set(initData.mContentBounds);
7553                        mEditTextLayerId = initData.mNodeLayerId;
7554                        nativeMapLayerRect(mNativeClass, mEditTextLayerId,
7555                                mEditTextContentBounds);
7556                        mEditTextContent.set(initData.mClientRect);
7557                        relocateAutoCompletePopup();
7558                    }
7559                    break;
7560
7561                case REPLACE_TEXT:{
7562                    String text = (String)msg.obj;
7563                    int start = msg.arg1;
7564                    int end = msg.arg2;
7565                    int cursorPosition = start + text.length();
7566                    replaceTextfieldText(start, end, text,
7567                            cursorPosition, cursorPosition);
7568                    selectionDone();
7569                    break;
7570                }
7571
7572                case UPDATE_MATCH_COUNT: {
7573                    WebViewCore.FindAllRequest request = (WebViewCore.FindAllRequest)msg.obj;
7574                    if (request == null) {
7575                        if (mFindCallback != null) {
7576                            mFindCallback.updateMatchCount(0, 0, true);
7577                        }
7578                    } else if (request == mFindRequest) {
7579                        int matchCount, matchIndex;
7580                        synchronized (mFindRequest) {
7581                            matchCount = request.mMatchCount;
7582                            matchIndex = request.mMatchIndex;
7583                        }
7584                        if (mFindCallback != null) {
7585                            mFindCallback.updateMatchCount(matchIndex, matchCount, false);
7586                        }
7587                        if (mFindListener != null) {
7588                            mFindListener.onFindResultReceived(matchIndex, matchCount, true);
7589                        }
7590                    }
7591                    break;
7592                }
7593
7594                case CLEAR_CARET_HANDLE:
7595                    if (mIsCaretSelection) {
7596                        selectionDone();
7597                    }
7598                    break;
7599
7600                case KEY_PRESS:
7601                    sendBatchableInputMessage(EventHub.KEY_PRESS, msg.arg1, 0, null);
7602                    break;
7603
7604                case RELOCATE_AUTO_COMPLETE_POPUP:
7605                    relocateAutoCompletePopup();
7606                    break;
7607
7608                case AUTOFILL_FORM:
7609                    mWebViewCore.sendMessage(EventHub.AUTOFILL_FORM,
7610                            msg.arg1, /* unused */0);
7611                    break;
7612
7613                case EDIT_TEXT_SIZE_CHANGED:
7614                    if (msg.arg1 == mFieldPointer) {
7615                        mEditTextContent.set((Rect)msg.obj);
7616                    }
7617                    break;
7618
7619                case SHOW_CARET_HANDLE:
7620                    if (!mSelectingText && mIsEditingText && mIsCaretSelection) {
7621                        setupWebkitSelect();
7622                        resetCaretTimer();
7623                        showPasteWindow();
7624                    }
7625                    break;
7626
7627                case UPDATE_CONTENT_BOUNDS:
7628                    mEditTextContentBounds.set((Rect) msg.obj);
7629                    nativeMapLayerRect(mNativeClass, mEditTextLayerId,
7630                            mEditTextContentBounds);
7631                    break;
7632
7633                case SCROLL_EDIT_TEXT:
7634                    scrollEditWithCursor();
7635                    break;
7636
7637                case SCROLL_HANDLE_INTO_VIEW:
7638                    scrollDraggedSelectionHandleIntoView();
7639                    break;
7640
7641                default:
7642                    super.handleMessage(msg);
7643                    break;
7644            }
7645        }
7646
7647        @Override
7648        public Looper getUiLooper() {
7649            return getLooper();
7650        }
7651
7652        @Override
7653        public void dispatchUiEvent(MotionEvent event, int eventType, int flags) {
7654            onHandleUiEvent(event, eventType, flags);
7655        }
7656
7657        @Override
7658        public Context getContext() {
7659            return WebViewClassic.this.getContext();
7660        }
7661
7662        @Override
7663        public boolean shouldInterceptTouchEvent(MotionEvent event) {
7664            if (!mSelectingText) {
7665                return false;
7666            }
7667            ensureSelectionHandles();
7668            int y = Math.round(event.getY() - getTitleHeight() + getScrollY());
7669            int x = Math.round(event.getX() + getScrollX());
7670            boolean isPressingHandle;
7671            if (mIsCaretSelection) {
7672                isPressingHandle = mSelectHandleCenter.getBounds()
7673                        .contains(x, y);
7674            } else {
7675                isPressingHandle =
7676                        mSelectHandleBaseBounds.contains(x, y)
7677                        || mSelectHandleExtentBounds.contains(x, y);
7678            }
7679            return isPressingHandle;
7680        }
7681
7682        @Override
7683        public void showTapHighlight(boolean show) {
7684            if (mShowTapHighlight != show) {
7685                mShowTapHighlight = show;
7686                invalidate();
7687            }
7688        }
7689
7690        @Override
7691        public void clearPreviousHitTest() {
7692            setHitTestResult(null);
7693        }
7694    }
7695
7696    private void setHitTestTypeFromUrl(String url) {
7697        String substr = null;
7698        if (url.startsWith(SCHEME_GEO)) {
7699            mInitialHitTestResult.setType(HitTestResult.GEO_TYPE);
7700            substr = url.substring(SCHEME_GEO.length());
7701        } else if (url.startsWith(SCHEME_TEL)) {
7702            mInitialHitTestResult.setType(HitTestResult.PHONE_TYPE);
7703            substr = url.substring(SCHEME_TEL.length());
7704        } else if (url.startsWith(SCHEME_MAILTO)) {
7705            mInitialHitTestResult.setType(HitTestResult.EMAIL_TYPE);
7706            substr = url.substring(SCHEME_MAILTO.length());
7707        } else {
7708            mInitialHitTestResult.setType(HitTestResult.SRC_ANCHOR_TYPE);
7709            mInitialHitTestResult.setExtra(url);
7710            return;
7711        }
7712        try {
7713            mInitialHitTestResult.setExtra(URLDecoder.decode(substr, "UTF-8"));
7714        } catch (Throwable e) {
7715            Log.w(LOGTAG, "Failed to decode URL! " + substr, e);
7716            mInitialHitTestResult.setType(HitTestResult.UNKNOWN_TYPE);
7717        }
7718    }
7719
7720    private void setHitTestResult(WebKitHitTest hit) {
7721        if (hit == null) {
7722            mInitialHitTestResult = null;
7723            return;
7724        }
7725        mInitialHitTestResult = new HitTestResult();
7726        if (hit.mLinkUrl != null) {
7727            setHitTestTypeFromUrl(hit.mLinkUrl);
7728            if (hit.mImageUrl != null
7729                    && mInitialHitTestResult.getType() == HitTestResult.SRC_ANCHOR_TYPE) {
7730                mInitialHitTestResult.setType(HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
7731                mInitialHitTestResult.setExtra(hit.mImageUrl);
7732            }
7733        } else if (hit.mImageUrl != null) {
7734            mInitialHitTestResult.setType(HitTestResult.IMAGE_TYPE);
7735            mInitialHitTestResult.setExtra(hit.mImageUrl);
7736        } else if (hit.mEditable) {
7737            mInitialHitTestResult.setType(HitTestResult.EDIT_TEXT_TYPE);
7738        } else if (hit.mIntentUrl != null) {
7739            setHitTestTypeFromUrl(hit.mIntentUrl);
7740        }
7741    }
7742
7743    private boolean shouldDrawHighlightRect() {
7744        if (mFocusedNode == null || mInitialHitTestResult == null) {
7745            return false;
7746        }
7747        if (mTouchHighlightRegion.isEmpty()) {
7748            return false;
7749        }
7750        if (mFocusedNode.mHasFocus && !mWebView.isInTouchMode()) {
7751            return mDrawCursorRing && !mFocusedNode.mEditable;
7752        }
7753        if (mFocusedNode.mHasFocus && mFocusedNode.mEditable) {
7754            return false;
7755        }
7756        return mShowTapHighlight;
7757    }
7758
7759
7760    private FocusTransitionDrawable mFocusTransition = null;
7761    static class FocusTransitionDrawable extends Drawable {
7762        Region mPreviousRegion;
7763        Region mNewRegion;
7764        float mProgress = 0;
7765        WebViewClassic mWebView;
7766        Paint mPaint;
7767        int mMaxAlpha;
7768        Point mTranslate;
7769
7770        public FocusTransitionDrawable(WebViewClassic view) {
7771            mWebView = view;
7772            mPaint = new Paint(mWebView.mTouchHightlightPaint);
7773            mMaxAlpha = mPaint.getAlpha();
7774        }
7775
7776        @Override
7777        public void setColorFilter(ColorFilter cf) {
7778        }
7779
7780        @Override
7781        public void setAlpha(int alpha) {
7782        }
7783
7784        @Override
7785        public int getOpacity() {
7786            return 0;
7787        }
7788
7789        public void setProgress(float p) {
7790            mProgress = p;
7791            if (mWebView.mFocusTransition == this) {
7792                if (mProgress == 1f)
7793                    mWebView.mFocusTransition = null;
7794                mWebView.invalidate();
7795            }
7796        }
7797
7798        public float getProgress() {
7799            return mProgress;
7800        }
7801
7802        @Override
7803        public void draw(Canvas canvas) {
7804            if (mTranslate == null) {
7805                Rect bounds = mPreviousRegion.getBounds();
7806                Point from = new Point(bounds.centerX(), bounds.centerY());
7807                mNewRegion.getBounds(bounds);
7808                Point to = new Point(bounds.centerX(), bounds.centerY());
7809                mTranslate = new Point(from.x - to.x, from.y - to.y);
7810            }
7811            int alpha = (int) (mProgress * mMaxAlpha);
7812            RegionIterator iter = new RegionIterator(mPreviousRegion);
7813            Rect r = new Rect();
7814            mPaint.setAlpha(mMaxAlpha - alpha);
7815            float tx = mTranslate.x * mProgress;
7816            float ty = mTranslate.y * mProgress;
7817            int save = canvas.save(Canvas.MATRIX_SAVE_FLAG);
7818            canvas.translate(-tx, -ty);
7819            while (iter.next(r)) {
7820                canvas.drawRect(r, mPaint);
7821            }
7822            canvas.restoreToCount(save);
7823            iter = new RegionIterator(mNewRegion);
7824            r = new Rect();
7825            mPaint.setAlpha(alpha);
7826            save = canvas.save(Canvas.MATRIX_SAVE_FLAG);
7827            tx = mTranslate.x - tx;
7828            ty = mTranslate.y - ty;
7829            canvas.translate(tx, ty);
7830            while (iter.next(r)) {
7831                canvas.drawRect(r, mPaint);
7832            }
7833            canvas.restoreToCount(save);
7834        }
7835    };
7836
7837    private boolean shouldAnimateTo(WebKitHitTest hit) {
7838        // TODO: Don't be annoying or throw out the animation entirely
7839        return false;
7840    }
7841
7842    private void setTouchHighlightRects(WebKitHitTest hit) {
7843        FocusTransitionDrawable transition = null;
7844        if (shouldAnimateTo(hit)) {
7845            transition = new FocusTransitionDrawable(this);
7846        }
7847        Rect[] rects = hit != null ? hit.mTouchRects : null;
7848        if (!mTouchHighlightRegion.isEmpty()) {
7849            mWebView.invalidate(mTouchHighlightRegion.getBounds());
7850            if (transition != null) {
7851                transition.mPreviousRegion = new Region(mTouchHighlightRegion);
7852            }
7853            mTouchHighlightRegion.setEmpty();
7854        }
7855        if (rects != null) {
7856            mTouchHightlightPaint.setColor(hit.mTapHighlightColor);
7857            for (Rect rect : rects) {
7858                Rect viewRect = contentToViewRect(rect);
7859                // some sites, like stories in nytimes.com, set
7860                // mouse event handler in the top div. It is not
7861                // user friendly to highlight the div if it covers
7862                // more than half of the screen.
7863                if (viewRect.width() < getWidth() >> 1
7864                        || viewRect.height() < getHeight() >> 1) {
7865                    mTouchHighlightRegion.union(viewRect);
7866                } else if (DebugFlags.WEB_VIEW) {
7867                    Log.d(LOGTAG, "Skip the huge selection rect:"
7868                            + viewRect);
7869                }
7870            }
7871            mWebView.invalidate(mTouchHighlightRegion.getBounds());
7872            if (transition != null && transition.mPreviousRegion != null) {
7873                transition.mNewRegion = new Region(mTouchHighlightRegion);
7874                mFocusTransition = transition;
7875                ObjectAnimator animator = ObjectAnimator.ofFloat(
7876                        mFocusTransition, "progress", 1f);
7877                animator.start();
7878            }
7879        }
7880    }
7881
7882    // Interface to allow the profiled WebView to hook the page swap notifications.
7883    public interface PageSwapDelegate {
7884        void onPageSwapOccurred(boolean notifyAnimationStarted);
7885    }
7886
7887    long mLastSwapTime;
7888    double mAverageSwapFps;
7889
7890    /** Called by JNI when pages are swapped (only occurs with hardware
7891     * acceleration) */
7892    protected void pageSwapCallback(boolean notifyAnimationStarted) {
7893        if (DebugFlags.MEASURE_PAGE_SWAP_FPS) {
7894            long now = System.currentTimeMillis();
7895            long diff = now - mLastSwapTime;
7896            mAverageSwapFps = ((1000.0 / diff) + mAverageSwapFps) / 2;
7897            Log.d(LOGTAG, "page swap fps: " + mAverageSwapFps);
7898            mLastSwapTime = now;
7899        }
7900        mWebViewCore.resumeWebKitDraw();
7901        if (notifyAnimationStarted) {
7902            mWebViewCore.sendMessage(EventHub.NOTIFY_ANIMATION_STARTED);
7903        }
7904        if (mWebView instanceof PageSwapDelegate) {
7905            // This provides a hook for ProfiledWebView to observe the tile page swaps.
7906            ((PageSwapDelegate) mWebView).onPageSwapOccurred(notifyAnimationStarted);
7907        }
7908
7909        if (mPictureListener != null) {
7910            // trigger picture listener for hardware layers. Software layers are
7911            // triggered in setNewPicture
7912            mPictureListener.onNewPicture(getWebView(), capturePicture());
7913        }
7914    }
7915
7916    void setNewPicture(final WebViewCore.DrawData draw, boolean updateBaseLayer) {
7917        if (mNativeClass == 0) {
7918            if (mDelaySetPicture != null) {
7919                throw new IllegalStateException("Tried to setNewPicture with"
7920                        + " a delay picture already set! (memory leak)");
7921            }
7922            // Not initialized yet, delay set
7923            mDelaySetPicture = draw;
7924            return;
7925        }
7926        WebViewCore.ViewState viewState = draw.mViewState;
7927        boolean isPictureAfterFirstLayout = viewState != null;
7928
7929        if (updateBaseLayer) {
7930            setBaseLayer(draw.mBaseLayer,
7931                    getSettings().getShowVisualIndicator(),
7932                    isPictureAfterFirstLayout);
7933        }
7934        final Point viewSize = draw.mViewSize;
7935        // We update the layout (i.e. request a layout from the
7936        // view system) if the last view size that we sent to
7937        // WebCore matches the view size of the picture we just
7938        // received in the fixed dimension.
7939        final boolean updateLayout = viewSize.x == mLastWidthSent
7940                && viewSize.y == mLastHeightSent;
7941        // Don't send scroll event for picture coming from webkit,
7942        // since the new picture may cause a scroll event to override
7943        // the saved history scroll position.
7944        mSendScrollEvent = false;
7945        recordNewContentSize(draw.mContentSize.x,
7946                draw.mContentSize.y, updateLayout);
7947        if (isPictureAfterFirstLayout) {
7948            // Reset the last sent data here since dealing with new page.
7949            mLastWidthSent = 0;
7950            mZoomManager.onFirstLayout(draw);
7951            int scrollX = viewState.mShouldStartScrolledRight
7952                    ? getContentWidth() : viewState.mScrollX;
7953            int scrollY = viewState.mScrollY;
7954            contentScrollTo(scrollX, scrollY, false);
7955            if (!mDrawHistory) {
7956                // As we are on a new page, hide the keyboard
7957                hideSoftKeyboard();
7958            }
7959        }
7960        mSendScrollEvent = true;
7961
7962        int functor = 0;
7963        boolean forceInval = isPictureAfterFirstLayout;
7964        ViewRootImpl viewRoot = mWebView.getViewRootImpl();
7965        if (mWebView.isHardwareAccelerated()
7966                && mWebView.getLayerType() != View.LAYER_TYPE_SOFTWARE
7967                && viewRoot != null) {
7968            functor = nativeGetDrawGLFunction(mNativeClass);
7969            if (functor != 0) {
7970                // force an invalidate if functor attach not successful
7971                forceInval |= !viewRoot.attachFunctor(functor);
7972            }
7973        }
7974
7975        if (functor == 0
7976                || forceInval
7977                || mWebView.getLayerType() != View.LAYER_TYPE_NONE) {
7978            // invalidate the screen so that the next repaint will show new content
7979            // TODO: partial invalidate
7980            mWebView.invalidate();
7981        }
7982
7983        // update the zoom information based on the new picture
7984        if (mZoomManager.onNewPicture(draw))
7985            invalidate();
7986
7987        if (isPictureAfterFirstLayout) {
7988            mViewManager.postReadyToDrawAll();
7989        }
7990        scrollEditWithCursor();
7991
7992        if (mPictureListener != null) {
7993            if (!mWebView.isHardwareAccelerated()
7994                    || mWebView.getLayerType() == View.LAYER_TYPE_SOFTWARE) {
7995                // trigger picture listener for software layers. Hardware layers are
7996                // triggered in pageSwapCallback
7997                mPictureListener.onNewPicture(getWebView(), capturePicture());
7998            }
7999        }
8000    }
8001
8002    /**
8003     * Used when receiving messages for REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID
8004     * and UPDATE_TEXT_SELECTION_MSG_ID.
8005     */
8006    private void updateTextSelectionFromMessage(int nodePointer,
8007            int textGeneration, WebViewCore.TextSelectionData data) {
8008        if (textGeneration == mTextGeneration) {
8009            if (mInputConnection != null && mFieldPointer == nodePointer) {
8010                mInputConnection.setSelection(data.mStart, data.mEnd);
8011            }
8012        }
8013        nativeSetTextSelection(mNativeClass, data.mSelectTextPtr);
8014
8015        if ((data.mSelectionReason == TextSelectionData.REASON_ACCESSIBILITY_INJECTOR)
8016                || (!mSelectingText && data.mStart != data.mEnd
8017                        && data.mSelectionReason != TextSelectionData.REASON_SELECT_WORD)) {
8018            selectionDone();
8019            mShowTextSelectionExtra = true;
8020            invalidate();
8021            return;
8022        }
8023
8024        if (data.mSelectTextPtr != 0 &&
8025                (data.mStart != data.mEnd ||
8026                (mFieldPointer == nodePointer && mFieldPointer != 0) ||
8027                (nodePointer == 0 && data.mStart == 0 && data.mEnd == 0))) {
8028            mIsEditingText = (mFieldPointer == nodePointer) && nodePointer != 0;
8029            mIsCaretSelection = (data.mStart == data.mEnd && nodePointer != 0);
8030            if (mIsCaretSelection &&
8031                    (mInputConnection == null ||
8032                    mInputConnection.getEditable().length() == 0)) {
8033                // There's no text, don't show caret handle.
8034                selectionDone();
8035            } else {
8036                if (!mSelectingText) {
8037                    setupWebkitSelect();
8038                } else {
8039                    syncSelectionCursors();
8040                }
8041                animateHandles();
8042                if (mIsCaretSelection) {
8043                    resetCaretTimer();
8044                }
8045            }
8046        } else {
8047            selectionDone();
8048        }
8049        invalidate();
8050    }
8051
8052    private void scrollEditText(int scrollX, int scrollY) {
8053        // Scrollable edit text. Scroll it.
8054        float maxScrollX = getMaxTextScrollX();
8055        float scrollPercentX = ((float)scrollX)/maxScrollX;
8056        mEditTextContent.offsetTo(-scrollX, -scrollY);
8057        mWebViewCore.removeMessages(EventHub.SCROLL_TEXT_INPUT);
8058        mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT, 0,
8059                scrollY, (Float)scrollPercentX);
8060        animateHandles();
8061    }
8062
8063    private void beginTextBatch() {
8064        mIsBatchingTextChanges = true;
8065    }
8066
8067    private void commitTextBatch() {
8068        if (mWebViewCore != null) {
8069            mWebViewCore.sendMessages(mBatchedTextChanges);
8070        }
8071        mBatchedTextChanges.clear();
8072        mIsBatchingTextChanges = false;
8073    }
8074
8075    void sendBatchableInputMessage(int what, int arg1, int arg2,
8076            Object obj) {
8077        if (mWebViewCore == null) {
8078            return;
8079        }
8080        Message message = Message.obtain(null, what, arg1, arg2, obj);
8081        if (mIsBatchingTextChanges) {
8082            mBatchedTextChanges.add(message);
8083        } else {
8084            mWebViewCore.sendMessage(message);
8085        }
8086    }
8087
8088    // Class used to use a dropdown for a <select> element
8089    private class InvokeListBox implements Runnable {
8090        // Whether the listbox allows multiple selection.
8091        private boolean     mMultiple;
8092        // Passed in to a list with multiple selection to tell
8093        // which items are selected.
8094        private int[]       mSelectedArray;
8095        // Passed in to a list with single selection to tell
8096        // where the initial selection is.
8097        private int         mSelection;
8098
8099        private Container[] mContainers;
8100
8101        // Need these to provide stable ids to my ArrayAdapter,
8102        // which normally does not have stable ids. (Bug 1250098)
8103        private class Container extends Object {
8104            /**
8105             * Possible values for mEnabled.  Keep in sync with OptionStatus in
8106             * WebViewCore.cpp
8107             */
8108            final static int OPTGROUP = -1;
8109            final static int OPTION_DISABLED = 0;
8110            final static int OPTION_ENABLED = 1;
8111
8112            String  mString;
8113            int     mEnabled;
8114            int     mId;
8115
8116            @Override
8117            public String toString() {
8118                return mString;
8119            }
8120        }
8121
8122        /**
8123         *  Subclass ArrayAdapter so we can disable OptionGroupLabels,
8124         *  and allow filtering.
8125         */
8126        private class MyArrayListAdapter extends ArrayAdapter<Container> {
8127            public MyArrayListAdapter() {
8128                super(WebViewClassic.this.mContext,
8129                        mMultiple ? com.android.internal.R.layout.select_dialog_multichoice :
8130                        com.android.internal.R.layout.webview_select_singlechoice,
8131                        mContainers);
8132            }
8133
8134            @Override
8135            public View getView(int position, View convertView,
8136                    ViewGroup parent) {
8137                // Always pass in null so that we will get a new CheckedTextView
8138                // Otherwise, an item which was previously used as an <optgroup>
8139                // element (i.e. has no check), could get used as an <option>
8140                // element, which needs a checkbox/radio, but it would not have
8141                // one.
8142                convertView = super.getView(position, null, parent);
8143                Container c = item(position);
8144                if (c != null && Container.OPTION_ENABLED != c.mEnabled) {
8145                    // ListView does not draw dividers between disabled and
8146                    // enabled elements.  Use a LinearLayout to provide dividers
8147                    LinearLayout layout = new LinearLayout(mContext);
8148                    layout.setOrientation(LinearLayout.VERTICAL);
8149                    if (position > 0) {
8150                        View dividerTop = new View(mContext);
8151                        dividerTop.setBackgroundResource(
8152                                android.R.drawable.divider_horizontal_bright);
8153                        layout.addView(dividerTop);
8154                    }
8155
8156                    if (Container.OPTGROUP == c.mEnabled) {
8157                        // Currently select_dialog_multichoice uses CheckedTextViews.
8158                        // If that changes, the class cast will no longer be valid.
8159                        if (mMultiple) {
8160                            Assert.assertTrue(convertView instanceof CheckedTextView);
8161                            ((CheckedTextView) convertView).setCheckMarkDrawable(null);
8162                        }
8163                    } else {
8164                        // c.mEnabled == Container.OPTION_DISABLED
8165                        // Draw the disabled element in a disabled state.
8166                        convertView.setEnabled(false);
8167                    }
8168
8169                    layout.addView(convertView);
8170                    if (position < getCount() - 1) {
8171                        View dividerBottom = new View(mContext);
8172                        dividerBottom.setBackgroundResource(
8173                                android.R.drawable.divider_horizontal_bright);
8174                        layout.addView(dividerBottom);
8175                    }
8176                    return layout;
8177                }
8178                return convertView;
8179            }
8180
8181            @Override
8182            public boolean hasStableIds() {
8183                // AdapterView's onChanged method uses this to determine whether
8184                // to restore the old state.  Return false so that the old (out
8185                // of date) state does not replace the new, valid state.
8186                return false;
8187            }
8188
8189            private Container item(int position) {
8190                if (position < 0 || position >= getCount()) {
8191                    return null;
8192                }
8193                return getItem(position);
8194            }
8195
8196            @Override
8197            public long getItemId(int position) {
8198                Container item = item(position);
8199                if (item == null) {
8200                    return -1;
8201                }
8202                return item.mId;
8203            }
8204
8205            @Override
8206            public boolean areAllItemsEnabled() {
8207                return false;
8208            }
8209
8210            @Override
8211            public boolean isEnabled(int position) {
8212                Container item = item(position);
8213                if (item == null) {
8214                    return false;
8215                }
8216                return Container.OPTION_ENABLED == item.mEnabled;
8217            }
8218        }
8219
8220        private InvokeListBox(String[] array, int[] enabled, int[] selected) {
8221            mMultiple = true;
8222            mSelectedArray = selected;
8223
8224            int length = array.length;
8225            mContainers = new Container[length];
8226            for (int i = 0; i < length; i++) {
8227                mContainers[i] = new Container();
8228                mContainers[i].mString = array[i];
8229                mContainers[i].mEnabled = enabled[i];
8230                mContainers[i].mId = i;
8231            }
8232        }
8233
8234        private InvokeListBox(String[] array, int[] enabled, int selection) {
8235            mSelection = selection;
8236            mMultiple = false;
8237
8238            int length = array.length;
8239            mContainers = new Container[length];
8240            for (int i = 0; i < length; i++) {
8241                mContainers[i] = new Container();
8242                mContainers[i].mString = array[i];
8243                mContainers[i].mEnabled = enabled[i];
8244                mContainers[i].mId = i;
8245            }
8246        }
8247
8248        /*
8249         * Whenever the data set changes due to filtering, this class ensures
8250         * that the checked item remains checked.
8251         */
8252        private class SingleDataSetObserver extends DataSetObserver {
8253            private long        mCheckedId;
8254            private ListView    mListView;
8255            private Adapter     mAdapter;
8256
8257            /*
8258             * Create a new observer.
8259             * @param id The ID of the item to keep checked.
8260             * @param l ListView for getting and clearing the checked states
8261             * @param a Adapter for getting the IDs
8262             */
8263            public SingleDataSetObserver(long id, ListView l, Adapter a) {
8264                mCheckedId = id;
8265                mListView = l;
8266                mAdapter = a;
8267            }
8268
8269            @Override
8270            public void onChanged() {
8271                // The filter may have changed which item is checked.  Find the
8272                // item that the ListView thinks is checked.
8273                int position = mListView.getCheckedItemPosition();
8274                long id = mAdapter.getItemId(position);
8275                if (mCheckedId != id) {
8276                    // Clear the ListView's idea of the checked item, since
8277                    // it is incorrect
8278                    mListView.clearChoices();
8279                    // Search for mCheckedId.  If it is in the filtered list,
8280                    // mark it as checked
8281                    int count = mAdapter.getCount();
8282                    for (int i = 0; i < count; i++) {
8283                        if (mAdapter.getItemId(i) == mCheckedId) {
8284                            mListView.setItemChecked(i, true);
8285                            break;
8286                        }
8287                    }
8288                }
8289            }
8290        }
8291
8292        @Override
8293        public void run() {
8294            if (mWebViewCore == null
8295                    || getWebView().getWindowToken() == null
8296                    || getWebView().getViewRootImpl() == null) {
8297                // We've been detached and/or destroyed since this was posted
8298                return;
8299            }
8300            final ListView listView = (ListView) LayoutInflater.from(mContext)
8301                    .inflate(com.android.internal.R.layout.select_dialog, null);
8302            final MyArrayListAdapter adapter = new MyArrayListAdapter();
8303            AlertDialog.Builder b = new AlertDialog.Builder(mContext)
8304                    .setView(listView).setCancelable(true)
8305                    .setInverseBackgroundForced(true);
8306
8307            if (mMultiple) {
8308                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
8309                    @Override
8310                    public void onClick(DialogInterface dialog, int which) {
8311                        mWebViewCore.sendMessage(
8312                                EventHub.LISTBOX_CHOICES,
8313                                adapter.getCount(), 0,
8314                                listView.getCheckedItemPositions());
8315                    }});
8316                b.setNegativeButton(android.R.string.cancel,
8317                        new DialogInterface.OnClickListener() {
8318                    @Override
8319                    public void onClick(DialogInterface dialog, int which) {
8320                        mWebViewCore.sendMessage(
8321                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
8322                }});
8323            }
8324            mListBoxDialog = b.create();
8325            listView.setAdapter(adapter);
8326            listView.setFocusableInTouchMode(true);
8327            // There is a bug (1250103) where the checks in a ListView with
8328            // multiple items selected are associated with the positions, not
8329            // the ids, so the items do not properly retain their checks when
8330            // filtered.  Do not allow filtering on multiple lists until
8331            // that bug is fixed.
8332
8333            listView.setTextFilterEnabled(!mMultiple);
8334            if (mMultiple) {
8335                listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
8336                int length = mSelectedArray.length;
8337                for (int i = 0; i < length; i++) {
8338                    listView.setItemChecked(mSelectedArray[i], true);
8339                }
8340            } else {
8341                listView.setOnItemClickListener(new OnItemClickListener() {
8342                    @Override
8343                    public void onItemClick(AdapterView<?> parent, View v,
8344                            int position, long id) {
8345                        // Rather than sending the message right away, send it
8346                        // after the page regains focus.
8347                        mListBoxMessage = Message.obtain(null,
8348                                EventHub.SINGLE_LISTBOX_CHOICE, (int) id, 0);
8349                        if (mListBoxDialog != null) {
8350                            mListBoxDialog.dismiss();
8351                            mListBoxDialog = null;
8352                        }
8353                    }
8354                });
8355                if (mSelection != -1) {
8356                    listView.setSelection(mSelection);
8357                    listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
8358                    listView.setItemChecked(mSelection, true);
8359                    DataSetObserver observer = new SingleDataSetObserver(
8360                            adapter.getItemId(mSelection), listView, adapter);
8361                    adapter.registerDataSetObserver(observer);
8362                }
8363            }
8364            mListBoxDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
8365                @Override
8366                public void onCancel(DialogInterface dialog) {
8367                    mWebViewCore.sendMessage(
8368                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
8369                    mListBoxDialog = null;
8370                }
8371            });
8372            mListBoxDialog.show();
8373        }
8374    }
8375
8376    private Message mListBoxMessage;
8377
8378    /*
8379     * Request a dropdown menu for a listbox with multiple selection.
8380     *
8381     * @param array Labels for the listbox.
8382     * @param enabledArray  State for each element in the list.  See static
8383     *      integers in Container class.
8384     * @param selectedArray Which positions are initally selected.
8385     */
8386    void requestListBox(String[] array, int[] enabledArray, int[]
8387            selectedArray) {
8388        mPrivateHandler.post(
8389                new InvokeListBox(array, enabledArray, selectedArray));
8390    }
8391
8392    /*
8393     * Request a dropdown menu for a listbox with single selection or a single
8394     * <select> element.
8395     *
8396     * @param array Labels for the listbox.
8397     * @param enabledArray  State for each element in the list.  See static
8398     *      integers in Container class.
8399     * @param selection Which position is initally selected.
8400     */
8401    void requestListBox(String[] array, int[] enabledArray, int selection) {
8402        mPrivateHandler.post(
8403                new InvokeListBox(array, enabledArray, selection));
8404    }
8405
8406    private int getScaledMaxXScroll() {
8407        int width;
8408        if (mHeightCanMeasure == false) {
8409            width = getViewWidth() / 4;
8410        } else {
8411            Rect visRect = new Rect();
8412            calcOurVisibleRect(visRect);
8413            width = visRect.width() / 2;
8414        }
8415        // FIXME the divisor should be retrieved from somewhere
8416        return viewToContentX(width);
8417    }
8418
8419    private int getScaledMaxYScroll() {
8420        int height;
8421        if (mHeightCanMeasure == false) {
8422            height = getViewHeight() / 4;
8423        } else {
8424            Rect visRect = new Rect();
8425            calcOurVisibleRect(visRect);
8426            height = visRect.height() / 2;
8427        }
8428        // FIXME the divisor should be retrieved from somewhere
8429        // the closest thing today is hard-coded into ScrollView.java
8430        // (from ScrollView.java, line 363)   int maxJump = height/2;
8431        return Math.round(height * mZoomManager.getInvScale());
8432    }
8433
8434    /**
8435     * Called by JNI to invalidate view
8436     */
8437    private void viewInvalidate() {
8438        invalidate();
8439    }
8440
8441    /**
8442     * Pass the key directly to the page.  This assumes that
8443     * nativePageShouldHandleShiftAndArrows() returned true.
8444     */
8445    private void letPageHandleNavKey(int keyCode, long time, boolean down, int metaState) {
8446        int keyEventAction;
8447        if (down) {
8448            keyEventAction = KeyEvent.ACTION_DOWN;
8449        } else {
8450            keyEventAction = KeyEvent.ACTION_UP;
8451        }
8452
8453        KeyEvent event = new KeyEvent(time, time, keyEventAction, keyCode,
8454                1, (metaState & KeyEvent.META_SHIFT_ON)
8455                | (metaState & KeyEvent.META_ALT_ON)
8456                | (metaState & KeyEvent.META_SYM_ON)
8457                , KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0);
8458        sendKeyEvent(event);
8459    }
8460
8461    private void sendKeyEvent(KeyEvent event) {
8462        int direction = 0;
8463        switch (event.getKeyCode()) {
8464        case KeyEvent.KEYCODE_DPAD_DOWN:
8465            direction = View.FOCUS_DOWN;
8466            break;
8467        case KeyEvent.KEYCODE_DPAD_UP:
8468            direction = View.FOCUS_UP;
8469            break;
8470        case KeyEvent.KEYCODE_DPAD_LEFT:
8471            direction = View.FOCUS_LEFT;
8472            break;
8473        case KeyEvent.KEYCODE_DPAD_RIGHT:
8474            direction = View.FOCUS_RIGHT;
8475            break;
8476        case KeyEvent.KEYCODE_TAB:
8477            direction = event.isShiftPressed() ? View.FOCUS_BACKWARD : View.FOCUS_FORWARD;
8478            break;
8479        }
8480        if (direction != 0 && mWebView.focusSearch(direction) == null) {
8481            // Can't take focus in that direction
8482            direction = 0;
8483        }
8484        int eventHubAction = EventHub.KEY_UP;
8485        if (event.getAction() == KeyEvent.ACTION_DOWN) {
8486            eventHubAction = EventHub.KEY_DOWN;
8487            int sound = keyCodeToSoundsEffect(event.getKeyCode());
8488            if (sound != 0) {
8489                mWebView.playSoundEffect(sound);
8490            }
8491        }
8492        sendBatchableInputMessage(eventHubAction, direction, 0, event);
8493    }
8494
8495    /**
8496     * See {@link WebView#setBackgroundColor(int)}
8497     */
8498    @Override
8499    public void setBackgroundColor(int color) {
8500        mBackgroundColor = color;
8501        mWebViewCore.sendMessage(EventHub.SET_BACKGROUND_COLOR, color);
8502    }
8503
8504    /**
8505     * Enable the communication b/t the webView and VideoViewProxy
8506     *
8507     * only used by the Browser
8508     */
8509    public void setHTML5VideoViewProxy(HTML5VideoViewProxy proxy) {
8510        mHTML5VideoViewProxy = proxy;
8511    }
8512
8513    /**
8514     * Set the time to wait between passing touches to WebCore. See also the
8515     * TOUCH_SENT_INTERVAL member for further discussion.
8516     *
8517     * This is only used by the DRT test application.
8518     */
8519    public void setTouchInterval(int interval) {
8520        mCurrentTouchInterval = interval;
8521    }
8522
8523    /**
8524     * Copy text into the clipboard. This is called indirectly from
8525     * WebViewCore.
8526     * @param text The text to put into the clipboard.
8527     */
8528    private void copyToClipboard(String text) {
8529        ClipboardManager cm = (ClipboardManager)mContext
8530                .getSystemService(Context.CLIPBOARD_SERVICE);
8531        ClipData clip = ClipData.newPlainText(getTitle(), text);
8532        cm.setPrimaryClip(clip);
8533    }
8534
8535    /*package*/ void autoFillForm(int autoFillQueryId) {
8536        mPrivateHandler.obtainMessage(AUTOFILL_FORM, autoFillQueryId, 0)
8537            .sendToTarget();
8538    }
8539
8540    /* package */ ViewManager getViewManager() {
8541        return mViewManager;
8542    }
8543
8544    /** send content invalidate */
8545    protected void contentInvalidateAll() {
8546        if (mWebViewCore != null && !mBlockWebkitViewMessages) {
8547            mWebViewCore.sendMessage(EventHub.CONTENT_INVALIDATE_ALL);
8548        }
8549    }
8550
8551    /** discard all textures from tiles. Used in Profiled WebView */
8552    public void discardAllTextures() {
8553        nativeDiscardAllTextures();
8554    }
8555
8556    @Override
8557    public void setLayerType(int layerType, Paint paint) {
8558        updateHwAccelerated();
8559    }
8560
8561    @Override
8562    public void preDispatchDraw(Canvas canvas) {
8563        // no-op for WebViewClassic.
8564    }
8565
8566    private void updateHwAccelerated() {
8567        if (mNativeClass == 0) {
8568            return;
8569        }
8570        boolean hwAccelerated = false;
8571        if (mWebView.isHardwareAccelerated()
8572                && mWebView.getLayerType() != View.LAYER_TYPE_SOFTWARE) {
8573            hwAccelerated = true;
8574        }
8575
8576        // result is of type LayerAndroid::InvalidateFlags, non zero means invalidate/redraw
8577        int result = nativeSetHwAccelerated(mNativeClass, hwAccelerated);
8578        if (mWebViewCore != null && !mBlockWebkitViewMessages && result != 0) {
8579            mWebViewCore.contentDraw();
8580        }
8581    }
8582
8583    /**
8584     * Begin collecting per-tile profiling data
8585     *
8586     * only used by profiling tests
8587     */
8588    public void tileProfilingStart() {
8589        nativeTileProfilingStart();
8590    }
8591    /**
8592     * Return per-tile profiling data
8593     *
8594     * only used by profiling tests
8595     */
8596    public float tileProfilingStop() {
8597        return nativeTileProfilingStop();
8598    }
8599
8600    /** only used by profiling tests */
8601    public void tileProfilingClear() {
8602        nativeTileProfilingClear();
8603    }
8604    /** only used by profiling tests */
8605    public int tileProfilingNumFrames() {
8606        return nativeTileProfilingNumFrames();
8607    }
8608    /** only used by profiling tests */
8609    public int tileProfilingNumTilesInFrame(int frame) {
8610        return nativeTileProfilingNumTilesInFrame(frame);
8611    }
8612    /** only used by profiling tests */
8613    public int tileProfilingGetInt(int frame, int tile, String key) {
8614        return nativeTileProfilingGetInt(frame, tile, key);
8615    }
8616    /** only used by profiling tests */
8617    public float tileProfilingGetFloat(int frame, int tile, String key) {
8618        return nativeTileProfilingGetFloat(frame, tile, key);
8619    }
8620
8621    /**
8622     * Checks the focused content for an editable text field. This can be
8623     * text input or ContentEditable.
8624     * @return true if the focused item is an editable text field.
8625     */
8626    boolean focusCandidateIsEditableText() {
8627        if (mFocusedNode != null) {
8628            return mFocusedNode.mEditable;
8629        }
8630        return false;
8631    }
8632
8633    // Called via JNI
8634    private void postInvalidate() {
8635        mWebView.postInvalidate();
8636    }
8637
8638    // Note: must be called before first WebViewClassic is created.
8639    public static void setShouldMonitorWebCoreThread() {
8640        WebViewCore.setShouldMonitorWebCoreThread();
8641    }
8642
8643    @Override
8644    public void dumpViewHierarchyWithProperties(BufferedWriter out, int level) {
8645        int layer = getBaseLayer();
8646        if (layer != 0) {
8647            try {
8648                ByteArrayOutputStream stream = new ByteArrayOutputStream();
8649                ViewStateSerializer.dumpLayerHierarchy(layer, stream, level);
8650                stream.close();
8651                byte[] buf = stream.toByteArray();
8652                out.write(new String(buf, "ascii"));
8653            } catch (IOException e) {}
8654        }
8655    }
8656
8657    @Override
8658    public View findHierarchyView(String className, int hashCode) {
8659        if (mNativeClass == 0) return null;
8660        Picture pic = new Picture();
8661        if (!nativeDumpLayerContentToPicture(mNativeClass, className, hashCode, pic)) {
8662            return null;
8663        }
8664        return new PictureWrapperView(getContext(), pic, mWebView);
8665    }
8666
8667    private static class PictureWrapperView extends View {
8668        Picture mPicture;
8669        WebView mWebView;
8670
8671        public PictureWrapperView(Context context, Picture picture, WebView parent) {
8672            super(context);
8673            mPicture = picture;
8674            mWebView = parent;
8675            setWillNotDraw(false);
8676            setRight(mPicture.getWidth());
8677            setBottom(mPicture.getHeight());
8678        }
8679
8680        @Override
8681        protected void onDraw(Canvas canvas) {
8682            canvas.drawPicture(mPicture);
8683        }
8684
8685        @Override
8686        public boolean post(Runnable action) {
8687            return mWebView.post(action);
8688        }
8689    }
8690
8691    private native void     nativeCreate(int ptr, String drawableDir, boolean isHighEndGfx);
8692    private native void     nativeDebugDump();
8693    private static native void nativeDestroy(int ptr);
8694
8695    private native void nativeDraw(Canvas canvas, RectF visibleRect,
8696            int color, int extra);
8697    private native void     nativeDumpDisplayTree(String urlOrNull);
8698    private native boolean  nativeEvaluateLayersAnimations(int nativeInstance);
8699    private native int      nativeCreateDrawGLFunction(int nativeInstance, Rect invScreenRect,
8700            Rect screenRect, RectF visibleContentRect, float scale, int extras);
8701    private native int      nativeGetDrawGLFunction(int nativeInstance);
8702    private native void     nativeUpdateDrawGLFunction(int nativeInstance, Rect invScreenRect,
8703            Rect screenRect, RectF visibleContentRect, float scale);
8704    private native String   nativeGetSelection();
8705    private native void     nativeSetHeightCanMeasure(boolean measure);
8706    private native boolean  nativeSetBaseLayer(int nativeInstance,
8707            int layer, boolean showVisualIndicator, boolean isPictureAfterFirstLayout,
8708            int scrollingLayer);
8709    private native int      nativeGetBaseLayer(int nativeInstance);
8710    private native void     nativeCopyBaseContentToPicture(Picture pict);
8711    private native boolean     nativeDumpLayerContentToPicture(int nativeInstance,
8712            String className, int layerId, Picture pict);
8713    private native boolean  nativeHasContent();
8714    private native void     nativeStopGL(int ptr);
8715    private native void     nativeDiscardAllTextures();
8716    private native void     nativeTileProfilingStart();
8717    private native float    nativeTileProfilingStop();
8718    private native void     nativeTileProfilingClear();
8719    private native int      nativeTileProfilingNumFrames();
8720    private native int      nativeTileProfilingNumTilesInFrame(int frame);
8721    private native int      nativeTileProfilingGetInt(int frame, int tile, String key);
8722    private native float    nativeTileProfilingGetFloat(int frame, int tile, String key);
8723
8724    private native void     nativeUseHardwareAccelSkia(boolean enabled);
8725
8726    // Returns a pointer to the scrollable LayerAndroid at the given point.
8727    private native int      nativeScrollableLayer(int nativeInstance, int x, int y, Rect scrollRect,
8728            Rect scrollBounds);
8729    /**
8730     * Scroll the specified layer.
8731     * @param nativeInstance Native WebView instance
8732     * @param layer Id of the layer to scroll, as determined by nativeScrollableLayer.
8733     * @param newX Destination x position to which to scroll.
8734     * @param newY Destination y position to which to scroll.
8735     * @return True if the layer is successfully scrolled.
8736     */
8737    private native boolean  nativeScrollLayer(int nativeInstance, int layer, int newX, int newY);
8738    private native void     nativeSetIsScrolling(boolean isScrolling);
8739    private native int      nativeGetBackgroundColor(int nativeInstance);
8740    native boolean  nativeSetProperty(String key, String value);
8741    native String   nativeGetProperty(String key);
8742    /**
8743     * See {@link ComponentCallbacks2} for the trim levels and descriptions
8744     */
8745    private static native void     nativeOnTrimMemory(int level);
8746    private static native void nativeSetPauseDrawing(int instance, boolean pause);
8747    private static native void nativeSetTextSelection(int instance, int selection);
8748    private static native int nativeGetHandleLayerId(int instance, int handle,
8749            Point cursorLocation, QuadF textQuad);
8750    private static native void nativeMapLayerRect(int instance, int layerId,
8751            Rect rect);
8752    // Returns 1 if a layer sync is needed, else 0
8753    private static native int nativeSetHwAccelerated(int instance, boolean hwAccelerated);
8754    private static native void nativeFindMaxVisibleRect(int instance, int layerId,
8755            Rect visibleContentRect);
8756    private static native boolean nativeIsHandleLeft(int instance, int handleId);
8757    private static native boolean nativeIsPointVisible(int instance,
8758            int layerId, int contentX, int contentY);
8759}
8760