WebView.cpp revision 75fc360d144b97f5e50bedf7ed3222898cc56446
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
596int getHandleLayerId(SelectText::HandleId handleId, SkIPoint& cursorPoint,
597        FloatQuad& textBounds) {
598    SelectText* selectText = static_cast<SelectText*>(getDrawExtra(DrawExtrasSelection));
599    if (!selectText || !m_baseLayer)
600        return -1;
601    int layerId = selectText->caretLayerId(handleId);
602    IntRect cursorRect = selectText->caretRect(handleId);
603    IntRect textRect = selectText->textRect(handleId);
604    // Rects exclude the last pixel on right/bottom. We want only included pixels.
605    cursorPoint.set(cursorRect.x(), cursorRect.maxY() - 1);
606    textRect.setHeight(textRect.height() - 1);
607    textRect.setWidth(textRect.width() - 1);
608    textBounds = FloatQuad(textRect);
609
610    if (layerId != -1) {
611        // We need to make sure the drawTransform is up to date as this is
612        // called before a draw() or drawGL()
613        m_baseLayer->updateLayerPositions(m_visibleRect);
614        LayerAndroid* root = m_baseLayer;
615        LayerAndroid* layer = root ? root->findById(layerId) : 0;
616        if (layer && layer->drawTransform()) {
617            const TransformationMatrix* transform = layer->drawTransform();
618            // We're overloading the concept of Rect to be just the two
619            // points (bottom-left and top-right.
620            cursorPoint = transform->mapPoint(cursorPoint);
621            textBounds = transform->mapQuad(textBounds);
622        }
623    }
624    return layerId;
625}
626
627void mapLayerRect(int layerId, SkIRect& rect) {
628    if (layerId != -1) {
629        // We need to make sure the drawTransform is up to date as this is
630        // called before a draw() or drawGL()
631        m_baseLayer->updateLayerPositions(m_visibleRect);
632        LayerAndroid* layer = m_baseLayer ? m_baseLayer->findById(layerId) : 0;
633        if (layer && layer->drawTransform())
634            rect = layer->drawTransform()->mapRect(rect);
635    }
636}
637
638void floatQuadToQuadF(JNIEnv* env, const FloatQuad& nativeTextQuad,
639        jobject textQuad)
640{
641    jobject p1 = env->GetObjectField(textQuad, m_javaGlue.m_quadFP1);
642    jobject p2 = env->GetObjectField(textQuad, m_javaGlue.m_quadFP2);
643    jobject p3 = env->GetObjectField(textQuad, m_javaGlue.m_quadFP3);
644    jobject p4 = env->GetObjectField(textQuad, m_javaGlue.m_quadFP4);
645    GraphicsJNI::point_to_jpointf(nativeTextQuad.p1(), env, p1);
646    GraphicsJNI::point_to_jpointf(nativeTextQuad.p2(), env, p2);
647    GraphicsJNI::point_to_jpointf(nativeTextQuad.p3(), env, p3);
648    GraphicsJNI::point_to_jpointf(nativeTextQuad.p4(), env, p4);
649    env->DeleteLocalRef(p1);
650    env->DeleteLocalRef(p2);
651    env->DeleteLocalRef(p3);
652    env->DeleteLocalRef(p4);
653}
654
655// This is called when WebView switches rendering modes in a more permanent fashion
656// such as when the layer type is set or the view is attached/detached from the window
657int setHwAccelerated(bool hwAccelerated) {
658    if (!m_glWebViewState)
659        return 0;
660    LayerAndroid* root = m_baseLayer;
661    if (root)
662        return root->setHwAccelerated(hwAccelerated);
663    return 0;
664}
665
666    bool m_isDrawingPaused;
667private: // local state for WebView
668    // private to getFrameCache(); other functions operate in a different thread
669    WebViewCore* m_viewImpl;
670    int m_generation; // associate unique ID with sent kit focus to match with ui
671    // Corresponds to the same-named boolean on the java side.
672    bool m_heightCanMeasure;
673    int m_lastDx;
674    SkMSec m_lastDxTime;
675    DrawExtra* m_extras[DRAW_EXTRAS_SIZE];
676    BaseLayerAndroid* m_baseLayer;
677    Functor* m_glDrawFunctor;
678#if USE(ACCELERATED_COMPOSITING)
679    GLWebViewState* m_glWebViewState;
680#endif
681    SkRect m_visibleRect;
682    bool m_isHighEndGfx;
683}; // end of WebView class
684
685
686/**
687 * This class holds a function pointer and parameters for calling drawGL into a specific
688 * viewport. The pointer to the Functor will be put on a framework display list to be called
689 * when the display list is replayed.
690 */
691class GLDrawFunctor : Functor {
692    public:
693    GLDrawFunctor(WebView* _wvInstance,
694            int (WebView::*_funcPtr)(WebCore::IntRect&, WebCore::IntRect*,
695                    WebCore::IntRect&, int, WebCore::IntRect&, jfloat, jint, bool),
696            WebCore::IntRect _viewRect, float _scale, int _extras) {
697        wvInstance = _wvInstance;
698        funcPtr = _funcPtr;
699        viewRect = _viewRect;
700        scale = _scale;
701        extras = _extras;
702    };
703    status_t operator()(int messageId, void* data) {
704        if (viewRect.isEmpty()) {
705            // NOOP operation if viewport is empty
706            return 0;
707        }
708
709        WebCore::IntRect inval;
710        int titlebarHeight = webViewRect.height() - viewRect.height();
711
712        uirenderer::DrawGlInfo* info = reinterpret_cast<uirenderer::DrawGlInfo*>(data);
713        WebCore::IntRect localViewRect = viewRect;
714        if (info->isLayer)
715            localViewRect.move(-1 * localViewRect.x(), -1 * localViewRect.y());
716
717        WebCore::IntRect clip(info->clipLeft, info->clipTop,
718                              info->clipRight - info->clipLeft,
719                              info->clipBottom - info->clipTop);
720        bool shouldDraw = (messageId == uirenderer::DrawGlInfo::kModeDraw);
721        TilesManager::instance()->shader()->setWebViewMatrix(info->transform, info->isLayer);
722        int returnFlags = (*wvInstance.*funcPtr)(localViewRect, &inval, webViewRect,
723                titlebarHeight, clip, scale, extras, shouldDraw);
724        if ((returnFlags & uirenderer::DrawGlInfo::kStatusDraw) != 0) {
725            IntRect finalInval;
726            if (inval.isEmpty())
727                finalInval = webViewRect;
728            else {
729                finalInval.setX(webViewRect.x() + inval.x());
730                finalInval.setY(webViewRect.y() + titlebarHeight + inval.y());
731                finalInval.setWidth(inval.width());
732                finalInval.setHeight(inval.height());
733            }
734            info->dirtyLeft = finalInval.x();
735            info->dirtyTop = finalInval.y();
736            info->dirtyRight = finalInval.maxX();
737            info->dirtyBottom = finalInval.maxY();
738        }
739        // return 1 if invalidation needed, 2 to request non-drawing functor callback, 0 otherwise
740        ALOGV("returnFlags are %d, shouldDraw %d", returnFlags, shouldDraw);
741        return returnFlags;
742    }
743    void updateRect(WebCore::IntRect& _viewRect) {
744        viewRect = _viewRect;
745    }
746    void updateViewRect(WebCore::IntRect& _viewRect) {
747        webViewRect = _viewRect;
748    }
749    void updateScale(float _scale) {
750        scale = _scale;
751    }
752    private:
753    WebView* wvInstance;
754    int (WebView::*funcPtr)(WebCore::IntRect&, WebCore::IntRect*,
755            WebCore::IntRect&, int, WebCore::IntRect&, float, int, bool);
756    WebCore::IntRect viewRect;
757    WebCore::IntRect webViewRect;
758    jfloat scale;
759    jint extras;
760};
761
762/*
763 * Native JNI methods
764 */
765
766static void nativeCreate(JNIEnv *env, jobject obj, int viewImpl,
767                         jstring drawableDir, jboolean isHighEndGfx)
768{
769    WTF::String dir = jstringToWtfString(env, drawableDir);
770    new WebView(env, obj, viewImpl, dir, isHighEndGfx);
771    // NEED THIS OR SOMETHING LIKE IT!
772    //Release(obj);
773}
774
775static WebCore::IntRect jrect_to_webrect(JNIEnv* env, jobject obj)
776{
777    if (obj) {
778        int L, T, R, B;
779        GraphicsJNI::get_jrect(env, obj, &L, &T, &R, &B);
780        return WebCore::IntRect(L, T, R - L, B - T);
781    } else
782        return WebCore::IntRect();
783}
784
785static SkRect jrectf_to_rect(JNIEnv* env, jobject obj)
786{
787    SkRect rect = SkRect::MakeEmpty();
788    if (obj)
789        GraphicsJNI::jrectf_to_rect(env, obj, &rect);
790    return rect;
791}
792
793static jint nativeDraw(JNIEnv *env, jobject obj, jobject canv,
794        jobject visible, jint color,
795        jint extras, jboolean split) {
796    SkCanvas* canvas = GraphicsJNI::getNativeCanvas(env, canv);
797    WebView* webView = GET_NATIVE_VIEW(env, obj);
798    SkRect visibleRect = jrectf_to_rect(env, visible);
799    webView->setVisibleRect(visibleRect);
800    PictureSet* pictureSet = webView->draw(canvas, color,
801            static_cast<WebView::DrawExtras>(extras), split);
802    return reinterpret_cast<jint>(pictureSet);
803}
804
805static jint nativeGetDrawGLFunction(JNIEnv *env, jobject obj, jint nativeView,
806                                    jobject jrect, jobject jviewrect,
807                                    jobject jvisiblerect,
808                                    jfloat scale, jint extras) {
809    WebCore::IntRect viewRect = jrect_to_webrect(env, jrect);
810    WebView *wvInstance = (WebView*) nativeView;
811    SkRect visibleRect = jrectf_to_rect(env, jvisiblerect);
812    wvInstance->setVisibleRect(visibleRect);
813
814    GLDrawFunctor* functor = new GLDrawFunctor(wvInstance,
815            &android::WebView::drawGL, viewRect, scale, extras);
816    wvInstance->setFunctor((Functor*) functor);
817
818    WebCore::IntRect webViewRect = jrect_to_webrect(env, jviewrect);
819    functor->updateViewRect(webViewRect);
820
821    return (jint)functor;
822}
823
824static void nativeUpdateDrawGLFunction(JNIEnv *env, jobject obj, jobject jrect,
825        jobject jviewrect, jobject jvisiblerect, jfloat scale) {
826    WebView *wvInstance = GET_NATIVE_VIEW(env, obj);
827    if (wvInstance) {
828        GLDrawFunctor* functor = (GLDrawFunctor*) wvInstance->getFunctor();
829        if (functor) {
830            WebCore::IntRect viewRect = jrect_to_webrect(env, jrect);
831            functor->updateRect(viewRect);
832
833            SkRect visibleRect = jrectf_to_rect(env, jvisiblerect);
834            wvInstance->setVisibleRect(visibleRect);
835
836            WebCore::IntRect webViewRect = jrect_to_webrect(env, jviewrect);
837            functor->updateViewRect(webViewRect);
838
839            functor->updateScale(scale);
840        }
841    }
842}
843
844static bool nativeEvaluateLayersAnimations(JNIEnv *env, jobject obj, jint nativeView)
845{
846    // only call in software rendering, initialize and evaluate animations
847#if USE(ACCELERATED_COMPOSITING)
848    BaseLayerAndroid* baseLayer = ((WebView*)nativeView)->getBaseLayer();
849    if (baseLayer) {
850        baseLayer->initAnimations();
851        return baseLayer->evaluateAnimations();
852    }
853#endif
854    return false;
855}
856
857static bool nativeSetBaseLayer(JNIEnv *env, jobject obj, jint nativeView, jint layer, jobject inval,
858                               jboolean showVisualIndicator,
859                               jboolean isPictureAfterFirstLayout)
860{
861    BaseLayerAndroid* layerImpl = reinterpret_cast<BaseLayerAndroid*>(layer);
862    SkRegion invalRegion;
863    if (inval)
864        invalRegion = *GraphicsJNI::getNativeRegion(env, inval);
865    return ((WebView*)nativeView)->setBaseLayer(layerImpl, invalRegion, showVisualIndicator,
866                                                isPictureAfterFirstLayout);
867}
868
869static BaseLayerAndroid* nativeGetBaseLayer(JNIEnv *env, jobject obj)
870{
871    return GET_NATIVE_VIEW(env, obj)->getBaseLayer();
872}
873
874static void nativeReplaceBaseContent(JNIEnv *env, jobject obj, jint content)
875{
876    PictureSet* set = reinterpret_cast<PictureSet*>(content);
877    GET_NATIVE_VIEW(env, obj)->replaceBaseContent(set);
878}
879
880static void nativeCopyBaseContentToPicture(JNIEnv *env, jobject obj, jobject pict)
881{
882    SkPicture* picture = GraphicsJNI::getNativePicture(env, pict);
883    GET_NATIVE_VIEW(env, obj)->copyBaseContentToPicture(picture);
884}
885
886static bool nativeHasContent(JNIEnv *env, jobject obj)
887{
888    return GET_NATIVE_VIEW(env, obj)->hasContent();
889}
890
891static jobject nativeLayerBounds(JNIEnv* env, jobject obj, jint jlayer)
892{
893    SkRect r;
894#if USE(ACCELERATED_COMPOSITING)
895    LayerAndroid* layer = (LayerAndroid*) jlayer;
896    r = layer->bounds();
897#else
898    r.setEmpty();
899#endif
900    SkIRect irect;
901    r.round(&irect);
902    jclass rectClass = env->FindClass("android/graphics/Rect");
903    jmethodID init = env->GetMethodID(rectClass, "<init>", "(IIII)V");
904    jobject rect = env->NewObject(rectClass, init, irect.fLeft, irect.fTop,
905        irect.fRight, irect.fBottom);
906    env->DeleteLocalRef(rectClass);
907    return rect;
908}
909
910static void nativeSetHeightCanMeasure(JNIEnv *env, jobject obj, bool measure)
911{
912    WebView* view = GET_NATIVE_VIEW(env, obj);
913    ALOG_ASSERT(view, "view not set in nativeSetHeightCanMeasure");
914    view->setHeightCanMeasure(measure);
915}
916
917static void nativeDestroy(JNIEnv *env, jobject obj)
918{
919    WebView* view = GET_NATIVE_VIEW(env, obj);
920    ALOGD("nativeDestroy view: %p", view);
921    ALOG_ASSERT(view, "view not set in nativeDestroy");
922    delete view;
923}
924
925static void nativeStopGL(JNIEnv *env, jobject obj)
926{
927    GET_NATIVE_VIEW(env, obj)->stopGL();
928}
929
930static jobject nativeGetSelection(JNIEnv *env, jobject obj)
931{
932    WebView* view = GET_NATIVE_VIEW(env, obj);
933    ALOG_ASSERT(view, "view not set in %s", __FUNCTION__);
934    String selection = view->getSelection();
935    return wtfStringToJstring(env, selection);
936}
937
938static void nativeDiscardAllTextures(JNIEnv *env, jobject obj)
939{
940    //discard all textures for debugging/test purposes, but not gl backing memory
941    bool allTextures = true, deleteGLTextures = false;
942    TilesManager::instance()->discardTextures(allTextures, deleteGLTextures);
943}
944
945static void nativeTileProfilingStart(JNIEnv *env, jobject obj)
946{
947    TilesManager::instance()->getProfiler()->start();
948}
949
950static float nativeTileProfilingStop(JNIEnv *env, jobject obj)
951{
952    return TilesManager::instance()->getProfiler()->stop();
953}
954
955static void nativeTileProfilingClear(JNIEnv *env, jobject obj)
956{
957    TilesManager::instance()->getProfiler()->clear();
958}
959
960static int nativeTileProfilingNumFrames(JNIEnv *env, jobject obj)
961{
962    return TilesManager::instance()->getProfiler()->numFrames();
963}
964
965static int nativeTileProfilingNumTilesInFrame(JNIEnv *env, jobject obj, int frame)
966{
967    return TilesManager::instance()->getProfiler()->numTilesInFrame(frame);
968}
969
970static int nativeTileProfilingGetInt(JNIEnv *env, jobject obj, int frame, int tile, jstring jkey)
971{
972    WTF::String key = jstringToWtfString(env, jkey);
973    TileProfileRecord* record = TilesManager::instance()->getProfiler()->getTile(frame, tile);
974
975    if (key == "left")
976        return record->left;
977    if (key == "top")
978        return record->top;
979    if (key == "right")
980        return record->right;
981    if (key == "bottom")
982        return record->bottom;
983    if (key == "level")
984        return record->level;
985    if (key == "isReady")
986        return record->isReady ? 1 : 0;
987    return -1;
988}
989
990static float nativeTileProfilingGetFloat(JNIEnv *env, jobject obj, int frame, int tile, jstring jkey)
991{
992    TileProfileRecord* record = TilesManager::instance()->getProfiler()->getTile(frame, tile);
993    return record->scale;
994}
995
996#ifdef ANDROID_DUMP_DISPLAY_TREE
997static void dumpToFile(const char text[], void* file) {
998    fwrite(text, 1, strlen(text), reinterpret_cast<FILE*>(file));
999    fwrite("\n", 1, 1, reinterpret_cast<FILE*>(file));
1000}
1001#endif
1002
1003// Return true to view invalidate WebView
1004static bool nativeSetProperty(JNIEnv *env, jobject obj, jstring jkey, jstring jvalue)
1005{
1006    WTF::String key = jstringToWtfString(env, jkey);
1007    WTF::String value = jstringToWtfString(env, jvalue);
1008    if (key == "inverted") {
1009        bool shouldInvert = (value == "true");
1010        TilesManager::instance()->setInvertedScreen(shouldInvert);
1011        return true;
1012    }
1013    else if (key == "inverted_contrast") {
1014        float contrast = value.toFloat();
1015        TilesManager::instance()->setInvertedScreenContrast(contrast);
1016        return true;
1017    }
1018    else if (key == "enable_cpu_upload_path") {
1019        TilesManager::instance()->transferQueue()->setTextureUploadType(
1020            value == "true" ? CpuUpload : GpuUpload);
1021    }
1022    else if (key == "use_minimal_memory") {
1023        TilesManager::instance()->setUseMinimalMemory(value == "true");
1024    }
1025    else if (key == "use_double_buffering") {
1026        TilesManager::instance()->setUseDoubleBuffering(value == "true");
1027    }
1028    else if (key == "tree_updates") {
1029        TilesManager::instance()->clearContentUpdates();
1030    }
1031    return false;
1032}
1033
1034static jstring nativeGetProperty(JNIEnv *env, jobject obj, jstring jkey)
1035{
1036    WTF::String key = jstringToWtfString(env, jkey);
1037    if (key == "tree_updates") {
1038        int updates = TilesManager::instance()->getContentUpdates();
1039        WTF::String wtfUpdates = WTF::String::number(updates);
1040        return wtfStringToJstring(env, wtfUpdates);
1041    }
1042    return 0;
1043}
1044
1045static void nativeOnTrimMemory(JNIEnv *env, jobject obj, jint level)
1046{
1047    if (TilesManager::hardwareAccelerationEnabled()) {
1048        // When we got TRIM_MEMORY_MODERATE or TRIM_MEMORY_COMPLETE, we should
1049        // make sure the transfer queue is empty and then abandon the Surface
1050        // Texture to avoid ANR b/c framework may destroy the EGL context.
1051        // Refer to WindowManagerImpl.java for conditions we followed.
1052        TilesManager* tilesManager = TilesManager::instance();
1053        if (level >= TRIM_MEMORY_MODERATE
1054            && !tilesManager->highEndGfx()) {
1055            ALOGD("OnTrimMemory with EGL Context %p", eglGetCurrentContext());
1056            tilesManager->transferQueue()->emptyQueue();
1057            tilesManager->shader()->cleanupGLResources();
1058            tilesManager->videoLayerManager()->cleanupGLResources();
1059        }
1060
1061        bool freeAllTextures = (level > TRIM_MEMORY_UI_HIDDEN), glTextures = true;
1062        tilesManager->discardTextures(freeAllTextures, glTextures);
1063    }
1064}
1065
1066static void nativeDumpDisplayTree(JNIEnv* env, jobject jwebview, jstring jurl)
1067{
1068#ifdef ANDROID_DUMP_DISPLAY_TREE
1069    WebView* view = GET_NATIVE_VIEW(env, jwebview);
1070    ALOG_ASSERT(view, "view not set in %s", __FUNCTION__);
1071
1072    if (view && view->getWebViewCore()) {
1073        FILE* file = fopen(DISPLAY_TREE_LOG_FILE, "w");
1074        if (file) {
1075            SkFormatDumper dumper(dumpToFile, file);
1076            // dump the URL
1077            if (jurl) {
1078                const char* str = env->GetStringUTFChars(jurl, 0);
1079                SkDebugf("Dumping %s to %s\n", str, DISPLAY_TREE_LOG_FILE);
1080                dumpToFile(str, file);
1081                env->ReleaseStringUTFChars(jurl, str);
1082            }
1083            // now dump the display tree
1084            SkDumpCanvas canvas(&dumper);
1085            // this will playback the picture into the canvas, which will
1086            // spew its contents to the dumper
1087            view->draw(&canvas, 0, WebView::DrawExtrasNone, false);
1088            // we're done with the file now
1089            fwrite("\n", 1, 1, file);
1090            fclose(file);
1091        }
1092#if USE(ACCELERATED_COMPOSITING)
1093        const LayerAndroid* baseLayer = view->getBaseLayer();
1094        if (baseLayer) {
1095          FILE* file = fopen(LAYERS_TREE_LOG_FILE,"w");
1096          if (file) {
1097              baseLayer->dumpLayers(file, 0);
1098              fclose(file);
1099          }
1100        }
1101#endif
1102    }
1103#endif
1104}
1105
1106static int nativeScrollableLayer(JNIEnv* env, jobject jwebview, jint x, jint y,
1107    jobject rect, jobject bounds)
1108{
1109    WebView* view = GET_NATIVE_VIEW(env, jwebview);
1110    ALOG_ASSERT(view, "view not set in %s", __FUNCTION__);
1111    SkIRect nativeRect, nativeBounds;
1112    int id = view->scrollableLayer(x, y, &nativeRect, &nativeBounds);
1113    if (rect)
1114        GraphicsJNI::irect_to_jrect(nativeRect, env, rect);
1115    if (bounds)
1116        GraphicsJNI::irect_to_jrect(nativeBounds, env, bounds);
1117    return id;
1118}
1119
1120static bool nativeScrollLayer(JNIEnv* env, jobject obj, jint layerId, jint x,
1121        jint y)
1122{
1123#if ENABLE(ANDROID_OVERFLOW_SCROLL)
1124    WebView* view = GET_NATIVE_VIEW(env, obj);
1125    view->scrollLayer(layerId, x, y);
1126
1127    //TODO: the below only needed for the SW rendering path
1128    LayerAndroid* baseLayer = view->getBaseLayer();
1129    if (!baseLayer)
1130        return false;
1131    LayerAndroid* layer = baseLayer->findById(layerId);
1132    if (!layer || !layer->contentIsScrollable())
1133        return false;
1134    return static_cast<ScrollableLayerAndroid*>(layer)->scrollTo(x, y);
1135#endif
1136    return false;
1137}
1138
1139static void nativeSetIsScrolling(JNIEnv* env, jobject jwebview, jboolean isScrolling)
1140{
1141    WebView* view = GET_NATIVE_VIEW(env, jwebview);
1142    ALOG_ASSERT(view, "view not set in %s", __FUNCTION__);
1143    view->setIsScrolling(isScrolling);
1144}
1145
1146static void nativeUseHardwareAccelSkia(JNIEnv*, jobject, jboolean enabled)
1147{
1148    BaseRenderer::setCurrentRendererType(enabled ? BaseRenderer::Ganesh : BaseRenderer::Raster);
1149}
1150
1151static int nativeGetBackgroundColor(JNIEnv* env, jobject obj)
1152{
1153    WebView* view = GET_NATIVE_VIEW(env, obj);
1154    BaseLayerAndroid* baseLayer = view->getBaseLayer();
1155    if (baseLayer) {
1156        WebCore::Color color = baseLayer->getBackgroundColor();
1157        if (color.isValid())
1158            return SkColorSetARGB(color.alpha(), color.red(),
1159                                  color.green(), color.blue());
1160    }
1161    return SK_ColorWHITE;
1162}
1163
1164static void nativeSetPauseDrawing(JNIEnv *env, jobject obj, jint nativeView,
1165                                      jboolean pause)
1166{
1167    ((WebView*)nativeView)->m_isDrawingPaused = pause;
1168}
1169
1170static void nativeSetTextSelection(JNIEnv *env, jobject obj, jint nativeView,
1171                                   jint selectionPtr)
1172{
1173    SelectText* selection = reinterpret_cast<SelectText*>(selectionPtr);
1174    reinterpret_cast<WebView*>(nativeView)->setTextSelection(selection);
1175}
1176
1177static jint nativeGetHandleLayerId(JNIEnv *env, jobject obj, jint nativeView,
1178                                     jint handleIndex, jobject cursorPoint,
1179                                     jobject textQuad)
1180{
1181    WebView* webview = reinterpret_cast<WebView*>(nativeView);
1182    SkIPoint nativePoint;
1183    FloatQuad nativeTextQuad;
1184    int layerId = webview->getHandleLayerId((SelectText::HandleId) handleIndex,
1185            nativePoint, nativeTextQuad);
1186    if (cursorPoint)
1187        GraphicsJNI::ipoint_to_jpoint(nativePoint, env, cursorPoint);
1188    if (textQuad)
1189        webview->floatQuadToQuadF(env, nativeTextQuad, textQuad);
1190    return layerId;
1191}
1192
1193static jboolean nativeIsBaseFirst(JNIEnv *env, jobject obj, jint nativeView)
1194{
1195    WebView* webview = reinterpret_cast<WebView*>(nativeView);
1196    SelectText* select = static_cast<SelectText*>(
1197            webview->getDrawExtra(WebView::DrawExtrasSelection));
1198    return select ? select->isBaseFirst() : false;
1199}
1200
1201static void nativeMapLayerRect(JNIEnv *env, jobject obj, jint nativeView,
1202        jint layerId, jobject rect)
1203{
1204    WebView* webview = reinterpret_cast<WebView*>(nativeView);
1205    SkIRect nativeRect;
1206    GraphicsJNI::jrect_to_irect(env, rect, &nativeRect);
1207    webview->mapLayerRect(layerId, nativeRect);
1208    GraphicsJNI::irect_to_jrect(nativeRect, env, rect);
1209}
1210
1211static jint nativeSetHwAccelerated(JNIEnv *env, jobject obj, jint nativeView,
1212        jboolean hwAccelerated)
1213{
1214    WebView* webview = reinterpret_cast<WebView*>(nativeView);
1215    return webview->setHwAccelerated(hwAccelerated);
1216}
1217
1218/*
1219 * JNI registration
1220 */
1221static JNINativeMethod gJavaWebViewMethods[] = {
1222    { "nativeCreate", "(ILjava/lang/String;Z)V",
1223        (void*) nativeCreate },
1224    { "nativeDestroy", "()V",
1225        (void*) nativeDestroy },
1226    { "nativeDraw", "(Landroid/graphics/Canvas;Landroid/graphics/RectF;IIZ)I",
1227        (void*) nativeDraw },
1228    { "nativeGetDrawGLFunction", "(ILandroid/graphics/Rect;Landroid/graphics/Rect;Landroid/graphics/RectF;FI)I",
1229        (void*) nativeGetDrawGLFunction },
1230    { "nativeUpdateDrawGLFunction", "(Landroid/graphics/Rect;Landroid/graphics/Rect;Landroid/graphics/RectF;F)V",
1231        (void*) nativeUpdateDrawGLFunction },
1232    { "nativeDumpDisplayTree", "(Ljava/lang/String;)V",
1233        (void*) nativeDumpDisplayTree },
1234    { "nativeEvaluateLayersAnimations", "(I)Z",
1235        (void*) nativeEvaluateLayersAnimations },
1236    { "nativeGetSelection", "()Ljava/lang/String;",
1237        (void*) nativeGetSelection },
1238    { "nativeLayerBounds", "(I)Landroid/graphics/Rect;",
1239        (void*) nativeLayerBounds },
1240    { "nativeSetHeightCanMeasure", "(Z)V",
1241        (void*) nativeSetHeightCanMeasure },
1242    { "nativeSetBaseLayer", "(IILandroid/graphics/Region;ZZ)Z",
1243        (void*) nativeSetBaseLayer },
1244    { "nativeGetBaseLayer", "()I",
1245        (void*) nativeGetBaseLayer },
1246    { "nativeReplaceBaseContent", "(I)V",
1247        (void*) nativeReplaceBaseContent },
1248    { "nativeCopyBaseContentToPicture", "(Landroid/graphics/Picture;)V",
1249        (void*) nativeCopyBaseContentToPicture },
1250    { "nativeHasContent", "()Z",
1251        (void*) nativeHasContent },
1252    { "nativeDiscardAllTextures", "()V",
1253        (void*) nativeDiscardAllTextures },
1254    { "nativeTileProfilingStart", "()V",
1255        (void*) nativeTileProfilingStart },
1256    { "nativeTileProfilingStop", "()F",
1257        (void*) nativeTileProfilingStop },
1258    { "nativeTileProfilingClear", "()V",
1259        (void*) nativeTileProfilingClear },
1260    { "nativeTileProfilingNumFrames", "()I",
1261        (void*) nativeTileProfilingNumFrames },
1262    { "nativeTileProfilingNumTilesInFrame", "(I)I",
1263        (void*) nativeTileProfilingNumTilesInFrame },
1264    { "nativeTileProfilingGetInt", "(IILjava/lang/String;)I",
1265        (void*) nativeTileProfilingGetInt },
1266    { "nativeTileProfilingGetFloat", "(IILjava/lang/String;)F",
1267        (void*) nativeTileProfilingGetFloat },
1268    { "nativeStopGL", "()V",
1269        (void*) nativeStopGL },
1270    { "nativeScrollableLayer", "(IILandroid/graphics/Rect;Landroid/graphics/Rect;)I",
1271        (void*) nativeScrollableLayer },
1272    { "nativeScrollLayer", "(III)Z",
1273        (void*) nativeScrollLayer },
1274    { "nativeSetIsScrolling", "(Z)V",
1275        (void*) nativeSetIsScrolling },
1276    { "nativeUseHardwareAccelSkia", "(Z)V",
1277        (void*) nativeUseHardwareAccelSkia },
1278    { "nativeGetBackgroundColor", "()I",
1279        (void*) nativeGetBackgroundColor },
1280    { "nativeSetProperty", "(Ljava/lang/String;Ljava/lang/String;)Z",
1281        (void*) nativeSetProperty },
1282    { "nativeGetProperty", "(Ljava/lang/String;)Ljava/lang/String;",
1283        (void*) nativeGetProperty },
1284    { "nativeOnTrimMemory", "(I)V",
1285        (void*) nativeOnTrimMemory },
1286    { "nativeSetPauseDrawing", "(IZ)V",
1287        (void*) nativeSetPauseDrawing },
1288    { "nativeSetTextSelection", "(II)V",
1289        (void*) nativeSetTextSelection },
1290    { "nativeGetHandleLayerId", "(IILandroid/graphics/Point;Landroid/webkit/QuadF;)I",
1291        (void*) nativeGetHandleLayerId },
1292    { "nativeIsBaseFirst", "(I)Z",
1293        (void*) nativeIsBaseFirst },
1294    { "nativeMapLayerRect", "(IILandroid/graphics/Rect;)V",
1295        (void*) nativeMapLayerRect },
1296    { "nativeSetHwAccelerated", "(IZ)I",
1297        (void*) nativeSetHwAccelerated },
1298};
1299
1300int registerWebView(JNIEnv* env)
1301{
1302    jclass clazz = env->FindClass("android/webkit/WebViewClassic");
1303    ALOG_ASSERT(clazz, "Unable to find class android/webkit/WebViewClassic");
1304    gWebViewField = env->GetFieldID(clazz, "mNativeClass", "I");
1305    ALOG_ASSERT(gWebViewField, "Unable to find android/webkit/WebViewClassic.mNativeClass");
1306    env->DeleteLocalRef(clazz);
1307
1308    return jniRegisterNativeMethods(env, "android/webkit/WebViewClassic", gJavaWebViewMethods, NELEM(gJavaWebViewMethods));
1309}
1310
1311} // namespace android
1312