WebView.cpp revision 6184a1dfef36741a1e5602f5bf24ac99fcfa0aec
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_updateRectsForGL;
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_updateRectsForGL = GetJMethod(env, clazz, "updateRectsForGL", "()V");
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_visibleContentRect.fLeft)
235        dx = left - m_visibleContentRect.fLeft;
236    // Only scroll right if the entire width can fit on screen.
237    else if (right > m_visibleContentRect.fRight
238            && right - left < m_visibleContentRect.width())
239        dx = right - m_visibleContentRect.fRight;
240    int dy = 0;
241    int top = rect.y();
242    int bottom = rect.maxY();
243    if (top < m_visibleContentRect.fTop)
244        dy = top - m_visibleContentRect.fTop;
245    // Only scroll down if the entire height can fit on screen
246    else if (bottom > m_visibleContentRect.fBottom
247            && bottom - top < m_visibleContentRect.height())
248        dy = bottom - m_visibleContentRect.fBottom;
249    if ((dx|dy) == 0 || !scrollBy(dx, dy))
250        return;
251    viewInvalidate();
252}
253
254int drawGL(WebCore::IntRect& invScreenRect, WebCore::IntRect* invalRect,
255        WebCore::IntRect& screenRect, int titleBarHeight,
256        WebCore::IntRect& screenClip, float scale, int extras, bool shouldDraw)
257{
258#if USE(ACCELERATED_COMPOSITING)
259    if (!m_baseLayer)
260        return 0;
261
262    if (m_viewImpl)
263        m_viewImpl->setPrerenderingEnabled(!m_isDrawingPaused);
264
265    if (!m_glWebViewState) {
266        TilesManager::instance()->setHighEndGfx(m_isHighEndGfx);
267        m_glWebViewState = new GLWebViewState();
268        m_glWebViewState->setBaseLayer(m_baseLayer, false, true);
269    }
270
271    DrawExtra* extra = getDrawExtra((DrawExtras) extras);
272
273    m_glWebViewState->glExtras()->setDrawExtra(extra);
274
275    // Make sure we have valid coordinates. We might not have valid coords
276    // if the zoom manager is still initializing. We will be redrawn
277    // once the correct scale is set
278    if (!m_visibleContentRect.isFinite())
279        return 0;
280    bool treesSwapped = false;
281    bool newTreeHasAnim = false;
282    int ret = m_glWebViewState->drawGL(invScreenRect, m_visibleContentRect, invalRect,
283                                        screenRect, titleBarHeight, screenClip, scale,
284                                        &treesSwapped, &newTreeHasAnim, shouldDraw);
285    if (treesSwapped) {
286        ALOG_ASSERT(m_javaGlue.m_obj, "A java object was not associated with this native WebView!");
287        JNIEnv* env = JSC::Bindings::getJNIEnv();
288        AutoJObject javaObject = m_javaGlue.object(env);
289        if (javaObject.get()) {
290            env->CallVoidMethod(javaObject.get(), m_javaGlue.m_pageSwapCallback, newTreeHasAnim);
291            checkException(env);
292        }
293    }
294    return m_isDrawingPaused ? 0 : ret;
295#endif
296    return 0;
297}
298
299void draw(SkCanvas* canvas, SkColor bgColor, DrawExtras extras)
300{
301    if (!m_baseLayer) {
302        canvas->drawColor(bgColor);
303        return;
304    }
305
306    // draw the content of the base layer first
307    LayerContent* content = m_baseLayer->content();
308    int sc = canvas->save(SkCanvas::kClip_SaveFlag);
309    if (content) {
310        canvas->clipRect(SkRect::MakeLTRB(0, 0, content->width(), content->height()),
311                         SkRegion::kDifference_Op);
312    }
313    Color c = m_baseLayer->getBackgroundColor();
314    canvas->drawColor(SkColorSetARGBInline(c.alpha(), c.red(), c.green(), c.blue()));
315    canvas->restoreToCount(sc);
316
317    // call this to be sure we've adjusted for any scrolling or animations
318    // before we actually draw
319    m_baseLayer->updateLayerPositions(m_visibleContentRect);
320    m_baseLayer->updatePositions();
321
322    // We have to set the canvas' matrix on the base layer
323    // (to have fixed layers work as intended)
324    SkAutoCanvasRestore restore(canvas, true);
325    m_baseLayer->setMatrix(canvas->getTotalMatrix());
326    canvas->resetMatrix();
327    m_baseLayer->draw(canvas, getDrawExtra(extras));
328}
329
330int getScaledMaxXScroll()
331{
332    ALOG_ASSERT(m_javaGlue.m_obj, "A java object was not associated with this native WebView!");
333    JNIEnv* env = JSC::Bindings::getJNIEnv();
334    AutoJObject javaObject = m_javaGlue.object(env);
335    if (!javaObject.get())
336        return 0;
337    int result = env->CallIntMethod(javaObject.get(), m_javaGlue.m_getScaledMaxXScroll);
338    checkException(env);
339    return result;
340}
341
342int getScaledMaxYScroll()
343{
344    ALOG_ASSERT(m_javaGlue.m_obj, "A java object was not associated with this native WebView!");
345    JNIEnv* env = JSC::Bindings::getJNIEnv();
346    AutoJObject javaObject = m_javaGlue.object(env);
347    if (!javaObject.get())
348        return 0;
349    int result = env->CallIntMethod(javaObject.get(), m_javaGlue.m_getScaledMaxYScroll);
350    checkException(env);
351    return result;
352}
353
354// Call through JNI to ask Java side to update the rectangles for GL functor.
355// This is called at every draw when it is not in process mode, so we should
356// keep this route as efficient as possible. Currently, its average cost on Xoom
357// is about 0.1ms - 0.2ms.
358// Alternatively, this can be achieved by adding more listener on Java side, but
359// that will be more likely causing jank when triggering GC.
360void updateRectsForGL()
361{
362    JNIEnv* env = JSC::Bindings::getJNIEnv();
363    AutoJObject javaObject = m_javaGlue.object(env);
364    if (!javaObject.get())
365        return;
366    env->CallVoidMethod(javaObject.get(), m_javaGlue.m_updateRectsForGL);
367    checkException(env);
368}
369
370#if USE(ACCELERATED_COMPOSITING)
371static const ScrollableLayerAndroid* findScrollableLayer(
372    const LayerAndroid* parent, int x, int y, SkIRect* foundBounds) {
373    IntRect bounds = enclosingIntRect(parent->fullContentAreaMapped());
374
375    // Check the parent bounds first; this will clip to within a masking layer's
376    // bounds.
377    if (parent->masksToBounds() && !bounds.contains(x, y))
378        return 0;
379
380    int count = parent->countChildren();
381    while (count--) {
382        const LayerAndroid* child = parent->getChild(count);
383        const ScrollableLayerAndroid* result = findScrollableLayer(child, x, y, foundBounds);
384        if (result) {
385            if (parent->masksToBounds()) {
386                if (bounds.width() < foundBounds->width())
387                    foundBounds->fRight = foundBounds->fLeft + bounds.width();
388                if (bounds.height() < foundBounds->height())
389                    foundBounds->fBottom = foundBounds->fTop + bounds.height();
390            }
391            return result;
392        }
393    }
394    if (parent->contentIsScrollable()) {
395        foundBounds->set(bounds.x(), bounds.y(), bounds.width(), bounds.height());
396        return static_cast<const ScrollableLayerAndroid*>(parent);
397    }
398    return 0;
399}
400#endif
401
402int scrollableLayer(int x, int y, SkIRect* layerRect, SkIRect* bounds)
403{
404#if USE(ACCELERATED_COMPOSITING)
405    if (!m_baseLayer)
406        return 0;
407    const ScrollableLayerAndroid* result = findScrollableLayer(m_baseLayer, x, y, bounds);
408    if (result) {
409        result->getScrollRect(layerRect);
410        return result->uniqueId();
411    }
412#endif
413    return 0;
414}
415
416void scrollLayer(int layerId, int x, int y)
417{
418    if (m_glWebViewState)
419        m_glWebViewState->scrollLayer(layerId, x, y);
420}
421
422void setHeightCanMeasure(bool measure)
423{
424    m_heightCanMeasure = measure;
425}
426
427String getSelection()
428{
429    SelectText* select = static_cast<SelectText*>(
430            getDrawExtra(WebView::DrawExtrasSelection));
431    if (select)
432        return select->getText();
433    return String();
434}
435
436bool scrollBy(int dx, int dy)
437{
438    ALOG_ASSERT(m_javaGlue.m_obj, "A java object was not associated with this native WebView!");
439
440    JNIEnv* env = JSC::Bindings::getJNIEnv();
441    AutoJObject javaObject = m_javaGlue.object(env);
442    if (!javaObject.get())
443        return false;
444    bool result = env->CallBooleanMethod(javaObject.get(), m_javaGlue.m_scrollBy, dx, dy, true);
445    checkException(env);
446    return result;
447}
448
449void setIsScrolling(bool isScrolling)
450{
451#if USE(ACCELERATED_COMPOSITING)
452    if (m_glWebViewState)
453        m_glWebViewState->setIsScrolling(isScrolling);
454#endif
455}
456
457void viewInvalidate()
458{
459    JNIEnv* env = JSC::Bindings::getJNIEnv();
460    AutoJObject javaObject = m_javaGlue.object(env);
461    if (!javaObject.get())
462        return;
463    env->CallVoidMethod(javaObject.get(), m_javaGlue.m_viewInvalidate);
464    checkException(env);
465}
466
467void viewInvalidateRect(int l, int t, int r, int b)
468{
469    JNIEnv* env = JSC::Bindings::getJNIEnv();
470    AutoJObject javaObject = m_javaGlue.object(env);
471    if (!javaObject.get())
472        return;
473    env->CallVoidMethod(javaObject.get(), m_javaGlue.m_viewInvalidateRect, l, r, t, b);
474    checkException(env);
475}
476
477void postInvalidateDelayed(int64_t delay, const WebCore::IntRect& bounds)
478{
479    JNIEnv* env = JSC::Bindings::getJNIEnv();
480    AutoJObject javaObject = m_javaGlue.object(env);
481    if (!javaObject.get())
482        return;
483    env->CallVoidMethod(javaObject.get(), m_javaGlue.m_postInvalidateDelayed,
484        delay, bounds.x(), bounds.y(), bounds.maxX(), bounds.maxY());
485    checkException(env);
486}
487
488#if ENABLE(ANDROID_OVERFLOW_SCROLL)
489static void copyScrollPosition(const LayerAndroid* fromRoot,
490                               LayerAndroid* toRoot, int layerId)
491{
492    if (!fromRoot || !toRoot)
493        return;
494    const LayerAndroid* from = fromRoot->findById(layerId);
495    LayerAndroid* to = toRoot->findById(layerId);
496    if (!from || !to || !from->contentIsScrollable() || !to->contentIsScrollable())
497        return;
498    // TODO: Support this for iframes.
499    if (to->isIFrameContent() || from->isIFrameContent())
500        return;
501    to->setScrollOffset(from->getScrollOffset());
502}
503#endif
504
505BaseLayerAndroid* getBaseLayer() const { return m_baseLayer; }
506
507bool setBaseLayer(BaseLayerAndroid* newBaseLayer, bool showVisualIndicator,
508                  bool isPictureAfterFirstLayout, int scrollingLayer)
509{
510    bool queueFull = false;
511#if USE(ACCELERATED_COMPOSITING)
512    if (m_glWebViewState)
513        queueFull = m_glWebViewState->setBaseLayer(newBaseLayer, showVisualIndicator,
514                                                   isPictureAfterFirstLayout);
515#endif
516
517#if ENABLE(ANDROID_OVERFLOW_SCROLL)
518    copyScrollPosition(m_baseLayer, newBaseLayer, scrollingLayer);
519#endif
520    SkSafeUnref(m_baseLayer);
521    m_baseLayer = newBaseLayer;
522
523    return queueFull;
524}
525
526void copyBaseContentToPicture(SkPicture* picture)
527{
528    if (!m_baseLayer || !m_baseLayer->content())
529        return;
530    LayerContent* content = m_baseLayer->content();
531    content->draw(picture->beginRecording(content->width(), content->height(),
532                                          SkPicture::kUsePathBoundsForClip_RecordingFlag));
533    picture->endRecording();
534}
535
536bool hasContent() {
537    if (!m_baseLayer || !m_baseLayer->content())
538        return false;
539    return !m_baseLayer->content()->isEmpty();
540}
541
542void setFunctor(Functor* functor) {
543    delete m_glDrawFunctor;
544    m_glDrawFunctor = functor;
545}
546
547Functor* getFunctor() {
548    return m_glDrawFunctor;
549}
550
551void setVisibleContentRect(SkRect& visibleContentRect) {
552    m_visibleContentRect = visibleContentRect;
553}
554
555void setDrawExtra(DrawExtra *extra, DrawExtras type)
556{
557    if (type == DrawExtrasNone)
558        return;
559    DrawExtra* old = m_extras[type - 1];
560    m_extras[type - 1] = extra;
561    if (old != extra) {
562        delete old;
563    }
564}
565
566void setTextSelection(SelectText *selection) {
567    setDrawExtra(selection, DrawExtrasSelection);
568}
569
570const TransformationMatrix* getLayerTransform(int layerId) {
571    if (layerId != -1 && m_baseLayer) {
572        LayerAndroid* layer = m_baseLayer->findById(layerId);
573        // We need to make sure the drawTransform is up to date as this is
574        // called before a draw() or drawGL()
575        if (layer) {
576            m_baseLayer->updatePositionsRecursive(m_visibleContentRect);
577            return layer->drawTransform();
578        }
579    }
580    return 0;
581}
582
583int getHandleLayerId(SelectText::HandleId handleId, SkIPoint& cursorPoint,
584        FloatQuad& textBounds) {
585    SelectText* selectText = static_cast<SelectText*>(getDrawExtra(DrawExtrasSelection));
586    if (!selectText || !m_baseLayer)
587        return -1;
588    int layerId = selectText->caretLayerId(handleId);
589    IntRect cursorRect = selectText->caretRect(handleId);
590    IntRect textRect = selectText->textRect(handleId);
591    // Rects exclude the last pixel on right/bottom. We want only included pixels.
592    cursorPoint.set(cursorRect.x(), cursorRect.maxY() - 1);
593    textRect.setHeight(std::max(1, textRect.height() - 1));
594    textRect.setWidth(std::max(1, textRect.width() - 1));
595    textBounds = FloatQuad(textRect);
596
597    const TransformationMatrix* transform = getLayerTransform(layerId);
598    if (transform) {
599        // We're overloading the concept of Rect to be just the two
600        // points (bottom-left and top-right.
601        cursorPoint = transform->mapPoint(cursorPoint);
602        textBounds = transform->mapQuad(textBounds);
603    }
604    return layerId;
605}
606
607void mapLayerRect(int layerId, SkIRect& rect) {
608    const TransformationMatrix* transform = getLayerTransform(layerId);
609    if (transform)
610        rect = transform->mapRect(rect);
611}
612
613void floatQuadToQuadF(JNIEnv* env, const FloatQuad& nativeTextQuad,
614        jobject textQuad)
615{
616    jobject p1 = env->GetObjectField(textQuad, m_javaGlue.m_quadFP1);
617    jobject p2 = env->GetObjectField(textQuad, m_javaGlue.m_quadFP2);
618    jobject p3 = env->GetObjectField(textQuad, m_javaGlue.m_quadFP3);
619    jobject p4 = env->GetObjectField(textQuad, m_javaGlue.m_quadFP4);
620    GraphicsJNI::point_to_jpointf(nativeTextQuad.p1(), env, p1);
621    GraphicsJNI::point_to_jpointf(nativeTextQuad.p2(), env, p2);
622    GraphicsJNI::point_to_jpointf(nativeTextQuad.p3(), env, p3);
623    GraphicsJNI::point_to_jpointf(nativeTextQuad.p4(), env, p4);
624    env->DeleteLocalRef(p1);
625    env->DeleteLocalRef(p2);
626    env->DeleteLocalRef(p3);
627    env->DeleteLocalRef(p4);
628}
629
630// This is called when WebView switches rendering modes in a more permanent fashion
631// such as when the layer type is set or the view is attached/detached from the window
632int setHwAccelerated(bool hwAccelerated) {
633    if (!m_glWebViewState)
634        return 0;
635    LayerAndroid* root = m_baseLayer;
636    if (root)
637        return root->setHwAccelerated(hwAccelerated);
638    return 0;
639}
640
641void setDrawingPaused(bool isPaused)
642{
643    m_isDrawingPaused = isPaused;
644    if (m_viewImpl)
645        m_viewImpl->setPrerenderingEnabled(!isPaused);
646}
647
648// Finds the rectangles within world to the left, right, top, and bottom
649// of rect and adds them to rects. If no intersection exists, false is returned.
650static bool findMaskedRects(const FloatRect& world,
651        const FloatRect& rect, Vector<FloatRect>& rects) {
652    if (!world.intersects(rect))
653        return false; // nothing to subtract
654
655    // left rectangle
656    if (rect.x() > world.x())
657        rects.append(FloatRect(world.x(), world.y(),
658                rect.x() - world.x(), world.height()));
659    // top rectangle
660    if (rect.y() > world.y())
661        rects.append(FloatRect(world.x(), world.y(),
662                world.width(), rect.y() - world.y()));
663    // right rectangle
664    if (rect.maxX() < world.maxX())
665        rects.append(FloatRect(rect.maxX(), world.y(),
666                world.maxX() - rect.maxX(), world.height()));
667    // bottom rectangle
668    if (rect.maxY() < world.maxY())
669        rects.append(FloatRect(world.x(), rect.maxY(),
670                world.width(), world.maxY() - rect.maxY()));
671    return true;
672}
673
674// Returns false if layerId is a fixed position layer, otherwise
675// all fixed position layer rectangles are subtracted from those within
676// rects. Rects will be modified to contain rectangles that don't include
677// the fixed position layer rectangles.
678static bool findMaskedRectsForLayer(LayerAndroid* layer,
679        Vector<FloatRect>& rects, int layerId)
680{
681    if (layer->isPositionFixed()) {
682        if (layerId == layer->uniqueId())
683            return false;
684        FloatRect layerRect = layer->fullContentAreaMapped();
685        for (int i = rects.size() - 1; i >= 0; i--)
686            if (findMaskedRects(rects[i], layerRect, rects))
687                rects.remove(i);
688    }
689
690    int childIndex = 0;
691    while (LayerAndroid* child = layer->getChild(childIndex++))
692        if (!findMaskedRectsForLayer(child, rects, layerId))
693            return false;
694
695    return true;
696}
697
698// Finds the largest rectangle not masked by any fixed layer.
699void findMaxVisibleRect(int movingLayerId, SkIRect& visibleContentRect)
700{
701    if (!m_baseLayer)
702        return;
703
704    FloatRect visibleContentFloatRect(visibleContentRect);
705    m_baseLayer->updatePositionsRecursive(visibleContentFloatRect);
706    Vector<FloatRect> rects;
707    rects.append(visibleContentFloatRect);
708    if (findMaskedRectsForLayer(m_baseLayer, rects, movingLayerId)) {
709        float maxSize = 0.0;
710        const FloatRect* largest = 0;
711        for (int i = 0; i < rects.size(); i++) {
712            const FloatRect& rect = rects[i];
713            float size = rect.width() * rect.height();
714            if (size > maxSize) {
715                maxSize = size;
716                largest = &rect;
717            }
718        }
719        if (largest) {
720            SkRect largeRect = *largest;
721            largeRect.round(&visibleContentRect);
722        }
723    }
724}
725
726private: // local state for WebView
727    bool m_isDrawingPaused;
728    // private to getFrameCache(); other functions operate in a different thread
729    WebViewCore* m_viewImpl;
730    int m_generation; // associate unique ID with sent kit focus to match with ui
731    // Corresponds to the same-named boolean on the java side.
732    bool m_heightCanMeasure;
733    int m_lastDx;
734    SkMSec m_lastDxTime;
735    DrawExtra* m_extras[DRAW_EXTRAS_SIZE];
736    BaseLayerAndroid* m_baseLayer;
737    Functor* m_glDrawFunctor;
738#if USE(ACCELERATED_COMPOSITING)
739    GLWebViewState* m_glWebViewState;
740#endif
741    SkRect m_visibleContentRect;
742    bool m_isHighEndGfx;
743}; // end of WebView class
744
745
746/**
747 * This class holds a function pointer and parameters for calling drawGL into a specific
748 * viewport. The pointer to the Functor will be put on a framework display list to be called
749 * when the display list is replayed.
750 */
751class GLDrawFunctor : Functor {
752    public:
753    GLDrawFunctor(WebView* _wvInstance,
754            int (WebView::*_funcPtr)(WebCore::IntRect&, WebCore::IntRect*,
755                    WebCore::IntRect&, int, WebCore::IntRect&, jfloat, jint, bool),
756            WebCore::IntRect _invScreenRect, float _scale, int _extras) {
757        wvInstance = _wvInstance;
758        funcPtr = _funcPtr;
759        invScreenRect = _invScreenRect;
760        scale = _scale;
761        extras = _extras;
762    };
763
764    status_t operator()(int messageId, void* data) {
765        TRACE_METHOD();
766        bool shouldDraw = (messageId == uirenderer::DrawGlInfo::kModeDraw);
767        if (shouldDraw)
768            wvInstance->updateRectsForGL();
769
770        if (invScreenRect.isEmpty()) {
771            // NOOP operation if viewport is empty
772            return 0;
773        }
774
775        WebCore::IntRect inval;
776        int titlebarHeight = screenRect.height() - invScreenRect.height();
777
778        uirenderer::DrawGlInfo* info = reinterpret_cast<uirenderer::DrawGlInfo*>(data);
779        WebCore::IntRect screenClip(info->clipLeft, info->clipTop,
780                                    info->clipRight - info->clipLeft,
781                                    info->clipBottom - info->clipTop);
782
783        WebCore::IntRect localInvScreenRect = invScreenRect;
784        if (info->isLayer) {
785            // When webview is on a layer, we need to use the viewport relative
786            // to the FBO, rather than the screen(which will use invScreenRect).
787            localInvScreenRect.setX(screenClip.x());
788            localInvScreenRect.setY(info->height - screenClip.y() - screenClip.height());
789        }
790        // Send the necessary info to the shader.
791        TilesManager::instance()->shader()->setGLDrawInfo(info);
792
793        int returnFlags = (*wvInstance.*funcPtr)(localInvScreenRect, &inval, screenRect,
794                titlebarHeight, screenClip, scale, extras, shouldDraw);
795        if ((returnFlags & uirenderer::DrawGlInfo::kStatusDraw) != 0) {
796            IntRect finalInval;
797            if (inval.isEmpty())
798                finalInval = screenRect;
799            else {
800                finalInval.setX(screenRect.x() + inval.x());
801                finalInval.setY(screenRect.y() + titlebarHeight + inval.y());
802                finalInval.setWidth(inval.width());
803                finalInval.setHeight(inval.height());
804            }
805            info->dirtyLeft = finalInval.x();
806            info->dirtyTop = finalInval.y();
807            info->dirtyRight = finalInval.maxX();
808            info->dirtyBottom = finalInval.maxY();
809        }
810        // return 1 if invalidation needed, 2 to request non-drawing functor callback, 0 otherwise
811        ALOGV("returnFlags are %d, shouldDraw %d", returnFlags, shouldDraw);
812        return returnFlags;
813    }
814    void updateScreenRect(WebCore::IntRect& _screenRect) {
815        screenRect = _screenRect;
816    }
817    void updateInvScreenRect(WebCore::IntRect& _invScreenRect) {
818        invScreenRect = _invScreenRect;
819    }
820    void updateScale(float _scale) {
821        scale = _scale;
822    }
823    void updateExtras(jint _extras) {
824        extras = _extras;
825    }
826    private:
827    WebView* wvInstance;
828    int (WebView::*funcPtr)(WebCore::IntRect&, WebCore::IntRect*,
829            WebCore::IntRect&, int, WebCore::IntRect&, float, int, bool);
830    WebCore::IntRect invScreenRect;
831    WebCore::IntRect screenRect;
832    jfloat scale;
833    jint extras;
834};
835
836/*
837 * Native JNI methods
838 */
839
840static void nativeCreate(JNIEnv *env, jobject obj, int viewImpl,
841                         jstring drawableDir, jboolean isHighEndGfx)
842{
843    WTF::String dir = jstringToWtfString(env, drawableDir);
844    new WebView(env, obj, viewImpl, dir, isHighEndGfx);
845    // NEED THIS OR SOMETHING LIKE IT!
846    //Release(obj);
847}
848
849static WebCore::IntRect jrect_to_webrect(JNIEnv* env, jobject obj)
850{
851    if (obj) {
852        int L, T, R, B;
853        GraphicsJNI::get_jrect(env, obj, &L, &T, &R, &B);
854        return WebCore::IntRect(L, T, R - L, B - T);
855    } else
856        return WebCore::IntRect();
857}
858
859static SkRect jrectf_to_rect(JNIEnv* env, jobject obj)
860{
861    SkRect rect = SkRect::MakeEmpty();
862    if (obj)
863        GraphicsJNI::jrectf_to_rect(env, obj, &rect);
864    return rect;
865}
866
867static void nativeDraw(JNIEnv *env, jobject obj, jobject canv,
868        jobject visible, jint color,
869        jint extras) {
870    SkCanvas* canvas = GraphicsJNI::getNativeCanvas(env, canv);
871    WebView* webView = GET_NATIVE_VIEW(env, obj);
872    SkRect visibleContentRect = jrectf_to_rect(env, visible);
873    webView->setVisibleContentRect(visibleContentRect);
874    webView->draw(canvas, color, static_cast<WebView::DrawExtras>(extras));
875}
876
877static jint nativeCreateDrawGLFunction(JNIEnv *env, jobject obj, jint nativeView,
878                                       jobject jinvscreenrect, jobject jscreenrect,
879                                       jobject jvisiblecontentrect,
880                                       jfloat scale, jint extras) {
881    WebCore::IntRect invScreenRect = jrect_to_webrect(env, jinvscreenrect);
882    WebView *wvInstance = reinterpret_cast<WebView*>(nativeView);
883    SkRect visibleContentRect = jrectf_to_rect(env, jvisiblecontentrect);
884    wvInstance->setVisibleContentRect(visibleContentRect);
885
886    GLDrawFunctor* functor = (GLDrawFunctor*) wvInstance->getFunctor();
887    if (!functor) {
888        functor = new GLDrawFunctor(wvInstance, &android::WebView::drawGL,
889                                    invScreenRect, scale, extras);
890        wvInstance->setFunctor((Functor*) functor);
891    } else {
892        functor->updateInvScreenRect(invScreenRect);
893        functor->updateScale(scale);
894        functor->updateExtras(extras);
895    }
896
897    WebCore::IntRect rect = jrect_to_webrect(env, jscreenrect);
898    functor->updateScreenRect(rect);
899
900    return (jint)functor;
901}
902
903static jint nativeGetDrawGLFunction(JNIEnv *env, jobject obj, jint nativeView) {
904    WebView *wvInstance = reinterpret_cast<WebView*>(nativeView);
905    if (!wvInstance)
906        return 0;
907
908    return (jint) wvInstance->getFunctor();
909}
910
911static void nativeUpdateDrawGLFunction(JNIEnv *env, jobject obj, jint nativeView,
912                                       jobject jinvscreenrect, jobject jscreenrect,
913                                       jobject jvisiblecontentrect, jfloat scale) {
914    WebView *wvInstance = reinterpret_cast<WebView*>(nativeView);
915    if (wvInstance) {
916        GLDrawFunctor* functor = (GLDrawFunctor*) wvInstance->getFunctor();
917        if (functor) {
918            WebCore::IntRect invScreenRect = jrect_to_webrect(env, jinvscreenrect);
919            functor->updateInvScreenRect(invScreenRect);
920
921            SkRect visibleContentRect = jrectf_to_rect(env, jvisiblecontentrect);
922            wvInstance->setVisibleContentRect(visibleContentRect);
923
924            WebCore::IntRect screenRect = jrect_to_webrect(env, jscreenrect);
925            functor->updateScreenRect(screenRect);
926
927            functor->updateScale(scale);
928        }
929    }
930}
931
932static bool nativeEvaluateLayersAnimations(JNIEnv *env, jobject obj, jint nativeView)
933{
934    // only call in software rendering, initialize and evaluate animations
935#if USE(ACCELERATED_COMPOSITING)
936    BaseLayerAndroid* baseLayer = reinterpret_cast<WebView*>(nativeView)->getBaseLayer();
937    if (baseLayer) {
938        baseLayer->initAnimations();
939        return baseLayer->evaluateAnimations();
940    }
941#endif
942    return false;
943}
944
945static bool nativeSetBaseLayer(JNIEnv *env, jobject obj, jint nativeView, jint layer,
946                               jboolean showVisualIndicator,
947                               jboolean isPictureAfterFirstLayout,
948                               jint scrollingLayer)
949{
950    BaseLayerAndroid* layerImpl = reinterpret_cast<BaseLayerAndroid*>(layer);
951    return reinterpret_cast<WebView*>(nativeView)->setBaseLayer(layerImpl, showVisualIndicator,
952                                                                isPictureAfterFirstLayout,
953                                                                scrollingLayer);
954}
955
956static BaseLayerAndroid* nativeGetBaseLayer(JNIEnv *env, jobject obj, jint nativeView)
957{
958    return reinterpret_cast<WebView*>(nativeView)->getBaseLayer();
959}
960
961static void nativeCopyBaseContentToPicture(JNIEnv *env, jobject obj, jobject pict)
962{
963    SkPicture* picture = GraphicsJNI::getNativePicture(env, pict);
964    GET_NATIVE_VIEW(env, obj)->copyBaseContentToPicture(picture);
965}
966
967static bool nativeHasContent(JNIEnv *env, jobject obj)
968{
969    return GET_NATIVE_VIEW(env, obj)->hasContent();
970}
971
972static void nativeSetHeightCanMeasure(JNIEnv *env, jobject obj, bool measure)
973{
974    WebView* view = GET_NATIVE_VIEW(env, obj);
975    ALOG_ASSERT(view, "view not set in nativeSetHeightCanMeasure");
976    view->setHeightCanMeasure(measure);
977}
978
979static void nativeDestroy(JNIEnv *env, jobject obj)
980{
981    WebView* view = GET_NATIVE_VIEW(env, obj);
982    ALOGD("nativeDestroy view: %p", view);
983    ALOG_ASSERT(view, "view not set in nativeDestroy");
984    delete view;
985}
986
987static void nativeStopGL(JNIEnv *env, jobject obj)
988{
989    GET_NATIVE_VIEW(env, obj)->stopGL();
990}
991
992static jobject nativeGetSelection(JNIEnv *env, jobject obj)
993{
994    WebView* view = GET_NATIVE_VIEW(env, obj);
995    ALOG_ASSERT(view, "view not set in %s", __FUNCTION__);
996    String selection = view->getSelection();
997    return wtfStringToJstring(env, selection);
998}
999
1000static void nativeDiscardAllTextures(JNIEnv *env, jobject obj)
1001{
1002    //discard all textures for debugging/test purposes, but not gl backing memory
1003    bool allTextures = true, deleteGLTextures = false;
1004    TilesManager::instance()->discardTextures(allTextures, deleteGLTextures);
1005}
1006
1007static void nativeTileProfilingStart(JNIEnv *env, jobject obj)
1008{
1009    TilesManager::instance()->getProfiler()->start();
1010}
1011
1012static float nativeTileProfilingStop(JNIEnv *env, jobject obj)
1013{
1014    return TilesManager::instance()->getProfiler()->stop();
1015}
1016
1017static void nativeTileProfilingClear(JNIEnv *env, jobject obj)
1018{
1019    TilesManager::instance()->getProfiler()->clear();
1020}
1021
1022static int nativeTileProfilingNumFrames(JNIEnv *env, jobject obj)
1023{
1024    return TilesManager::instance()->getProfiler()->numFrames();
1025}
1026
1027static int nativeTileProfilingNumTilesInFrame(JNIEnv *env, jobject obj, int frame)
1028{
1029    return TilesManager::instance()->getProfiler()->numTilesInFrame(frame);
1030}
1031
1032static int nativeTileProfilingGetInt(JNIEnv *env, jobject obj, int frame, int tile, jstring jkey)
1033{
1034    WTF::String key = jstringToWtfString(env, jkey);
1035    TileProfileRecord* record = TilesManager::instance()->getProfiler()->getTile(frame, tile);
1036
1037    if (key == "left")
1038        return record->left;
1039    if (key == "top")
1040        return record->top;
1041    if (key == "right")
1042        return record->right;
1043    if (key == "bottom")
1044        return record->bottom;
1045    if (key == "level")
1046        return record->level;
1047    if (key == "isReady")
1048        return record->isReady ? 1 : 0;
1049    return -1;
1050}
1051
1052static float nativeTileProfilingGetFloat(JNIEnv *env, jobject obj, int frame, int tile, jstring jkey)
1053{
1054    TileProfileRecord* record = TilesManager::instance()->getProfiler()->getTile(frame, tile);
1055    return record->scale;
1056}
1057
1058#ifdef ANDROID_DUMP_DISPLAY_TREE
1059static void dumpToFile(const char text[], void* file) {
1060    fwrite(text, 1, strlen(text), reinterpret_cast<FILE*>(file));
1061    fwrite("\n", 1, 1, reinterpret_cast<FILE*>(file));
1062}
1063#endif
1064
1065// Return true to view invalidate WebView
1066static bool nativeSetProperty(JNIEnv *env, jobject obj, jstring jkey, jstring jvalue)
1067{
1068    WTF::String key = jstringToWtfString(env, jkey);
1069    WTF::String value = jstringToWtfString(env, jvalue);
1070    if (key == "inverted") {
1071        bool shouldInvert = (value == "true");
1072        TilesManager::instance()->setInvertedScreen(shouldInvert);
1073        return true;
1074    }
1075    else if (key == "inverted_contrast") {
1076        float contrast = value.toFloat();
1077        TilesManager::instance()->setInvertedScreenContrast(contrast);
1078        return true;
1079    }
1080    else if (key == "enable_cpu_upload_path") {
1081        TilesManager::instance()->transferQueue()->setTextureUploadType(
1082            value == "true" ? CpuUpload : GpuUpload);
1083    }
1084    else if (key == "use_minimal_memory") {
1085        TilesManager::instance()->setUseMinimalMemory(value == "true");
1086    }
1087    else if (key == "use_double_buffering") {
1088        TilesManager::instance()->setUseDoubleBuffering(value == "true");
1089    }
1090    else if (key == "tree_updates") {
1091        TilesManager::instance()->clearContentUpdates();
1092    }
1093    return false;
1094}
1095
1096static jstring nativeGetProperty(JNIEnv *env, jobject obj, jstring jkey)
1097{
1098    WTF::String key = jstringToWtfString(env, jkey);
1099    if (key == "tree_updates") {
1100        int updates = TilesManager::instance()->getContentUpdates();
1101        WTF::String wtfUpdates = WTF::String::number(updates);
1102        return wtfStringToJstring(env, wtfUpdates);
1103    }
1104    return 0;
1105}
1106
1107static void nativeOnTrimMemory(JNIEnv *env, jobject obj, jint level)
1108{
1109    if (TilesManager::hardwareAccelerationEnabled()) {
1110        // When we got TRIM_MEMORY_MODERATE or TRIM_MEMORY_COMPLETE, we should
1111        // make sure the transfer queue is empty and then abandon the Surface
1112        // Texture to avoid ANR b/c framework may destroy the EGL context.
1113        // Refer to WindowManagerImpl.java for conditions we followed.
1114        TilesManager* tilesManager = TilesManager::instance();
1115        if ((level >= TRIM_MEMORY_MODERATE
1116            && !tilesManager->highEndGfx())
1117            || level >= TRIM_MEMORY_COMPLETE) {
1118            ALOGD("OnTrimMemory with EGL Context %p", eglGetCurrentContext());
1119            tilesManager->cleanupGLResources();
1120        }
1121
1122        bool freeAllTextures = (level > TRIM_MEMORY_UI_HIDDEN), glTextures = true;
1123        tilesManager->discardTextures(freeAllTextures, glTextures);
1124    }
1125}
1126
1127static void nativeDumpDisplayTree(JNIEnv* env, jobject jwebview, jstring jurl)
1128{
1129#ifdef ANDROID_DUMP_DISPLAY_TREE
1130    WebView* view = GET_NATIVE_VIEW(env, jwebview);
1131    ALOG_ASSERT(view, "view not set in %s", __FUNCTION__);
1132
1133    if (view && view->getWebViewCore()) {
1134        FILE* file = fopen(DISPLAY_TREE_LOG_FILE, "w");
1135        if (file) {
1136            SkFormatDumper dumper(dumpToFile, file);
1137            // dump the URL
1138            if (jurl) {
1139                const char* str = env->GetStringUTFChars(jurl, 0);
1140                SkDebugf("Dumping %s to %s\n", str, DISPLAY_TREE_LOG_FILE);
1141                dumpToFile(str, file);
1142                env->ReleaseStringUTFChars(jurl, str);
1143            }
1144            // now dump the display tree
1145            SkDumpCanvas canvas(&dumper);
1146            // this will playback the picture into the canvas, which will
1147            // spew its contents to the dumper
1148            view->draw(&canvas, 0, WebView::DrawExtrasNone);
1149            // we're done with the file now
1150            fwrite("\n", 1, 1, file);
1151            fclose(file);
1152        }
1153#if USE(ACCELERATED_COMPOSITING)
1154        const LayerAndroid* baseLayer = view->getBaseLayer();
1155        if (baseLayer) {
1156          FILE* file = fopen(LAYERS_TREE_LOG_FILE,"w");
1157          if (file) {
1158              baseLayer->dumpLayers(file, 0);
1159              fclose(file);
1160          }
1161        }
1162#endif
1163    }
1164#endif
1165}
1166
1167static int nativeScrollableLayer(JNIEnv* env, jobject jwebview, jint nativeView,
1168    jint x, jint y, jobject rect, jobject bounds)
1169{
1170    WebView* webview = reinterpret_cast<WebView*>(nativeView);
1171    ALOG_ASSERT(webview, "webview not set in %s", __FUNCTION__);
1172    SkIRect nativeRect, nativeBounds;
1173    int id = webview->scrollableLayer(x, y, &nativeRect, &nativeBounds);
1174    if (rect)
1175        GraphicsJNI::irect_to_jrect(nativeRect, env, rect);
1176    if (bounds)
1177        GraphicsJNI::irect_to_jrect(nativeBounds, env, bounds);
1178    return id;
1179}
1180
1181static bool nativeScrollLayer(JNIEnv* env, jobject obj,
1182    jint nativeView, jint layerId, jint x, jint y)
1183{
1184#if ENABLE(ANDROID_OVERFLOW_SCROLL)
1185    WebView* webview = reinterpret_cast<WebView*>(nativeView);
1186    webview->scrollLayer(layerId, x, y);
1187
1188    //TODO: the below only needed for the SW rendering path
1189    LayerAndroid* baseLayer = webview->getBaseLayer();
1190    if (!baseLayer)
1191        return false;
1192    LayerAndroid* layer = baseLayer->findById(layerId);
1193    if (!layer || !layer->contentIsScrollable())
1194        return false;
1195    return static_cast<ScrollableLayerAndroid*>(layer)->scrollTo(x, y);
1196#endif
1197    return false;
1198}
1199
1200static void nativeSetIsScrolling(JNIEnv* env, jobject jwebview, jboolean isScrolling)
1201{
1202    // TODO: Pass in the native pointer instead
1203    WebView* view = GET_NATIVE_VIEW(env, jwebview);
1204    if (view)
1205        view->setIsScrolling(isScrolling);
1206}
1207
1208static void nativeUseHardwareAccelSkia(JNIEnv*, jobject, jboolean enabled)
1209{
1210    BaseRenderer::setCurrentRendererType(enabled ? BaseRenderer::Ganesh : BaseRenderer::Raster);
1211}
1212
1213static int nativeGetBackgroundColor(JNIEnv* env, jobject obj, jint nativeView)
1214{
1215    WebView* view = reinterpret_cast<WebView*>(nativeView);
1216    BaseLayerAndroid* baseLayer = view->getBaseLayer();
1217    if (baseLayer) {
1218        WebCore::Color color = baseLayer->getBackgroundColor();
1219        if (color.isValid())
1220            return SkColorSetARGB(color.alpha(), color.red(),
1221                                  color.green(), color.blue());
1222    }
1223    return SK_ColorWHITE;
1224}
1225
1226static void nativeSetPauseDrawing(JNIEnv *env, jobject obj, jint nativeView,
1227                                      jboolean pause)
1228{
1229    reinterpret_cast<WebView*>(nativeView)->setDrawingPaused(pause);
1230}
1231
1232static void nativeSetTextSelection(JNIEnv *env, jobject obj, jint nativeView,
1233                                   jint selectionPtr)
1234{
1235    SelectText* selection = reinterpret_cast<SelectText*>(selectionPtr);
1236    reinterpret_cast<WebView*>(nativeView)->setTextSelection(selection);
1237}
1238
1239static jint nativeGetHandleLayerId(JNIEnv *env, jobject obj, jint nativeView,
1240                                     jint handleIndex, jobject cursorPoint,
1241                                     jobject textQuad)
1242{
1243    WebView* webview = reinterpret_cast<WebView*>(nativeView);
1244    SkIPoint nativePoint;
1245    FloatQuad nativeTextQuad;
1246    int layerId = webview->getHandleLayerId((SelectText::HandleId) handleIndex,
1247            nativePoint, nativeTextQuad);
1248    if (cursorPoint)
1249        GraphicsJNI::ipoint_to_jpoint(nativePoint, env, cursorPoint);
1250    if (textQuad)
1251        webview->floatQuadToQuadF(env, nativeTextQuad, textQuad);
1252    return layerId;
1253}
1254
1255static void nativeMapLayerRect(JNIEnv *env, jobject obj, jint nativeView,
1256        jint layerId, jobject rect)
1257{
1258    WebView* webview = reinterpret_cast<WebView*>(nativeView);
1259    SkIRect nativeRect;
1260    GraphicsJNI::jrect_to_irect(env, rect, &nativeRect);
1261    webview->mapLayerRect(layerId, nativeRect);
1262    GraphicsJNI::irect_to_jrect(nativeRect, env, rect);
1263}
1264
1265static jint nativeSetHwAccelerated(JNIEnv *env, jobject obj, jint nativeView,
1266        jboolean hwAccelerated)
1267{
1268    WebView* webview = reinterpret_cast<WebView*>(nativeView);
1269    return webview->setHwAccelerated(hwAccelerated);
1270}
1271
1272static void nativeFindMaxVisibleRect(JNIEnv *env, jobject obj, jint nativeView,
1273        jint movingLayerId, jobject visibleContentRect)
1274{
1275    WebView* webview = reinterpret_cast<WebView*>(nativeView);
1276    SkIRect nativeRect;
1277    GraphicsJNI::jrect_to_irect(env, visibleContentRect, &nativeRect);
1278    webview->findMaxVisibleRect(movingLayerId, nativeRect);
1279    GraphicsJNI::irect_to_jrect(nativeRect, env, visibleContentRect);
1280}
1281
1282/*
1283 * JNI registration
1284 */
1285static JNINativeMethod gJavaWebViewMethods[] = {
1286    { "nativeCreate", "(ILjava/lang/String;Z)V",
1287        (void*) nativeCreate },
1288    { "nativeDestroy", "()V",
1289        (void*) nativeDestroy },
1290    { "nativeDraw", "(Landroid/graphics/Canvas;Landroid/graphics/RectF;II)V",
1291        (void*) nativeDraw },
1292    { "nativeCreateDrawGLFunction", "(ILandroid/graphics/Rect;Landroid/graphics/Rect;Landroid/graphics/RectF;FI)I",
1293        (void*) nativeCreateDrawGLFunction },
1294    { "nativeGetDrawGLFunction", "(I)I",
1295        (void*) nativeGetDrawGLFunction },
1296    { "nativeUpdateDrawGLFunction", "(ILandroid/graphics/Rect;Landroid/graphics/Rect;Landroid/graphics/RectF;F)V",
1297        (void*) nativeUpdateDrawGLFunction },
1298    { "nativeDumpDisplayTree", "(Ljava/lang/String;)V",
1299        (void*) nativeDumpDisplayTree },
1300    { "nativeEvaluateLayersAnimations", "(I)Z",
1301        (void*) nativeEvaluateLayersAnimations },
1302    { "nativeGetSelection", "()Ljava/lang/String;",
1303        (void*) nativeGetSelection },
1304    { "nativeSetHeightCanMeasure", "(Z)V",
1305        (void*) nativeSetHeightCanMeasure },
1306    { "nativeSetBaseLayer", "(IIZZI)Z",
1307        (void*) nativeSetBaseLayer },
1308    { "nativeGetBaseLayer", "(I)I",
1309        (void*) nativeGetBaseLayer },
1310    { "nativeCopyBaseContentToPicture", "(Landroid/graphics/Picture;)V",
1311        (void*) nativeCopyBaseContentToPicture },
1312    { "nativeHasContent", "()Z",
1313        (void*) nativeHasContent },
1314    { "nativeDiscardAllTextures", "()V",
1315        (void*) nativeDiscardAllTextures },
1316    { "nativeTileProfilingStart", "()V",
1317        (void*) nativeTileProfilingStart },
1318    { "nativeTileProfilingStop", "()F",
1319        (void*) nativeTileProfilingStop },
1320    { "nativeTileProfilingClear", "()V",
1321        (void*) nativeTileProfilingClear },
1322    { "nativeTileProfilingNumFrames", "()I",
1323        (void*) nativeTileProfilingNumFrames },
1324    { "nativeTileProfilingNumTilesInFrame", "(I)I",
1325        (void*) nativeTileProfilingNumTilesInFrame },
1326    { "nativeTileProfilingGetInt", "(IILjava/lang/String;)I",
1327        (void*) nativeTileProfilingGetInt },
1328    { "nativeTileProfilingGetFloat", "(IILjava/lang/String;)F",
1329        (void*) nativeTileProfilingGetFloat },
1330    { "nativeStopGL", "()V",
1331        (void*) nativeStopGL },
1332    { "nativeScrollableLayer", "(IIILandroid/graphics/Rect;Landroid/graphics/Rect;)I",
1333        (void*) nativeScrollableLayer },
1334    { "nativeScrollLayer", "(IIII)Z",
1335        (void*) nativeScrollLayer },
1336    { "nativeSetIsScrolling", "(Z)V",
1337        (void*) nativeSetIsScrolling },
1338    { "nativeUseHardwareAccelSkia", "(Z)V",
1339        (void*) nativeUseHardwareAccelSkia },
1340    { "nativeGetBackgroundColor", "(I)I",
1341        (void*) nativeGetBackgroundColor },
1342    { "nativeSetProperty", "(Ljava/lang/String;Ljava/lang/String;)Z",
1343        (void*) nativeSetProperty },
1344    { "nativeGetProperty", "(Ljava/lang/String;)Ljava/lang/String;",
1345        (void*) nativeGetProperty },
1346    { "nativeOnTrimMemory", "(I)V",
1347        (void*) nativeOnTrimMemory },
1348    { "nativeSetPauseDrawing", "(IZ)V",
1349        (void*) nativeSetPauseDrawing },
1350    { "nativeSetTextSelection", "(II)V",
1351        (void*) nativeSetTextSelection },
1352    { "nativeGetHandleLayerId", "(IILandroid/graphics/Point;Landroid/webkit/QuadF;)I",
1353        (void*) nativeGetHandleLayerId },
1354    { "nativeMapLayerRect", "(IILandroid/graphics/Rect;)V",
1355        (void*) nativeMapLayerRect },
1356    { "nativeSetHwAccelerated", "(IZ)I",
1357        (void*) nativeSetHwAccelerated },
1358    { "nativeFindMaxVisibleRect", "(IILandroid/graphics/Rect;)V",
1359        (void*) nativeFindMaxVisibleRect },
1360};
1361
1362int registerWebView(JNIEnv* env)
1363{
1364    jclass clazz = env->FindClass("android/webkit/WebViewClassic");
1365    ALOG_ASSERT(clazz, "Unable to find class android/webkit/WebViewClassic");
1366    gWebViewField = env->GetFieldID(clazz, "mNativeClass", "I");
1367    ALOG_ASSERT(gWebViewField, "Unable to find android/webkit/WebViewClassic.mNativeClass");
1368    env->DeleteLocalRef(clazz);
1369
1370    return jniRegisterNativeMethods(env, "android/webkit/WebViewClassic", gJavaWebViewMethods, NELEM(gJavaWebViewMethods));
1371}
1372
1373} // namespace android
1374