WebView.cpp revision d71bb71a2be8c0f7eff98c981a5410aa49e04843
1/*
2 * Copyright 2007, The Android Open Source Project
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *  * Redistributions of source code must retain the above copyright
8 *    notice, this list of conditions and the following disclaimer.
9 *  * Redistributions in binary form must reproduce the above copyright
10 *    notice, this list of conditions and the following disclaimer in the
11 *    documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 */
25
26#define LOG_TAG "webviewglue"
27
28#include "config.h"
29
30#include "AndroidAnimation.h"
31#include "AndroidLog.h"
32#include "BaseLayerAndroid.h"
33#include "BaseRenderer.h"
34#include "DrawExtra.h"
35#include "Frame.h"
36#include "GLWebViewState.h"
37#include "GraphicsJNI.h"
38#include "HTMLInputElement.h"
39#include "IntPoint.h"
40#include "IntRect.h"
41#include "LayerAndroid.h"
42#include "LayerContent.h"
43#include "Node.h"
44#include "utils/Functor.h"
45#include "private/hwui/DrawGlInfo.h"
46#include "PlatformGraphicsContext.h"
47#include "PlatformString.h"
48#include "ScrollableLayerAndroid.h"
49#include "SelectText.h"
50#include "SkCanvas.h"
51#include "SkDumpCanvas.h"
52#include "SkPicture.h"
53#include "SkRect.h"
54#include "SkTime.h"
55#include "TilesManager.h"
56#include "TransferQueue.h"
57#include "WebCoreJni.h"
58#include "WebRequestContext.h"
59#include "WebViewCore.h"
60#include "android_graphics.h"
61
62#ifdef GET_NATIVE_VIEW
63#undef GET_NATIVE_VIEW
64#endif
65
66#define GET_NATIVE_VIEW(env, obj) ((WebView*)env->GetIntField(obj, gWebViewField))
67
68#include <JNIUtility.h>
69#include <JNIHelp.h>
70#include <jni.h>
71#include <androidfw/KeycodeLabels.h>
72#include <wtf/text/AtomicString.h>
73#include <wtf/text/CString.h>
74
75// Free as much as we possible can
76#define TRIM_MEMORY_COMPLETE 80
77// Free a lot (all textures gone)
78#define TRIM_MEMORY_MODERATE 60
79// More moderate free (keep bare minimum to restore quickly-ish - possibly clear all textures)
80#define TRIM_MEMORY_BACKGROUND 40
81// Moderate free (clear cached tiles, keep visible ones)
82#define TRIM_MEMORY_UI_HIDDEN 20
83// Duration to show the pressed cursor ring
84#define PRESSED_STATE_DURATION 400
85
86namespace android {
87
88static jfieldID gWebViewField;
89
90//-------------------------------------
91
92static jmethodID GetJMethod(JNIEnv* env, jclass clazz, const char name[], const char signature[])
93{
94    jmethodID m = env->GetMethodID(clazz, name, signature);
95    ALOG_ASSERT(m, "Could not find method %s", name);
96    return m;
97}
98
99//-------------------------------------
100// This class provides JNI for making calls into native code from the UI side
101// of the multi-threaded WebView.
102class WebView
103{
104public:
105enum FrameCachePermission {
106    DontAllowNewer,
107    AllowNewer
108};
109
110#define DRAW_EXTRAS_SIZE 2
111enum DrawExtras { // keep this in sync with WebView.java
112    DrawExtrasNone = 0,
113    DrawExtrasSelection = 1,
114    DrawExtrasCursorRing = 2
115};
116
117struct JavaGlue {
118    jweak       m_obj;
119    jmethodID   m_scrollBy;
120    jmethodID   m_getScaledMaxXScroll;
121    jmethodID   m_getScaledMaxYScroll;
122    jmethodID   m_getVisibleRect;
123    jmethodID   m_viewInvalidate;
124    jmethodID   m_viewInvalidateRect;
125    jmethodID   m_postInvalidateDelayed;
126    jmethodID   m_pageSwapCallback;
127    jfieldID    m_rectLeft;
128    jfieldID    m_rectTop;
129    jmethodID   m_rectWidth;
130    jmethodID   m_rectHeight;
131    jfieldID    m_quadFP1;
132    jfieldID    m_quadFP2;
133    jfieldID    m_quadFP3;
134    jfieldID    m_quadFP4;
135    AutoJObject object(JNIEnv* env) {
136        return getRealObject(env, m_obj);
137    }
138} m_javaGlue;
139
140WebView(JNIEnv* env, jobject javaWebView, int viewImpl, WTF::String drawableDir,
141        bool isHighEndGfx)
142    : m_isHighEndGfx(isHighEndGfx)
143{
144    memset(m_extras, 0, DRAW_EXTRAS_SIZE * sizeof(DrawExtra*));
145    jclass clazz = env->FindClass("android/webkit/WebViewClassic");
146    m_javaGlue.m_obj = env->NewWeakGlobalRef(javaWebView);
147    m_javaGlue.m_scrollBy = GetJMethod(env, clazz, "setContentScrollBy", "(IIZ)Z");
148    m_javaGlue.m_getScaledMaxXScroll = GetJMethod(env, clazz, "getScaledMaxXScroll", "()I");
149    m_javaGlue.m_getScaledMaxYScroll = GetJMethod(env, clazz, "getScaledMaxYScroll", "()I");
150    m_javaGlue.m_getVisibleRect = GetJMethod(env, clazz, "sendOurVisibleRect", "()Landroid/graphics/Rect;");
151    m_javaGlue.m_viewInvalidate = GetJMethod(env, clazz, "viewInvalidate", "()V");
152    m_javaGlue.m_viewInvalidateRect = GetJMethod(env, clazz, "viewInvalidate", "(IIII)V");
153    m_javaGlue.m_postInvalidateDelayed = GetJMethod(env, clazz,
154        "viewInvalidateDelayed", "(JIIII)V");
155    m_javaGlue.m_pageSwapCallback = GetJMethod(env, clazz, "pageSwapCallback", "(Z)V");
156    env->DeleteLocalRef(clazz);
157
158    jclass rectClass = env->FindClass("android/graphics/Rect");
159    ALOG_ASSERT(rectClass, "Could not find Rect class");
160    m_javaGlue.m_rectLeft = env->GetFieldID(rectClass, "left", "I");
161    m_javaGlue.m_rectTop = env->GetFieldID(rectClass, "top", "I");
162    m_javaGlue.m_rectWidth = GetJMethod(env, rectClass, "width", "()I");
163    m_javaGlue.m_rectHeight = GetJMethod(env, rectClass, "height", "()I");
164    env->DeleteLocalRef(rectClass);
165
166    jclass quadFClass = env->FindClass("android/webkit/QuadF");
167    ALOG_ASSERT(quadFClass, "Could not find QuadF class");
168    m_javaGlue.m_quadFP1 = env->GetFieldID(quadFClass, "p1", "Landroid/graphics/PointF;");
169    m_javaGlue.m_quadFP2 = env->GetFieldID(quadFClass, "p2", "Landroid/graphics/PointF;");
170    m_javaGlue.m_quadFP3 = env->GetFieldID(quadFClass, "p3", "Landroid/graphics/PointF;");
171    m_javaGlue.m_quadFP4 = env->GetFieldID(quadFClass, "p4", "Landroid/graphics/PointF;");
172    env->DeleteLocalRef(quadFClass);
173
174    env->SetIntField(javaWebView, gWebViewField, (jint)this);
175    m_viewImpl = (WebViewCore*) viewImpl;
176    m_generation = 0;
177    m_heightCanMeasure = false;
178    m_lastDx = 0;
179    m_lastDxTime = 0;
180    m_baseLayer = 0;
181    m_glDrawFunctor = 0;
182    m_isDrawingPaused = false;
183#if USE(ACCELERATED_COMPOSITING)
184    m_glWebViewState = 0;
185#endif
186}
187
188~WebView()
189{
190    if (m_javaGlue.m_obj)
191    {
192        JNIEnv* env = JSC::Bindings::getJNIEnv();
193        env->DeleteWeakGlobalRef(m_javaGlue.m_obj);
194        m_javaGlue.m_obj = 0;
195    }
196#if USE(ACCELERATED_COMPOSITING)
197    // We must remove the m_glWebViewState prior to deleting m_baseLayer. If we
198    // do not remove it here, we risk having BaseTiles trying to paint using a
199    // deallocated base layer.
200    stopGL();
201#endif
202    SkSafeUnref(m_baseLayer);
203    delete m_glDrawFunctor;
204    for (int i = 0; i < DRAW_EXTRAS_SIZE; i++)
205        delete m_extras[i];
206}
207
208DrawExtra* getDrawExtra(DrawExtras extras)
209{
210    if (extras == DrawExtrasNone)
211        return 0;
212    return m_extras[extras - 1];
213}
214
215void stopGL()
216{
217#if USE(ACCELERATED_COMPOSITING)
218    delete m_glWebViewState;
219    m_glWebViewState = 0;
220#endif
221}
222
223WebViewCore* getWebViewCore() const {
224    return m_viewImpl;
225}
226
227void scrollRectOnScreen(const IntRect& rect)
228{
229    if (rect.isEmpty())
230        return;
231    int dx = 0;
232    int left = rect.x();
233    int right = rect.maxX();
234    if (left < m_visibleRect.fLeft)
235        dx = left - m_visibleRect.fLeft;
236    // Only scroll right if the entire width can fit on screen.
237    else if (right > m_visibleRect.fRight
238            && right - left < m_visibleRect.width())
239        dx = right - m_visibleRect.fRight;
240    int dy = 0;
241    int top = rect.y();
242    int bottom = rect.maxY();
243    if (top < m_visibleRect.fTop)
244        dy = top - m_visibleRect.fTop;
245    // Only scroll down if the entire height can fit on screen
246    else if (bottom > m_visibleRect.fBottom
247            && bottom - top < m_visibleRect.height())
248        dy = bottom - m_visibleRect.fBottom;
249    if ((dx|dy) == 0 || !scrollBy(dx, dy))
250        return;
251    viewInvalidate();
252}
253
254int drawGL(WebCore::IntRect& viewRect, WebCore::IntRect* invalRect,
255        WebCore::IntRect& webViewRect, int titleBarHeight,
256        WebCore::IntRect& clip, float scale, int extras, bool shouldDraw)
257{
258#if USE(ACCELERATED_COMPOSITING)
259    if (!m_baseLayer)
260        return 0;
261
262    if (!m_glWebViewState) {
263        TilesManager::instance()->setHighEndGfx(m_isHighEndGfx);
264        m_glWebViewState = new GLWebViewState();
265        m_glWebViewState->setBaseLayer(m_baseLayer, false, true);
266    }
267
268    DrawExtra* extra = getDrawExtra((DrawExtras) extras);
269
270    m_glWebViewState->glExtras()->setDrawExtra(extra);
271
272    // Make sure we have valid coordinates. We might not have valid coords
273    // if the zoom manager is still initializing. We will be redrawn
274    // once the correct scale is set
275    if (!m_visibleRect.isFinite())
276        return 0;
277    bool treesSwapped = false;
278    bool newTreeHasAnim = false;
279    int ret = m_glWebViewState->drawGL(viewRect, m_visibleRect, invalRect,
280                                        webViewRect, titleBarHeight, clip, scale,
281                                        &treesSwapped, &newTreeHasAnim, shouldDraw);
282    if (treesSwapped) {
283        ALOG_ASSERT(m_javaGlue.m_obj, "A java object was not associated with this native WebView!");
284        JNIEnv* env = JSC::Bindings::getJNIEnv();
285        AutoJObject javaObject = m_javaGlue.object(env);
286        if (javaObject.get()) {
287            env->CallVoidMethod(javaObject.get(), m_javaGlue.m_pageSwapCallback, newTreeHasAnim);
288            checkException(env);
289        }
290    }
291    return m_isDrawingPaused ? 0 : ret;
292#endif
293    return 0;
294}
295
296PictureSet* draw(SkCanvas* canvas, SkColor bgColor, DrawExtras extras, bool split)
297{
298    PictureSet* ret = 0;
299    if (!m_baseLayer) {
300        canvas->drawColor(bgColor);
301        return ret;
302    }
303
304    // draw the content of the base layer first
305    LayerContent* content = m_baseLayer->content();
306    int sc = canvas->save(SkCanvas::kClip_SaveFlag);
307    canvas->clipRect(SkRect::MakeLTRB(0, 0, content->width(),
308                content->height()), SkRegion::kDifference_Op);
309    Color c = m_baseLayer->getBackgroundColor();
310    canvas->drawColor(SkColorSetARGBInline(c.alpha(), c.red(), c.green(), c.blue()));
311    canvas->restoreToCount(sc);
312
313    // call this to be sure we've adjusted for any scrolling or animations
314    // before we actually draw
315    m_baseLayer->updateLayerPositions(m_visibleRect);
316    m_baseLayer->updatePositions();
317
318    // We have to set the canvas' matrix on the base layer
319    // (to have fixed layers work as intended)
320    SkAutoCanvasRestore restore(canvas, true);
321    m_baseLayer->setMatrix(canvas->getTotalMatrix());
322    canvas->resetMatrix();
323    m_baseLayer->draw(canvas, getDrawExtra(extras));
324
325    return ret;
326}
327
328int getScaledMaxXScroll()
329{
330    ALOG_ASSERT(m_javaGlue.m_obj, "A java object was not associated with this native WebView!");
331    JNIEnv* env = JSC::Bindings::getJNIEnv();
332    AutoJObject javaObject = m_javaGlue.object(env);
333    if (!javaObject.get())
334        return 0;
335    int result = env->CallIntMethod(javaObject.get(), m_javaGlue.m_getScaledMaxXScroll);
336    checkException(env);
337    return result;
338}
339
340int getScaledMaxYScroll()
341{
342    ALOG_ASSERT(m_javaGlue.m_obj, "A java object was not associated with this native WebView!");
343    JNIEnv* env = JSC::Bindings::getJNIEnv();
344    AutoJObject javaObject = m_javaGlue.object(env);
345    if (!javaObject.get())
346        return 0;
347    int result = env->CallIntMethod(javaObject.get(), m_javaGlue.m_getScaledMaxYScroll);
348    checkException(env);
349    return result;
350}
351
352IntRect getVisibleRect()
353{
354    IntRect rect;
355    ALOG_ASSERT(m_javaGlue.m_obj, "A java object was not associated with this native WebView!");
356    JNIEnv* env = JSC::Bindings::getJNIEnv();
357    AutoJObject javaObject = m_javaGlue.object(env);
358    if (!javaObject.get())
359        return rect;
360    jobject jRect = env->CallObjectMethod(javaObject.get(), m_javaGlue.m_getVisibleRect);
361    checkException(env);
362    rect.setX(env->GetIntField(jRect, m_javaGlue.m_rectLeft));
363    checkException(env);
364    rect.setY(env->GetIntField(jRect, m_javaGlue.m_rectTop));
365    checkException(env);
366    rect.setWidth(env->CallIntMethod(jRect, m_javaGlue.m_rectWidth));
367    checkException(env);
368    rect.setHeight(env->CallIntMethod(jRect, m_javaGlue.m_rectHeight));
369    checkException(env);
370    env->DeleteLocalRef(jRect);
371    checkException(env);
372    return rect;
373}
374
375#if USE(ACCELERATED_COMPOSITING)
376static const ScrollableLayerAndroid* findScrollableLayer(
377    const LayerAndroid* parent, int x, int y, SkIRect* foundBounds) {
378    SkRect bounds;
379    parent->bounds(&bounds);
380    // Check the parent bounds first; this will clip to within a masking layer's
381    // bounds.
382    if (parent->masksToBounds() && !bounds.contains(x, y))
383        return 0;
384    // Move the hit test local to parent.
385    x -= bounds.fLeft;
386    y -= bounds.fTop;
387    int count = parent->countChildren();
388    while (count--) {
389        const LayerAndroid* child = parent->getChild(count);
390        const ScrollableLayerAndroid* result = findScrollableLayer(child, x, y,
391            foundBounds);
392        if (result) {
393            foundBounds->offset(bounds.fLeft, bounds.fTop);
394            if (parent->masksToBounds()) {
395                if (bounds.width() < foundBounds->width())
396                    foundBounds->fRight = foundBounds->fLeft + bounds.width();
397                if (bounds.height() < foundBounds->height())
398                    foundBounds->fBottom = foundBounds->fTop + bounds.height();
399            }
400            return result;
401        }
402    }
403    if (parent->contentIsScrollable()) {
404        foundBounds->set(0, 0, bounds.width(), bounds.height());
405        return static_cast<const ScrollableLayerAndroid*>(parent);
406    }
407    return 0;
408}
409#endif
410
411int scrollableLayer(int x, int y, SkIRect* layerRect, SkIRect* bounds)
412{
413#if USE(ACCELERATED_COMPOSITING)
414    if (!m_baseLayer)
415        return 0;
416    const ScrollableLayerAndroid* result = findScrollableLayer(m_baseLayer, x, y, bounds);
417    if (result) {
418        result->getScrollRect(layerRect);
419        return result->uniqueId();
420    }
421#endif
422    return 0;
423}
424
425void scrollLayer(int layerId, int x, int y)
426{
427    if (m_glWebViewState)
428        m_glWebViewState->scrollLayer(layerId, x, y);
429}
430
431void setHeightCanMeasure(bool measure)
432{
433    m_heightCanMeasure = measure;
434}
435
436String getSelection()
437{
438    SelectText* select = static_cast<SelectText*>(
439            getDrawExtra(WebView::DrawExtrasSelection));
440    if (select)
441        return select->getText();
442    return String();
443}
444
445bool scrollBy(int dx, int dy)
446{
447    ALOG_ASSERT(m_javaGlue.m_obj, "A java object was not associated with this native WebView!");
448
449    JNIEnv* env = JSC::Bindings::getJNIEnv();
450    AutoJObject javaObject = m_javaGlue.object(env);
451    if (!javaObject.get())
452        return false;
453    bool result = env->CallBooleanMethod(javaObject.get(), m_javaGlue.m_scrollBy, dx, dy, true);
454    checkException(env);
455    return result;
456}
457
458void setIsScrolling(bool isScrolling)
459{
460#if USE(ACCELERATED_COMPOSITING)
461    if (m_glWebViewState)
462        m_glWebViewState->setIsScrolling(isScrolling);
463#endif
464}
465
466void viewInvalidate()
467{
468    JNIEnv* env = JSC::Bindings::getJNIEnv();
469    AutoJObject javaObject = m_javaGlue.object(env);
470    if (!javaObject.get())
471        return;
472    env->CallVoidMethod(javaObject.get(), m_javaGlue.m_viewInvalidate);
473    checkException(env);
474}
475
476void viewInvalidateRect(int l, int t, int r, int b)
477{
478    JNIEnv* env = JSC::Bindings::getJNIEnv();
479    AutoJObject javaObject = m_javaGlue.object(env);
480    if (!javaObject.get())
481        return;
482    env->CallVoidMethod(javaObject.get(), m_javaGlue.m_viewInvalidateRect, l, r, t, b);
483    checkException(env);
484}
485
486void postInvalidateDelayed(int64_t delay, const WebCore::IntRect& bounds)
487{
488    JNIEnv* env = JSC::Bindings::getJNIEnv();
489    AutoJObject javaObject = m_javaGlue.object(env);
490    if (!javaObject.get())
491        return;
492    env->CallVoidMethod(javaObject.get(), m_javaGlue.m_postInvalidateDelayed,
493        delay, bounds.x(), bounds.y(), bounds.maxX(), bounds.maxY());
494    checkException(env);
495}
496
497#if ENABLE(ANDROID_OVERFLOW_SCROLL)
498static void copyScrollPositionRecursive(const LayerAndroid* from,
499                                        LayerAndroid* root)
500{
501    if (!from || !root)
502        return;
503    for (int i = 0; i < from->countChildren(); i++) {
504        const LayerAndroid* l = from->getChild(i);
505        if (l->contentIsScrollable()) {
506            const SkPoint& pos = l->getPosition();
507            LayerAndroid* match = root->findById(l->uniqueId());
508            if (match && match->contentIsScrollable())
509                match->setPosition(pos.fX, pos.fY);
510        }
511        copyScrollPositionRecursive(l, root);
512    }
513}
514#endif
515
516BaseLayerAndroid* getBaseLayer() const { return m_baseLayer; }
517
518bool setBaseLayer(BaseLayerAndroid* newBaseLayer, SkRegion& inval, bool showVisualIndicator,
519                  bool isPictureAfterFirstLayout)
520{
521    bool queueFull = false;
522#if USE(ACCELERATED_COMPOSITING)
523    if (m_glWebViewState) {
524        // TODO: mark as inval on webkit side
525        if (newBaseLayer)
526            newBaseLayer->markAsDirty(inval);
527        queueFull = m_glWebViewState->setBaseLayer(newBaseLayer, showVisualIndicator,
528                                                   isPictureAfterFirstLayout);
529    }
530#endif
531
532#if ENABLE(ANDROID_OVERFLOW_SCROLL)
533    if (newBaseLayer) {
534        // TODO: the below tree position copies are only necessary in software rendering
535        copyScrollPositionRecursive(m_baseLayer, newBaseLayer);
536    }
537#endif
538    SkSafeUnref(m_baseLayer);
539    m_baseLayer = newBaseLayer;
540
541    return queueFull;
542}
543
544void replaceBaseContent(PictureSet* set)
545{
546    if (!m_baseLayer)
547        return;
548    // TODO: remove the split picture codepath
549    delete set;
550}
551
552void copyBaseContentToPicture(SkPicture* picture)
553{
554    if (!m_baseLayer)
555        return;
556    LayerContent* content = m_baseLayer->content();
557    content->draw(picture->beginRecording(content->width(), content->height(),
558                                          SkPicture::kUsePathBoundsForClip_RecordingFlag));
559    picture->endRecording();
560}
561
562bool hasContent() {
563    if (!m_baseLayer)
564        return false;
565    return !m_baseLayer->content()->isEmpty();
566}
567
568void setFunctor(Functor* functor) {
569    delete m_glDrawFunctor;
570    m_glDrawFunctor = functor;
571}
572
573Functor* getFunctor() {
574    return m_glDrawFunctor;
575}
576
577void setVisibleRect(SkRect& visibleRect) {
578    m_visibleRect = visibleRect;
579}
580
581void setDrawExtra(DrawExtra *extra, DrawExtras type)
582{
583    if (type == DrawExtrasNone)
584        return;
585    DrawExtra* old = m_extras[type - 1];
586    m_extras[type - 1] = extra;
587    if (old != extra) {
588        delete old;
589    }
590}
591
592void setTextSelection(SelectText *selection) {
593    setDrawExtra(selection, DrawExtrasSelection);
594}
595
596const TransformationMatrix* getLayerTransform(int layerId) {
597    if (layerId != -1 && m_baseLayer) {
598        LayerAndroid* layer = m_baseLayer->findById(layerId);
599        // We need to make sure the drawTransform is up to date as this is
600        // called before a draw() or drawGL()
601        if (layer) {
602            m_baseLayer->updateLayerPositions(m_visibleRect);
603            return layer->drawTransform();
604        }
605    }
606    return 0;
607}
608
609int getHandleLayerId(SelectText::HandleId handleId, SkIPoint& cursorPoint,
610        FloatQuad& textBounds) {
611    SelectText* selectText = static_cast<SelectText*>(getDrawExtra(DrawExtrasSelection));
612    if (!selectText || !m_baseLayer)
613        return -1;
614    int layerId = selectText->caretLayerId(handleId);
615    IntRect cursorRect = selectText->caretRect(handleId);
616    IntRect textRect = selectText->textRect(handleId);
617    // Rects exclude the last pixel on right/bottom. We want only included pixels.
618    cursorPoint.set(cursorRect.x(), cursorRect.maxY() - 1);
619    textRect.setHeight(std::max(1, textRect.height() - 1));
620    textRect.setWidth(std::max(1, textRect.width() - 1));
621    textBounds = FloatQuad(textRect);
622
623    const TransformationMatrix* transform = getLayerTransform(layerId);
624    if (transform) {
625        // We're overloading the concept of Rect to be just the two
626        // points (bottom-left and top-right.
627        cursorPoint = transform->mapPoint(cursorPoint);
628        textBounds = transform->mapQuad(textBounds);
629    }
630    return layerId;
631}
632
633void mapLayerRect(int layerId, SkIRect& rect) {
634    const TransformationMatrix* transform = getLayerTransform(layerId);
635    if (transform)
636        transform->mapRect(rect);
637}
638
639void floatQuadToQuadF(JNIEnv* env, const FloatQuad& nativeTextQuad,
640        jobject textQuad)
641{
642    jobject p1 = env->GetObjectField(textQuad, m_javaGlue.m_quadFP1);
643    jobject p2 = env->GetObjectField(textQuad, m_javaGlue.m_quadFP2);
644    jobject p3 = env->GetObjectField(textQuad, m_javaGlue.m_quadFP3);
645    jobject p4 = env->GetObjectField(textQuad, m_javaGlue.m_quadFP4);
646    GraphicsJNI::point_to_jpointf(nativeTextQuad.p1(), env, p1);
647    GraphicsJNI::point_to_jpointf(nativeTextQuad.p2(), env, p2);
648    GraphicsJNI::point_to_jpointf(nativeTextQuad.p3(), env, p3);
649    GraphicsJNI::point_to_jpointf(nativeTextQuad.p4(), env, p4);
650    env->DeleteLocalRef(p1);
651    env->DeleteLocalRef(p2);
652    env->DeleteLocalRef(p3);
653    env->DeleteLocalRef(p4);
654}
655
656// This is called when WebView switches rendering modes in a more permanent fashion
657// such as when the layer type is set or the view is attached/detached from the window
658int setHwAccelerated(bool hwAccelerated) {
659    if (!m_glWebViewState)
660        return 0;
661    LayerAndroid* root = m_baseLayer;
662    if (root)
663        return root->setHwAccelerated(hwAccelerated);
664    return 0;
665}
666
667    bool m_isDrawingPaused;
668private: // local state for WebView
669    // private to getFrameCache(); other functions operate in a different thread
670    WebViewCore* m_viewImpl;
671    int m_generation; // associate unique ID with sent kit focus to match with ui
672    // Corresponds to the same-named boolean on the java side.
673    bool m_heightCanMeasure;
674    int m_lastDx;
675    SkMSec m_lastDxTime;
676    DrawExtra* m_extras[DRAW_EXTRAS_SIZE];
677    BaseLayerAndroid* m_baseLayer;
678    Functor* m_glDrawFunctor;
679#if USE(ACCELERATED_COMPOSITING)
680    GLWebViewState* m_glWebViewState;
681#endif
682    SkRect m_visibleRect;
683    bool m_isHighEndGfx;
684}; // end of WebView class
685
686
687/**
688 * This class holds a function pointer and parameters for calling drawGL into a specific
689 * viewport. The pointer to the Functor will be put on a framework display list to be called
690 * when the display list is replayed.
691 */
692class GLDrawFunctor : Functor {
693    public:
694    GLDrawFunctor(WebView* _wvInstance,
695            int (WebView::*_funcPtr)(WebCore::IntRect&, WebCore::IntRect*,
696                    WebCore::IntRect&, int, WebCore::IntRect&, jfloat, jint, bool),
697            WebCore::IntRect _viewRect, float _scale, int _extras) {
698        wvInstance = _wvInstance;
699        funcPtr = _funcPtr;
700        viewRect = _viewRect;
701        scale = _scale;
702        extras = _extras;
703    };
704    status_t operator()(int messageId, void* data) {
705        TRACE_METHOD();
706
707        if (viewRect.isEmpty()) {
708            // NOOP operation if viewport is empty
709            return 0;
710        }
711
712        WebCore::IntRect inval;
713        int titlebarHeight = webViewRect.height() - viewRect.height();
714
715        uirenderer::DrawGlInfo* info = reinterpret_cast<uirenderer::DrawGlInfo*>(data);
716        WebCore::IntRect clip(info->clipLeft, info->clipTop,
717                              info->clipRight - info->clipLeft,
718                              info->clipBottom - info->clipTop);
719
720        WebCore::IntRect localViewRect = viewRect;
721        if (info->isLayer) {
722            // When webview is on a layer, we need to use the viewport relative
723            // to the FBO, rather than the screen(which will use viewRect).
724            localViewRect.setX(clip.x());
725            localViewRect.setY(info->height - clip.y() - clip.height());
726        }
727        bool shouldDraw = (messageId == uirenderer::DrawGlInfo::kModeDraw);
728        // Send the necessary info to the shader.
729        TilesManager::instance()->shader()->setGLDrawInfo(info);
730
731        int returnFlags = (*wvInstance.*funcPtr)(localViewRect, &inval, webViewRect,
732                titlebarHeight, clip, scale, extras, shouldDraw);
733        if ((returnFlags & uirenderer::DrawGlInfo::kStatusDraw) != 0) {
734            IntRect finalInval;
735            if (inval.isEmpty())
736                finalInval = webViewRect;
737            else {
738                finalInval.setX(webViewRect.x() + inval.x());
739                finalInval.setY(webViewRect.y() + titlebarHeight + inval.y());
740                finalInval.setWidth(inval.width());
741                finalInval.setHeight(inval.height());
742            }
743            info->dirtyLeft = finalInval.x();
744            info->dirtyTop = finalInval.y();
745            info->dirtyRight = finalInval.maxX();
746            info->dirtyBottom = finalInval.maxY();
747        }
748        // return 1 if invalidation needed, 2 to request non-drawing functor callback, 0 otherwise
749        ALOGV("returnFlags are %d, shouldDraw %d", returnFlags, shouldDraw);
750        return returnFlags;
751    }
752    void updateRect(WebCore::IntRect& _viewRect) {
753        viewRect = _viewRect;
754    }
755    void updateViewRect(WebCore::IntRect& _viewRect) {
756        webViewRect = _viewRect;
757    }
758    void updateScale(float _scale) {
759        scale = _scale;
760    }
761    private:
762    WebView* wvInstance;
763    int (WebView::*funcPtr)(WebCore::IntRect&, WebCore::IntRect*,
764            WebCore::IntRect&, int, WebCore::IntRect&, float, int, bool);
765    WebCore::IntRect viewRect;
766    WebCore::IntRect webViewRect;
767    jfloat scale;
768    jint extras;
769};
770
771/*
772 * Native JNI methods
773 */
774
775static void nativeCreate(JNIEnv *env, jobject obj, int viewImpl,
776                         jstring drawableDir, jboolean isHighEndGfx)
777{
778    WTF::String dir = jstringToWtfString(env, drawableDir);
779    new WebView(env, obj, viewImpl, dir, isHighEndGfx);
780    // NEED THIS OR SOMETHING LIKE IT!
781    //Release(obj);
782}
783
784static WebCore::IntRect jrect_to_webrect(JNIEnv* env, jobject obj)
785{
786    if (obj) {
787        int L, T, R, B;
788        GraphicsJNI::get_jrect(env, obj, &L, &T, &R, &B);
789        return WebCore::IntRect(L, T, R - L, B - T);
790    } else
791        return WebCore::IntRect();
792}
793
794static SkRect jrectf_to_rect(JNIEnv* env, jobject obj)
795{
796    SkRect rect = SkRect::MakeEmpty();
797    if (obj)
798        GraphicsJNI::jrectf_to_rect(env, obj, &rect);
799    return rect;
800}
801
802static jint nativeDraw(JNIEnv *env, jobject obj, jobject canv,
803        jobject visible, jint color,
804        jint extras, jboolean split) {
805    SkCanvas* canvas = GraphicsJNI::getNativeCanvas(env, canv);
806    WebView* webView = GET_NATIVE_VIEW(env, obj);
807    SkRect visibleRect = jrectf_to_rect(env, visible);
808    webView->setVisibleRect(visibleRect);
809    PictureSet* pictureSet = webView->draw(canvas, color,
810            static_cast<WebView::DrawExtras>(extras), split);
811    return reinterpret_cast<jint>(pictureSet);
812}
813
814static jint nativeGetDrawGLFunction(JNIEnv *env, jobject obj, jint nativeView,
815                                    jobject jrect, jobject jviewrect,
816                                    jobject jvisiblerect,
817                                    jfloat scale, jint extras) {
818    WebCore::IntRect viewRect = jrect_to_webrect(env, jrect);
819    WebView *wvInstance = (WebView*) nativeView;
820    SkRect visibleRect = jrectf_to_rect(env, jvisiblerect);
821    wvInstance->setVisibleRect(visibleRect);
822
823    GLDrawFunctor* functor = new GLDrawFunctor(wvInstance,
824            &android::WebView::drawGL, viewRect, scale, extras);
825    wvInstance->setFunctor((Functor*) functor);
826
827    WebCore::IntRect webViewRect = jrect_to_webrect(env, jviewrect);
828    functor->updateViewRect(webViewRect);
829
830    return (jint)functor;
831}
832
833static void nativeUpdateDrawGLFunction(JNIEnv *env, jobject obj, jobject jrect,
834        jobject jviewrect, jobject jvisiblerect, jfloat scale) {
835    WebView *wvInstance = GET_NATIVE_VIEW(env, obj);
836    if (wvInstance) {
837        GLDrawFunctor* functor = (GLDrawFunctor*) wvInstance->getFunctor();
838        if (functor) {
839            WebCore::IntRect viewRect = jrect_to_webrect(env, jrect);
840            functor->updateRect(viewRect);
841
842            SkRect visibleRect = jrectf_to_rect(env, jvisiblerect);
843            wvInstance->setVisibleRect(visibleRect);
844
845            WebCore::IntRect webViewRect = jrect_to_webrect(env, jviewrect);
846            functor->updateViewRect(webViewRect);
847
848            functor->updateScale(scale);
849        }
850    }
851}
852
853static bool nativeEvaluateLayersAnimations(JNIEnv *env, jobject obj, jint nativeView)
854{
855    // only call in software rendering, initialize and evaluate animations
856#if USE(ACCELERATED_COMPOSITING)
857    BaseLayerAndroid* baseLayer = ((WebView*)nativeView)->getBaseLayer();
858    if (baseLayer) {
859        baseLayer->initAnimations();
860        return baseLayer->evaluateAnimations();
861    }
862#endif
863    return false;
864}
865
866static bool nativeSetBaseLayer(JNIEnv *env, jobject obj, jint nativeView, jint layer, jobject inval,
867                               jboolean showVisualIndicator,
868                               jboolean isPictureAfterFirstLayout)
869{
870    BaseLayerAndroid* layerImpl = reinterpret_cast<BaseLayerAndroid*>(layer);
871    SkRegion invalRegion;
872    if (inval)
873        invalRegion = *GraphicsJNI::getNativeRegion(env, inval);
874    return ((WebView*)nativeView)->setBaseLayer(layerImpl, invalRegion, showVisualIndicator,
875                                                isPictureAfterFirstLayout);
876}
877
878static BaseLayerAndroid* nativeGetBaseLayer(JNIEnv *env, jobject obj)
879{
880    return GET_NATIVE_VIEW(env, obj)->getBaseLayer();
881}
882
883static void nativeReplaceBaseContent(JNIEnv *env, jobject obj, jint content)
884{
885    PictureSet* set = reinterpret_cast<PictureSet*>(content);
886    GET_NATIVE_VIEW(env, obj)->replaceBaseContent(set);
887}
888
889static void nativeCopyBaseContentToPicture(JNIEnv *env, jobject obj, jobject pict)
890{
891    SkPicture* picture = GraphicsJNI::getNativePicture(env, pict);
892    GET_NATIVE_VIEW(env, obj)->copyBaseContentToPicture(picture);
893}
894
895static bool nativeHasContent(JNIEnv *env, jobject obj)
896{
897    return GET_NATIVE_VIEW(env, obj)->hasContent();
898}
899
900static jobject nativeLayerBounds(JNIEnv* env, jobject obj, jint jlayer)
901{
902    SkRect r;
903#if USE(ACCELERATED_COMPOSITING)
904    LayerAndroid* layer = (LayerAndroid*) jlayer;
905    r = layer->bounds();
906#else
907    r.setEmpty();
908#endif
909    SkIRect irect;
910    r.round(&irect);
911    jclass rectClass = env->FindClass("android/graphics/Rect");
912    jmethodID init = env->GetMethodID(rectClass, "<init>", "(IIII)V");
913    jobject rect = env->NewObject(rectClass, init, irect.fLeft, irect.fTop,
914        irect.fRight, irect.fBottom);
915    env->DeleteLocalRef(rectClass);
916    return rect;
917}
918
919static void nativeSetHeightCanMeasure(JNIEnv *env, jobject obj, bool measure)
920{
921    WebView* view = GET_NATIVE_VIEW(env, obj);
922    ALOG_ASSERT(view, "view not set in nativeSetHeightCanMeasure");
923    view->setHeightCanMeasure(measure);
924}
925
926static void nativeDestroy(JNIEnv *env, jobject obj)
927{
928    WebView* view = GET_NATIVE_VIEW(env, obj);
929    ALOGD("nativeDestroy view: %p", view);
930    ALOG_ASSERT(view, "view not set in nativeDestroy");
931    delete view;
932}
933
934static void nativeStopGL(JNIEnv *env, jobject obj)
935{
936    GET_NATIVE_VIEW(env, obj)->stopGL();
937}
938
939static jobject nativeGetSelection(JNIEnv *env, jobject obj)
940{
941    WebView* view = GET_NATIVE_VIEW(env, obj);
942    ALOG_ASSERT(view, "view not set in %s", __FUNCTION__);
943    String selection = view->getSelection();
944    return wtfStringToJstring(env, selection);
945}
946
947static void nativeDiscardAllTextures(JNIEnv *env, jobject obj)
948{
949    //discard all textures for debugging/test purposes, but not gl backing memory
950    bool allTextures = true, deleteGLTextures = false;
951    TilesManager::instance()->discardTextures(allTextures, deleteGLTextures);
952}
953
954static void nativeTileProfilingStart(JNIEnv *env, jobject obj)
955{
956    TilesManager::instance()->getProfiler()->start();
957}
958
959static float nativeTileProfilingStop(JNIEnv *env, jobject obj)
960{
961    return TilesManager::instance()->getProfiler()->stop();
962}
963
964static void nativeTileProfilingClear(JNIEnv *env, jobject obj)
965{
966    TilesManager::instance()->getProfiler()->clear();
967}
968
969static int nativeTileProfilingNumFrames(JNIEnv *env, jobject obj)
970{
971    return TilesManager::instance()->getProfiler()->numFrames();
972}
973
974static int nativeTileProfilingNumTilesInFrame(JNIEnv *env, jobject obj, int frame)
975{
976    return TilesManager::instance()->getProfiler()->numTilesInFrame(frame);
977}
978
979static int nativeTileProfilingGetInt(JNIEnv *env, jobject obj, int frame, int tile, jstring jkey)
980{
981    WTF::String key = jstringToWtfString(env, jkey);
982    TileProfileRecord* record = TilesManager::instance()->getProfiler()->getTile(frame, tile);
983
984    if (key == "left")
985        return record->left;
986    if (key == "top")
987        return record->top;
988    if (key == "right")
989        return record->right;
990    if (key == "bottom")
991        return record->bottom;
992    if (key == "level")
993        return record->level;
994    if (key == "isReady")
995        return record->isReady ? 1 : 0;
996    return -1;
997}
998
999static float nativeTileProfilingGetFloat(JNIEnv *env, jobject obj, int frame, int tile, jstring jkey)
1000{
1001    TileProfileRecord* record = TilesManager::instance()->getProfiler()->getTile(frame, tile);
1002    return record->scale;
1003}
1004
1005#ifdef ANDROID_DUMP_DISPLAY_TREE
1006static void dumpToFile(const char text[], void* file) {
1007    fwrite(text, 1, strlen(text), reinterpret_cast<FILE*>(file));
1008    fwrite("\n", 1, 1, reinterpret_cast<FILE*>(file));
1009}
1010#endif
1011
1012// Return true to view invalidate WebView
1013static bool nativeSetProperty(JNIEnv *env, jobject obj, jstring jkey, jstring jvalue)
1014{
1015    WTF::String key = jstringToWtfString(env, jkey);
1016    WTF::String value = jstringToWtfString(env, jvalue);
1017    if (key == "inverted") {
1018        bool shouldInvert = (value == "true");
1019        TilesManager::instance()->setInvertedScreen(shouldInvert);
1020        return true;
1021    }
1022    else if (key == "inverted_contrast") {
1023        float contrast = value.toFloat();
1024        TilesManager::instance()->setInvertedScreenContrast(contrast);
1025        return true;
1026    }
1027    else if (key == "enable_cpu_upload_path") {
1028        TilesManager::instance()->transferQueue()->setTextureUploadType(
1029            value == "true" ? CpuUpload : GpuUpload);
1030    }
1031    else if (key == "use_minimal_memory") {
1032        TilesManager::instance()->setUseMinimalMemory(value == "true");
1033    }
1034    else if (key == "use_double_buffering") {
1035        TilesManager::instance()->setUseDoubleBuffering(value == "true");
1036    }
1037    else if (key == "tree_updates") {
1038        TilesManager::instance()->clearContentUpdates();
1039    }
1040    return false;
1041}
1042
1043static jstring nativeGetProperty(JNIEnv *env, jobject obj, jstring jkey)
1044{
1045    WTF::String key = jstringToWtfString(env, jkey);
1046    if (key == "tree_updates") {
1047        int updates = TilesManager::instance()->getContentUpdates();
1048        WTF::String wtfUpdates = WTF::String::number(updates);
1049        return wtfStringToJstring(env, wtfUpdates);
1050    }
1051    return 0;
1052}
1053
1054static void nativeOnTrimMemory(JNIEnv *env, jobject obj, jint level)
1055{
1056    if (TilesManager::hardwareAccelerationEnabled()) {
1057        // When we got TRIM_MEMORY_MODERATE or TRIM_MEMORY_COMPLETE, we should
1058        // make sure the transfer queue is empty and then abandon the Surface
1059        // Texture to avoid ANR b/c framework may destroy the EGL context.
1060        // Refer to WindowManagerImpl.java for conditions we followed.
1061        TilesManager* tilesManager = TilesManager::instance();
1062        if (level >= TRIM_MEMORY_MODERATE
1063            && !tilesManager->highEndGfx()) {
1064            ALOGD("OnTrimMemory with EGL Context %p", eglGetCurrentContext());
1065            tilesManager->transferQueue()->emptyQueue();
1066            tilesManager->shader()->cleanupGLResources();
1067            tilesManager->videoLayerManager()->cleanupGLResources();
1068        }
1069
1070        bool freeAllTextures = (level > TRIM_MEMORY_UI_HIDDEN), glTextures = true;
1071        tilesManager->discardTextures(freeAllTextures, glTextures);
1072    }
1073}
1074
1075static void nativeDumpDisplayTree(JNIEnv* env, jobject jwebview, jstring jurl)
1076{
1077#ifdef ANDROID_DUMP_DISPLAY_TREE
1078    WebView* view = GET_NATIVE_VIEW(env, jwebview);
1079    ALOG_ASSERT(view, "view not set in %s", __FUNCTION__);
1080
1081    if (view && view->getWebViewCore()) {
1082        FILE* file = fopen(DISPLAY_TREE_LOG_FILE, "w");
1083        if (file) {
1084            SkFormatDumper dumper(dumpToFile, file);
1085            // dump the URL
1086            if (jurl) {
1087                const char* str = env->GetStringUTFChars(jurl, 0);
1088                SkDebugf("Dumping %s to %s\n", str, DISPLAY_TREE_LOG_FILE);
1089                dumpToFile(str, file);
1090                env->ReleaseStringUTFChars(jurl, str);
1091            }
1092            // now dump the display tree
1093            SkDumpCanvas canvas(&dumper);
1094            // this will playback the picture into the canvas, which will
1095            // spew its contents to the dumper
1096            view->draw(&canvas, 0, WebView::DrawExtrasNone, false);
1097            // we're done with the file now
1098            fwrite("\n", 1, 1, file);
1099            fclose(file);
1100        }
1101#if USE(ACCELERATED_COMPOSITING)
1102        const LayerAndroid* baseLayer = view->getBaseLayer();
1103        if (baseLayer) {
1104          FILE* file = fopen(LAYERS_TREE_LOG_FILE,"w");
1105          if (file) {
1106              baseLayer->dumpLayers(file, 0);
1107              fclose(file);
1108          }
1109        }
1110#endif
1111    }
1112#endif
1113}
1114
1115static int nativeScrollableLayer(JNIEnv* env, jobject jwebview, jint x, jint y,
1116    jobject rect, jobject bounds)
1117{
1118    WebView* view = GET_NATIVE_VIEW(env, jwebview);
1119    ALOG_ASSERT(view, "view not set in %s", __FUNCTION__);
1120    SkIRect nativeRect, nativeBounds;
1121    int id = view->scrollableLayer(x, y, &nativeRect, &nativeBounds);
1122    if (rect)
1123        GraphicsJNI::irect_to_jrect(nativeRect, env, rect);
1124    if (bounds)
1125        GraphicsJNI::irect_to_jrect(nativeBounds, env, bounds);
1126    return id;
1127}
1128
1129static bool nativeScrollLayer(JNIEnv* env, jobject obj, jint layerId, jint x,
1130        jint y)
1131{
1132#if ENABLE(ANDROID_OVERFLOW_SCROLL)
1133    WebView* view = GET_NATIVE_VIEW(env, obj);
1134    view->scrollLayer(layerId, x, y);
1135
1136    //TODO: the below only needed for the SW rendering path
1137    LayerAndroid* baseLayer = view->getBaseLayer();
1138    if (!baseLayer)
1139        return false;
1140    LayerAndroid* layer = baseLayer->findById(layerId);
1141    if (!layer || !layer->contentIsScrollable())
1142        return false;
1143    return static_cast<ScrollableLayerAndroid*>(layer)->scrollTo(x, y);
1144#endif
1145    return false;
1146}
1147
1148static void nativeSetIsScrolling(JNIEnv* env, jobject jwebview, jboolean isScrolling)
1149{
1150    WebView* view = GET_NATIVE_VIEW(env, jwebview);
1151    ALOG_ASSERT(view, "view not set in %s", __FUNCTION__);
1152    view->setIsScrolling(isScrolling);
1153}
1154
1155static void nativeUseHardwareAccelSkia(JNIEnv*, jobject, jboolean enabled)
1156{
1157    BaseRenderer::setCurrentRendererType(enabled ? BaseRenderer::Ganesh : BaseRenderer::Raster);
1158}
1159
1160static int nativeGetBackgroundColor(JNIEnv* env, jobject obj)
1161{
1162    WebView* view = GET_NATIVE_VIEW(env, obj);
1163    BaseLayerAndroid* baseLayer = view->getBaseLayer();
1164    if (baseLayer) {
1165        WebCore::Color color = baseLayer->getBackgroundColor();
1166        if (color.isValid())
1167            return SkColorSetARGB(color.alpha(), color.red(),
1168                                  color.green(), color.blue());
1169    }
1170    return SK_ColorWHITE;
1171}
1172
1173static void nativeSetPauseDrawing(JNIEnv *env, jobject obj, jint nativeView,
1174                                      jboolean pause)
1175{
1176    ((WebView*)nativeView)->m_isDrawingPaused = pause;
1177}
1178
1179static void nativeSetTextSelection(JNIEnv *env, jobject obj, jint nativeView,
1180                                   jint selectionPtr)
1181{
1182    SelectText* selection = reinterpret_cast<SelectText*>(selectionPtr);
1183    reinterpret_cast<WebView*>(nativeView)->setTextSelection(selection);
1184}
1185
1186static jint nativeGetHandleLayerId(JNIEnv *env, jobject obj, jint nativeView,
1187                                     jint handleIndex, jobject cursorPoint,
1188                                     jobject textQuad)
1189{
1190    WebView* webview = reinterpret_cast<WebView*>(nativeView);
1191    SkIPoint nativePoint;
1192    FloatQuad nativeTextQuad;
1193    int layerId = webview->getHandleLayerId((SelectText::HandleId) handleIndex,
1194            nativePoint, nativeTextQuad);
1195    if (cursorPoint)
1196        GraphicsJNI::ipoint_to_jpoint(nativePoint, env, cursorPoint);
1197    if (textQuad)
1198        webview->floatQuadToQuadF(env, nativeTextQuad, textQuad);
1199    return layerId;
1200}
1201
1202static jboolean nativeIsBaseFirst(JNIEnv *env, jobject obj, jint nativeView)
1203{
1204    WebView* webview = reinterpret_cast<WebView*>(nativeView);
1205    SelectText* select = static_cast<SelectText*>(
1206            webview->getDrawExtra(WebView::DrawExtrasSelection));
1207    return select ? select->isBaseFirst() : false;
1208}
1209
1210static void nativeMapLayerRect(JNIEnv *env, jobject obj, jint nativeView,
1211        jint layerId, jobject rect)
1212{
1213    WebView* webview = reinterpret_cast<WebView*>(nativeView);
1214    SkIRect nativeRect;
1215    GraphicsJNI::jrect_to_irect(env, rect, &nativeRect);
1216    webview->mapLayerRect(layerId, nativeRect);
1217    GraphicsJNI::irect_to_jrect(nativeRect, env, rect);
1218}
1219
1220static jint nativeSetHwAccelerated(JNIEnv *env, jobject obj, jint nativeView,
1221        jboolean hwAccelerated)
1222{
1223    WebView* webview = reinterpret_cast<WebView*>(nativeView);
1224    return webview->setHwAccelerated(hwAccelerated);
1225}
1226
1227/*
1228 * JNI registration
1229 */
1230static JNINativeMethod gJavaWebViewMethods[] = {
1231    { "nativeCreate", "(ILjava/lang/String;Z)V",
1232        (void*) nativeCreate },
1233    { "nativeDestroy", "()V",
1234        (void*) nativeDestroy },
1235    { "nativeDraw", "(Landroid/graphics/Canvas;Landroid/graphics/RectF;IIZ)I",
1236        (void*) nativeDraw },
1237    { "nativeGetDrawGLFunction", "(ILandroid/graphics/Rect;Landroid/graphics/Rect;Landroid/graphics/RectF;FI)I",
1238        (void*) nativeGetDrawGLFunction },
1239    { "nativeUpdateDrawGLFunction", "(Landroid/graphics/Rect;Landroid/graphics/Rect;Landroid/graphics/RectF;F)V",
1240        (void*) nativeUpdateDrawGLFunction },
1241    { "nativeDumpDisplayTree", "(Ljava/lang/String;)V",
1242        (void*) nativeDumpDisplayTree },
1243    { "nativeEvaluateLayersAnimations", "(I)Z",
1244        (void*) nativeEvaluateLayersAnimations },
1245    { "nativeGetSelection", "()Ljava/lang/String;",
1246        (void*) nativeGetSelection },
1247    { "nativeLayerBounds", "(I)Landroid/graphics/Rect;",
1248        (void*) nativeLayerBounds },
1249    { "nativeSetHeightCanMeasure", "(Z)V",
1250        (void*) nativeSetHeightCanMeasure },
1251    { "nativeSetBaseLayer", "(IILandroid/graphics/Region;ZZ)Z",
1252        (void*) nativeSetBaseLayer },
1253    { "nativeGetBaseLayer", "()I",
1254        (void*) nativeGetBaseLayer },
1255    { "nativeReplaceBaseContent", "(I)V",
1256        (void*) nativeReplaceBaseContent },
1257    { "nativeCopyBaseContentToPicture", "(Landroid/graphics/Picture;)V",
1258        (void*) nativeCopyBaseContentToPicture },
1259    { "nativeHasContent", "()Z",
1260        (void*) nativeHasContent },
1261    { "nativeDiscardAllTextures", "()V",
1262        (void*) nativeDiscardAllTextures },
1263    { "nativeTileProfilingStart", "()V",
1264        (void*) nativeTileProfilingStart },
1265    { "nativeTileProfilingStop", "()F",
1266        (void*) nativeTileProfilingStop },
1267    { "nativeTileProfilingClear", "()V",
1268        (void*) nativeTileProfilingClear },
1269    { "nativeTileProfilingNumFrames", "()I",
1270        (void*) nativeTileProfilingNumFrames },
1271    { "nativeTileProfilingNumTilesInFrame", "(I)I",
1272        (void*) nativeTileProfilingNumTilesInFrame },
1273    { "nativeTileProfilingGetInt", "(IILjava/lang/String;)I",
1274        (void*) nativeTileProfilingGetInt },
1275    { "nativeTileProfilingGetFloat", "(IILjava/lang/String;)F",
1276        (void*) nativeTileProfilingGetFloat },
1277    { "nativeStopGL", "()V",
1278        (void*) nativeStopGL },
1279    { "nativeScrollableLayer", "(IILandroid/graphics/Rect;Landroid/graphics/Rect;)I",
1280        (void*) nativeScrollableLayer },
1281    { "nativeScrollLayer", "(III)Z",
1282        (void*) nativeScrollLayer },
1283    { "nativeSetIsScrolling", "(Z)V",
1284        (void*) nativeSetIsScrolling },
1285    { "nativeUseHardwareAccelSkia", "(Z)V",
1286        (void*) nativeUseHardwareAccelSkia },
1287    { "nativeGetBackgroundColor", "()I",
1288        (void*) nativeGetBackgroundColor },
1289    { "nativeSetProperty", "(Ljava/lang/String;Ljava/lang/String;)Z",
1290        (void*) nativeSetProperty },
1291    { "nativeGetProperty", "(Ljava/lang/String;)Ljava/lang/String;",
1292        (void*) nativeGetProperty },
1293    { "nativeOnTrimMemory", "(I)V",
1294        (void*) nativeOnTrimMemory },
1295    { "nativeSetPauseDrawing", "(IZ)V",
1296        (void*) nativeSetPauseDrawing },
1297    { "nativeSetTextSelection", "(II)V",
1298        (void*) nativeSetTextSelection },
1299    { "nativeGetHandleLayerId", "(IILandroid/graphics/Point;Landroid/webkit/QuadF;)I",
1300        (void*) nativeGetHandleLayerId },
1301    { "nativeIsBaseFirst", "(I)Z",
1302        (void*) nativeIsBaseFirst },
1303    { "nativeMapLayerRect", "(IILandroid/graphics/Rect;)V",
1304        (void*) nativeMapLayerRect },
1305    { "nativeSetHwAccelerated", "(IZ)I",
1306        (void*) nativeSetHwAccelerated },
1307};
1308
1309int registerWebView(JNIEnv* env)
1310{
1311    jclass clazz = env->FindClass("android/webkit/WebViewClassic");
1312    ALOG_ASSERT(clazz, "Unable to find class android/webkit/WebViewClassic");
1313    gWebViewField = env->GetFieldID(clazz, "mNativeClass", "I");
1314    ALOG_ASSERT(gWebViewField, "Unable to find android/webkit/WebViewClassic.mNativeClass");
1315    env->DeleteLocalRef(clazz);
1316
1317    return jniRegisterNativeMethods(env, "android/webkit/WebViewClassic", gJavaWebViewMethods, NELEM(gJavaWebViewMethods));
1318}
1319
1320} // namespace android
1321