OSDN Git Service

am eecdc5b2: am 4c6c5a28: Merge "Turns out args should not be decoded twice." into...
[android-x86/external-webkit.git] / WebKit / android / jni / WebCoreFrameBridge.cpp
1 /*
2  * Copyright 2006, 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 "webcoreglue"
27
28 #include "config.h"
29 #include "WebCoreFrameBridge.h"
30
31 #include "Arena.h"
32 #include "BackForwardList.h"
33 #include "MemoryCache.h"
34 #include "Chrome.h"
35 #include "ChromeClientAndroid.h"
36 #include "ChromiumInit.h"
37 #include "ContextMenuClientAndroid.h"
38 #include "DeviceMotionClientAndroid.h"
39 #include "DeviceOrientationClientAndroid.h"
40 #include "Document.h"
41 #include "DocumentLoader.h"
42 #include "DragClientAndroid.h"
43 #include "EditorClientAndroid.h"
44 #include "Element.h"
45 #include "FocusController.h"
46 #include "Font.h"
47 #include "Frame.h"
48 #include "FrameLoader.h"
49 #include "FrameLoaderClientAndroid.h"
50 #include "FrameLoadRequest.h"
51 #include "FrameTree.h"
52 #include "FrameView.h"
53 #include "GraphicsContext.h"
54 #include "HistoryItem.h"
55 #include "HTMLCollection.h"
56 #include "HTMLElement.h"
57 #include "HTMLFormElement.h"
58 #include "HTMLInputElement.h"
59 #include "HTMLNames.h"
60 #include "IconDatabase.h"
61 #include "Image.h"
62 #include "InspectorClientAndroid.h"
63 #include "KURL.h"
64 #include "Page.h"
65 #include "PageCache.h"
66 #include "PlatformString.h"
67 #include "RenderPart.h"
68 #include "RenderSkinAndroid.h"
69 #include "RenderTreeAsText.h"
70 #include "RenderView.h"
71 #include "ResourceHandle.h"
72 #include "ResourceHandleInternal.h"
73 #include "ScriptController.h"
74 #include "ScriptValue.h"
75 #include "SecurityOrigin.h"
76 #include "SelectionController.h"
77 #include "Settings.h"
78 #include "SubstituteData.h"
79 #include "UrlInterceptResponse.h"
80 #include "UserGestureIndicator.h"
81 #include "WebCache.h"
82 #include "WebCoreJni.h"
83 #include "WebCoreResourceLoader.h"
84 #include "WebHistory.h"
85 #include "WebIconDatabase.h"
86 #include "WebFrameView.h"
87 #include "WebUrlLoaderClient.h"
88 #include "WebViewCore.h"
89 #include "android_graphics.h"
90 #include "jni.h"
91 #include "wds/DebugServer.h"
92
93 #include <JNIUtility.h>
94 #include <JNIHelp.h>
95 #include <SkGraphics.h>
96 #include <android_runtime/android_util_AssetManager.h>
97 #include <utils/misc.h>
98 #include <utils/AssetManager.h>
99 #include <wtf/CurrentTime.h>
100 #include <wtf/Platform.h>
101 #include <wtf/text/AtomicString.h>
102 #include <wtf/text/CString.h>
103 #include <wtf/text/StringBuilder.h>
104
105 #if USE(JSC)
106 #include "GCController.h"
107 #include "JSDOMWindow.h"
108 #include "JavaInstanceJSC.h"
109 #include <runtime_object.h>
110 #include <runtime_root.h>
111 #include <runtime/JSLock.h>
112 #elif USE(V8)
113 #include "JavaNPObjectV8.h"
114 #include "JavaInstanceV8.h"
115 #include "V8Counters.h"
116 #endif  // USE(JSC)
117
118 #ifdef ANDROID_INSTRUMENT
119 #include "TimeCounter.h"
120 #endif
121
122 #if ENABLE(ARCHIVE)
123 #include "WebArchiveAndroid.h"
124 #endif
125
126 #if ENABLE(WEB_AUTOFILL)
127 #include "autofill/WebAutoFill.h"
128 #endif
129
130 using namespace JSC::Bindings;
131
132 static String* gUploadFileLabel;
133 static String* gResetLabel;
134 static String* gSubmitLabel;
135 static String* gNoFileChosenLabel;
136
137 String* WebCore::PlatformBridge::globalLocalizedName(
138         WebCore::PlatformBridge::rawResId resId)
139 {
140     switch (resId) {
141     case WebCore::PlatformBridge::FileUploadLabel:
142         return gUploadFileLabel;
143     case WebCore::PlatformBridge::ResetLabel:
144         return gResetLabel;
145     case WebCore::PlatformBridge::SubmitLabel:
146         return gSubmitLabel;
147     case WebCore::PlatformBridge::FileUploadNoFileChosenLabel:
148         return gNoFileChosenLabel;
149
150     default:
151         return 0;
152     }
153 }
154 /**
155  * Instantiate the localized name desired.
156  */
157 void initGlobalLocalizedName(WebCore::PlatformBridge::rawResId resId,
158         android::WebFrame* webFrame)
159 {
160     String** pointer;
161     switch (resId) {
162     case WebCore::PlatformBridge::FileUploadLabel:
163         pointer = &gUploadFileLabel;
164         break;
165     case WebCore::PlatformBridge::ResetLabel:
166         pointer = &gResetLabel;
167         break;
168     case WebCore::PlatformBridge::SubmitLabel:
169         pointer = &gSubmitLabel;
170         break;
171     case WebCore::PlatformBridge::FileUploadNoFileChosenLabel:
172         pointer = &gNoFileChosenLabel;
173         break;
174     default:
175         return;
176     }
177     if (!(*pointer) && webFrame) {
178         (*pointer) = new String(webFrame->getRawResourceFilename(resId).impl());
179     }
180 }
181
182 namespace android {
183
184 // ----------------------------------------------------------------------------
185
186 #define WEBCORE_MEMORY_CAP 15 * 1024 * 1024
187
188 // ----------------------------------------------------------------------------
189
190 struct WebFrame::JavaBrowserFrame
191 {
192     jweak       mObj;
193     jweak       mHistoryList; // WebBackForwardList object
194     jmethodID   mStartLoadingResource;
195     jmethodID   mMaybeSavePassword;
196     jmethodID   mShouldInterceptRequest;
197     jmethodID   mLoadStarted;
198     jmethodID   mTransitionToCommitted;
199     jmethodID   mLoadFinished;
200     jmethodID   mReportError;
201     jmethodID   mSetTitle;
202     jmethodID   mWindowObjectCleared;
203     jmethodID   mSetProgress;
204     jmethodID   mDidReceiveIcon;
205     jmethodID   mDidReceiveTouchIconUrl;
206     jmethodID   mUpdateVisitedHistory;
207     jmethodID   mHandleUrl;
208     jmethodID   mCreateWindow;
209     jmethodID   mCloseWindow;
210     jmethodID   mDecidePolicyForFormResubmission;
211     jmethodID   mRequestFocus;
212     jmethodID   mGetRawResFilename;
213     jmethodID   mDensity;
214     jmethodID   mGetFileSize;
215     jmethodID   mGetFile;
216     jmethodID   mDidReceiveAuthenticationChallenge;
217     jmethodID   mReportSslCertError;
218     jmethodID   mDownloadStart;
219     jmethodID   mDidReceiveData;
220     jmethodID   mDidFinishLoading;
221     jmethodID   mSetCertificate;
222     jmethodID   mShouldSaveFormData;
223     jmethodID   mSaveFormData;
224     jmethodID   mAutoLogin;
225     AutoJObject frame(JNIEnv* env) {
226         return getRealObject(env, mObj);
227     }
228     AutoJObject history(JNIEnv* env) {
229         return getRealObject(env, mHistoryList);
230     }
231 };
232
233 static jfieldID gFrameField;
234 #define GET_NATIVE_FRAME(env, obj) ((WebCore::Frame*)env->GetIntField(obj, gFrameField))
235 #define SET_NATIVE_FRAME(env, obj, frame) (env->SetIntField(obj, gFrameField, frame))
236
237 // ----------------------------------------------------------------------------
238
239 WebFrame::WebFrame(JNIEnv* env, jobject obj, jobject historyList, WebCore::Page* page)
240     : mPage(page)
241 {
242     jclass clazz = env->GetObjectClass(obj);
243     mJavaFrame = new JavaBrowserFrame;
244     mJavaFrame->mObj = env->NewWeakGlobalRef(obj);
245     mJavaFrame->mHistoryList = env->NewWeakGlobalRef(historyList);
246     mJavaFrame->mStartLoadingResource = env->GetMethodID(clazz, "startLoadingResource",
247             "(ILjava/lang/String;Ljava/lang/String;Ljava/util/HashMap;[BJIZZZLjava/lang/String;Ljava/lang/String;)Landroid/webkit/LoadListener;");
248     mJavaFrame->mMaybeSavePassword = env->GetMethodID(clazz, "maybeSavePassword",
249             "([BLjava/lang/String;Ljava/lang/String;)V");
250     mJavaFrame->mShouldInterceptRequest =
251             env->GetMethodID(clazz, "shouldInterceptRequest",
252             "(Ljava/lang/String;)Landroid/webkit/WebResourceResponse;");
253     mJavaFrame->mLoadStarted = env->GetMethodID(clazz, "loadStarted",
254             "(Ljava/lang/String;Landroid/graphics/Bitmap;IZ)V");
255     mJavaFrame->mTransitionToCommitted = env->GetMethodID(clazz, "transitionToCommitted",
256             "(IZ)V");
257     mJavaFrame->mLoadFinished = env->GetMethodID(clazz, "loadFinished",
258             "(Ljava/lang/String;IZ)V");
259     mJavaFrame->mReportError = env->GetMethodID(clazz, "reportError",
260             "(ILjava/lang/String;Ljava/lang/String;)V");
261     mJavaFrame->mSetTitle = env->GetMethodID(clazz, "setTitle",
262             "(Ljava/lang/String;)V");
263     mJavaFrame->mWindowObjectCleared = env->GetMethodID(clazz, "windowObjectCleared",
264             "(I)V");
265     mJavaFrame->mSetProgress = env->GetMethodID(clazz, "setProgress",
266             "(I)V");
267     mJavaFrame->mDidReceiveIcon = env->GetMethodID(clazz, "didReceiveIcon",
268             "(Landroid/graphics/Bitmap;)V");
269     mJavaFrame->mDidReceiveTouchIconUrl = env->GetMethodID(clazz, "didReceiveTouchIconUrl",
270             "(Ljava/lang/String;Z)V");
271     mJavaFrame->mUpdateVisitedHistory = env->GetMethodID(clazz, "updateVisitedHistory",
272             "(Ljava/lang/String;Z)V");
273     mJavaFrame->mHandleUrl = env->GetMethodID(clazz, "handleUrl",
274             "(Ljava/lang/String;)Z");
275     mJavaFrame->mCreateWindow = env->GetMethodID(clazz, "createWindow",
276             "(ZZ)Landroid/webkit/BrowserFrame;");
277     mJavaFrame->mCloseWindow = env->GetMethodID(clazz, "closeWindow",
278             "(Landroid/webkit/WebViewCore;)V");
279     mJavaFrame->mDecidePolicyForFormResubmission = env->GetMethodID(clazz,
280             "decidePolicyForFormResubmission", "(I)V");
281     mJavaFrame->mRequestFocus = env->GetMethodID(clazz, "requestFocus",
282             "()V");
283     mJavaFrame->mGetRawResFilename = env->GetMethodID(clazz, "getRawResFilename",
284             "(I)Ljava/lang/String;");
285     mJavaFrame->mDensity = env->GetMethodID(clazz, "density","()F");
286     mJavaFrame->mGetFileSize = env->GetMethodID(clazz, "getFileSize", "(Ljava/lang/String;)I");
287     mJavaFrame->mGetFile = env->GetMethodID(clazz, "getFile", "(Ljava/lang/String;[BII)I");
288     mJavaFrame->mDidReceiveAuthenticationChallenge = env->GetMethodID(clazz, "didReceiveAuthenticationChallenge",
289             "(ILjava/lang/String;Ljava/lang/String;Z)V");
290     mJavaFrame->mReportSslCertError = env->GetMethodID(clazz, "reportSslCertError", "(II[B)V");
291     mJavaFrame->mDownloadStart = env->GetMethodID(clazz, "downloadStart",
292             "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;J)V");
293     mJavaFrame->mDidReceiveData = env->GetMethodID(clazz, "didReceiveData", "([BI)V");
294     mJavaFrame->mDidFinishLoading = env->GetMethodID(clazz, "didFinishLoading", "()V");
295     mJavaFrame->mSetCertificate = env->GetMethodID(clazz, "setCertificate", "([B)V");
296     mJavaFrame->mShouldSaveFormData = env->GetMethodID(clazz, "shouldSaveFormData", "()Z");
297     mJavaFrame->mSaveFormData = env->GetMethodID(clazz, "saveFormData", "(Ljava/util/HashMap;)V");
298     mJavaFrame->mAutoLogin = env->GetMethodID(clazz, "autoLogin",
299             "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
300     env->DeleteLocalRef(clazz);
301
302     LOG_ASSERT(mJavaFrame->mStartLoadingResource, "Could not find method startLoadingResource");
303     LOG_ASSERT(mJavaFrame->mMaybeSavePassword, "Could not find method maybeSavePassword");
304     LOG_ASSERT(mJavaFrame->mShouldInterceptRequest, "Could not find method shouldInterceptRequest");
305     LOG_ASSERT(mJavaFrame->mLoadStarted, "Could not find method loadStarted");
306     LOG_ASSERT(mJavaFrame->mTransitionToCommitted, "Could not find method transitionToCommitted");
307     LOG_ASSERT(mJavaFrame->mLoadFinished, "Could not find method loadFinished");
308     LOG_ASSERT(mJavaFrame->mReportError, "Could not find method reportError");
309     LOG_ASSERT(mJavaFrame->mSetTitle, "Could not find method setTitle");
310     LOG_ASSERT(mJavaFrame->mWindowObjectCleared, "Could not find method windowObjectCleared");
311     LOG_ASSERT(mJavaFrame->mSetProgress, "Could not find method setProgress");
312     LOG_ASSERT(mJavaFrame->mDidReceiveIcon, "Could not find method didReceiveIcon");
313     LOG_ASSERT(mJavaFrame->mDidReceiveTouchIconUrl, "Could not find method didReceiveTouchIconUrl");
314     LOG_ASSERT(mJavaFrame->mUpdateVisitedHistory, "Could not find method updateVisitedHistory");
315     LOG_ASSERT(mJavaFrame->mHandleUrl, "Could not find method handleUrl");
316     LOG_ASSERT(mJavaFrame->mCreateWindow, "Could not find method createWindow");
317     LOG_ASSERT(mJavaFrame->mCloseWindow, "Could not find method closeWindow");
318     LOG_ASSERT(mJavaFrame->mDecidePolicyForFormResubmission, "Could not find method decidePolicyForFormResubmission");
319     LOG_ASSERT(mJavaFrame->mRequestFocus, "Could not find method requestFocus");
320     LOG_ASSERT(mJavaFrame->mGetRawResFilename, "Could not find method getRawResFilename");
321     LOG_ASSERT(mJavaFrame->mDensity, "Could not find method density");
322     LOG_ASSERT(mJavaFrame->mGetFileSize, "Could not find method getFileSize");
323     LOG_ASSERT(mJavaFrame->mGetFile, "Could not find method getFile");
324     LOG_ASSERT(mJavaFrame->mDidReceiveAuthenticationChallenge, "Could not find method didReceiveAuthenticationChallenge");
325     LOG_ASSERT(mJavaFrame->mReportSslCertError, "Could not find method reportSslCertError");
326     LOG_ASSERT(mJavaFrame->mDownloadStart, "Could not find method downloadStart");
327     LOG_ASSERT(mJavaFrame->mDidReceiveData, "Could not find method didReceiveData");
328     LOG_ASSERT(mJavaFrame->mDidFinishLoading, "Could not find method didFinishLoading");
329     LOG_ASSERT(mJavaFrame->mSetCertificate, "Could not find method setCertificate");
330     LOG_ASSERT(mJavaFrame->mShouldSaveFormData, "Could not find method shouldSaveFormData");
331     LOG_ASSERT(mJavaFrame->mSaveFormData, "Could not find method saveFormData");
332     LOG_ASSERT(mJavaFrame->mAutoLogin, "Could not find method autoLogin");
333
334     mUserAgent = WTF::String();
335     mUserInitiatedAction = false;
336     mBlockNetworkLoads = false;
337     m_renderSkins = 0;
338 }
339
340 WebFrame::~WebFrame()
341 {
342     if (mJavaFrame->mObj) {
343         JNIEnv* env = getJNIEnv();
344         env->DeleteWeakGlobalRef(mJavaFrame->mObj);
345         env->DeleteWeakGlobalRef(mJavaFrame->mHistoryList);
346         mJavaFrame->mObj = 0;
347     }
348     delete mJavaFrame;
349     delete m_renderSkins;
350 }
351
352 WebFrame* WebFrame::getWebFrame(const WebCore::Frame* frame)
353 {
354     FrameLoaderClientAndroid* client =
355             static_cast<FrameLoaderClientAndroid*> (frame->loader()->client());
356     return client->webFrame();
357 }
358
359 static jobject createJavaMapFromHTTPHeaders(JNIEnv* env, const WebCore::HTTPHeaderMap& map)
360 {
361     jclass mapClass = env->FindClass("java/util/HashMap");
362     LOG_ASSERT(mapClass, "Could not find HashMap class!");
363     jmethodID init = env->GetMethodID(mapClass, "<init>", "(I)V");
364     LOG_ASSERT(init, "Could not find constructor for HashMap");
365     jobject hashMap = env->NewObject(mapClass, init, map.size());
366     LOG_ASSERT(hashMap, "Could not create a new HashMap");
367     jmethodID put = env->GetMethodID(mapClass, "put",
368             "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
369     LOG_ASSERT(put, "Could not find put method on HashMap");
370
371     WebCore::HTTPHeaderMap::const_iterator end = map.end();
372     for (WebCore::HTTPHeaderMap::const_iterator i = map.begin(); i != end; ++i) {
373         if (i->first.length() == 0 || i->second.length() == 0)
374             continue;
375         jstring key = wtfStringToJstring(env, i->first);
376         jstring val = wtfStringToJstring(env, i->second);
377         if (key && val) {
378             env->CallObjectMethod(hashMap, put, key, val);
379         }
380         env->DeleteLocalRef(key);
381         env->DeleteLocalRef(val);
382     }
383
384     env->DeleteLocalRef(mapClass);
385
386     return hashMap;
387 }
388
389 // This class stores the URI and the size of each file for upload.  The URI is
390 // stored so we do not have to create it again.  The size is stored so we can
391 // compare the actual size of the file with the stated size.  If the actual size
392 // is larger, we will not copy it, since we will not have enough space in our
393 // buffer.
394 class FileInfo {
395 public:
396     FileInfo(JNIEnv* env, const WTF::String& name) {
397         m_uri = wtfStringToJstring(env, name);
398         checkException(env);
399         m_size = 0;
400         m_env = env;
401     }
402     ~FileInfo() {
403         m_env->DeleteLocalRef(m_uri);
404     }
405     int getSize() { return m_size; }
406     jstring getUri() { return m_uri; }
407     void setSize(int size) { m_size = size; }
408 private:
409     // This is only a pointer to the JNIEnv* returned by
410     // JSC::Bindings::getJNIEnv().  Used to delete the jstring when finished.
411     JNIEnv* m_env;
412     jstring m_uri;
413     int m_size;
414 };
415
416 PassRefPtr<WebCore::ResourceLoaderAndroid>
417 WebFrame::startLoadingResource(WebCore::ResourceHandle* loader,
418                                   const WebCore::ResourceRequest& request,
419                                   bool mainResource,
420                                   bool synchronous)
421 {
422 #ifdef ANDROID_INSTRUMENT
423     TimeCounterAuto counter(TimeCounter::JavaCallbackTimeCounter);
424 #endif
425     LOGV("::WebCore:: startLoadingResource(%p, %s)",
426             loader, request.url().string().latin1().data());
427
428     WTF::String method = request.httpMethod();
429     WebCore::HTTPHeaderMap headers = request.httpHeaderFields();
430
431     JNIEnv* env = getJNIEnv();
432     WTF::String urlStr = request.url().string();
433     int colon = urlStr.find(':');
434     bool allLower = true;
435     for (int index = 0; index < colon; index++) {
436         UChar ch = urlStr[index];
437         if (!WTF::isASCIIAlpha(ch))
438             break;
439         allLower &= WTF::isASCIILower(ch);
440         if (index == colon - 1 && !allLower) {
441             urlStr = urlStr.substring(0, colon).lower()
442                     + urlStr.substring(colon);
443         }
444     }
445     LOGV("%s lower=%s", __FUNCTION__, urlStr.latin1().data());
446     jstring jUrlStr = wtfStringToJstring(env, urlStr);
447     jstring jMethodStr = NULL;
448     if (!method.isEmpty())
449         jMethodStr = wtfStringToJstring(env, method);
450     WebCore::FormData* formdata = request.httpBody();
451     jbyteArray jPostDataStr = getPostData(request);
452     jobject jHeaderMap = createJavaMapFromHTTPHeaders(env, headers);
453
454     // Convert the WebCore Cache Policy to a WebView Cache Policy.
455     int cacheMode = 0;  // WebSettings.LOAD_NORMAL
456     switch (request.cachePolicy()) {
457         case WebCore::ReloadIgnoringCacheData:
458             cacheMode = 2; // WebSettings.LOAD_NO_CACHE
459             break;
460         case WebCore::ReturnCacheDataDontLoad:
461             cacheMode = 3; // WebSettings.LOAD_CACHE_ONLY
462             break;
463         case WebCore::ReturnCacheDataElseLoad:
464             cacheMode = 1;   // WebSettings.LOAD_CACHE_ELSE_NETWORK
465             break;
466         case WebCore::UseProtocolCachePolicy:
467         default:
468             break;
469     }
470
471     LOGV("::WebCore:: startLoadingResource %s with cacheMode %d", urlStr.ascii().data(), cacheMode);
472
473     ResourceHandleInternal* loaderInternal = loader->getInternal();
474     jstring jUsernameString = loaderInternal->m_user.isEmpty() ?
475             NULL : wtfStringToJstring(env, loaderInternal->m_user);
476     jstring jPasswordString = loaderInternal->m_pass.isEmpty() ?
477             NULL : wtfStringToJstring(env, loaderInternal->m_pass);
478
479     bool isUserGesture = UserGestureIndicator::processingUserGesture();
480     jobject jLoadListener =
481         env->CallObjectMethod(mJavaFrame->frame(env).get(), mJavaFrame->mStartLoadingResource,
482                 (int)loader, jUrlStr, jMethodStr, jHeaderMap,
483                 jPostDataStr, formdata ? formdata->identifier(): 0,
484                 cacheMode, mainResource, isUserGesture,
485                 synchronous, jUsernameString, jPasswordString);
486
487     env->DeleteLocalRef(jUrlStr);
488     env->DeleteLocalRef(jMethodStr);
489     env->DeleteLocalRef(jPostDataStr);
490     env->DeleteLocalRef(jHeaderMap);
491     env->DeleteLocalRef(jUsernameString);
492     env->DeleteLocalRef(jPasswordString);
493     if (checkException(env))
494         return NULL;
495
496     PassRefPtr<WebCore::ResourceLoaderAndroid> h;
497     if (jLoadListener)
498         h = WebCoreResourceLoader::create(env, jLoadListener);
499     env->DeleteLocalRef(jLoadListener);
500     return h;
501 }
502
503 UrlInterceptResponse*
504 WebFrame::shouldInterceptRequest(const WTF::String& url)
505 {
506 #ifdef ANDROID_INSTRUMENT
507     TimeCounterAuto counter(TimeCounter::JavaCallbackTimeCounter);
508 #endif
509     LOGV("::WebCore:: shouldInterceptRequest(%s)", url.latin1().data());
510
511     JNIEnv* env = getJNIEnv();
512     jstring urlStr = wtfStringToJstring(env, url);
513     jobject response = env->CallObjectMethod(mJavaFrame->frame(env).get(), mJavaFrame->mShouldInterceptRequest, urlStr);
514     env->DeleteLocalRef(urlStr);
515     if (response == 0)
516         return 0;
517     return new UrlInterceptResponse(env, response);
518 }
519
520 void
521 WebFrame::reportError(int errorCode, const WTF::String& description,
522         const WTF::String& failingUrl)
523 {
524 #ifdef ANDROID_INSTRUMENT
525     TimeCounterAuto counter(TimeCounter::JavaCallbackTimeCounter);
526 #endif
527     LOGV("::WebCore:: reportError(%d, %s)", errorCode, description.ascii().data());
528     JNIEnv* env = getJNIEnv();
529
530     jstring descStr = wtfStringToJstring(env, description);
531     jstring failUrl = wtfStringToJstring(env, failingUrl);
532     env->CallVoidMethod(mJavaFrame->frame(env).get(), mJavaFrame->mReportError,
533             errorCode, descStr, failUrl);
534     env->DeleteLocalRef(descStr);
535     env->DeleteLocalRef(failUrl);
536 }
537
538 void
539 WebFrame::loadStarted(WebCore::Frame* frame)
540 {
541 #ifdef ANDROID_INSTRUMENT
542     TimeCounterAuto counter(TimeCounter::JavaCallbackTimeCounter);
543 #endif
544     // activeDocumentLoader() can return null.
545     DocumentLoader* documentLoader = frame->loader()->activeDocumentLoader();
546     if (documentLoader == NULL)
547         return;
548
549     const WebCore::KURL& url = documentLoader->url();
550     if (url.isEmpty())
551         return;
552     LOGV("::WebCore:: loadStarted %s", url.string().ascii().data());
553
554     bool isMainFrame = (!frame->tree() || !frame->tree()->parent());
555     WebCore::FrameLoadType loadType = frame->loader()->loadType();
556
557     if (loadType == WebCore::FrameLoadTypeReplace ||
558             (loadType == WebCore::FrameLoadTypeRedirectWithLockedBackForwardList &&
559              !isMainFrame))
560         return;
561
562     JNIEnv* env = getJNIEnv();
563     const WTF::String& urlString = url.string();
564     // If this is the main frame and we already have a favicon in the database,
565     // send it along with the page started notification.
566     jobject favicon = NULL;
567     if (isMainFrame) {
568         WebCore::Image* icon = WebCore::iconDatabase()->iconForPageURL(urlString, WebCore::IntSize(16, 16));
569         if (icon)
570             favicon = webcoreImageToJavaBitmap(env, icon);
571         LOGV("favicons", "Starting load with icon %p for %s", icon, url.string().utf8().data());
572     }
573     jstring urlStr = wtfStringToJstring(env, urlString);
574
575     env->CallVoidMethod(mJavaFrame->frame(env).get(), mJavaFrame->mLoadStarted, urlStr, favicon,
576             (int)loadType, isMainFrame);
577     checkException(env);
578     env->DeleteLocalRef(urlStr);
579     if (favicon)
580         env->DeleteLocalRef(favicon);
581
582     // Inform the client that the main frame has started a new load.
583     if (isMainFrame && mPage) {
584         Chrome* chrome = mPage->chrome();
585         if (chrome) {
586             ChromeClientAndroid* client = static_cast<ChromeClientAndroid*>(chrome->client());
587             if (client)
588                 client->onMainFrameLoadStarted();
589         }
590     }
591 }
592
593 void
594 WebFrame::transitionToCommitted(WebCore::Frame* frame)
595 {
596 #ifdef ANDROID_INSTRUMENT
597     TimeCounterAuto counter(TimeCounter::JavaCallbackTimeCounter);
598 #endif
599     JNIEnv* env = getJNIEnv();
600     WebCore::FrameLoadType loadType = frame->loader()->loadType();
601     bool isMainFrame = (!frame->tree() || !frame->tree()->parent());
602     env->CallVoidMethod(mJavaFrame->frame(env).get(), mJavaFrame->mTransitionToCommitted,
603             (int)loadType, isMainFrame);
604     checkException(env);
605 }
606
607 void
608 WebFrame::didFinishLoad(WebCore::Frame* frame)
609 {
610 #ifdef ANDROID_INSTRUMENT
611     TimeCounterAuto counter(TimeCounter::JavaCallbackTimeCounter);
612 #endif
613     JNIEnv* env = getJNIEnv();
614
615     // activeDocumentLoader() can return null.
616     WebCore::FrameLoader* loader = frame->loader();
617     DocumentLoader* documentLoader = loader->activeDocumentLoader();
618     if (documentLoader == NULL)
619       return;
620
621     const WebCore::KURL& url = documentLoader->url();
622     if (url.isEmpty())
623         return;
624     LOGV("::WebCore:: didFinishLoad %s", url.string().ascii().data());
625
626     bool isMainFrame = (!frame->tree() || !frame->tree()->parent());
627     WebCore::FrameLoadType loadType = loader->loadType();
628     const WTF::String& urlString = url.string();
629     jstring urlStr = wtfStringToJstring(env, urlString);
630     env->CallVoidMethod(mJavaFrame->frame(env).get(), mJavaFrame->mLoadFinished, urlStr,
631             (int)loadType, isMainFrame);
632     checkException(env);
633     env->DeleteLocalRef(urlStr);
634 }
635
636 void
637 WebFrame::addHistoryItem(WebCore::HistoryItem* item)
638 {
639 #ifdef ANDROID_INSTRUMENT
640     TimeCounterAuto counter(TimeCounter::JavaCallbackTimeCounter);
641 #endif
642     LOGV("::WebCore:: addHistoryItem");
643     JNIEnv* env = getJNIEnv();
644     WebHistory::AddItem(mJavaFrame->history(env), item);
645 }
646
647 void
648 WebFrame::removeHistoryItem(int index)
649 {
650 #ifdef ANDROID_INSTRUMENT
651     TimeCounterAuto counter(TimeCounter::JavaCallbackTimeCounter);
652 #endif
653     LOGV("::WebCore:: removeHistoryItem at %d", index);
654     JNIEnv* env = getJNIEnv();
655     WebHistory::RemoveItem(mJavaFrame->history(env), index);
656 }
657
658 void
659 WebFrame::updateHistoryIndex(int newIndex)
660 {
661 #ifdef ANDROID_INSTRUMENT
662     TimeCounterAuto counter(TimeCounter::JavaCallbackTimeCounter);
663 #endif
664     LOGV("::WebCore:: updateHistoryIndex to %d", newIndex);
665     JNIEnv* env = getJNIEnv();
666     WebHistory::UpdateHistoryIndex(mJavaFrame->history(env), newIndex);
667 }
668
669 void
670 WebFrame::setTitle(const WTF::String& title)
671 {
672 #ifdef ANDROID_INSTRUMENT
673     TimeCounterAuto counter(TimeCounter::JavaCallbackTimeCounter);
674 #endif
675 #ifndef NDEBUG
676     LOGV("setTitle(%s)", title.ascii().data());
677 #endif
678     JNIEnv* env = getJNIEnv();
679     jstring jTitleStr = wtfStringToJstring(env, title);
680
681     env->CallVoidMethod(mJavaFrame->frame(env).get(), mJavaFrame->mSetTitle, jTitleStr);
682     checkException(env);
683     env->DeleteLocalRef(jTitleStr);
684 }
685
686 void
687 WebFrame::windowObjectCleared(WebCore::Frame* frame)
688 {
689 #ifdef ANDROID_INSTRUMENT
690     TimeCounterAuto counter(TimeCounter::JavaCallbackTimeCounter);
691 #endif
692     LOGV("::WebCore:: windowObjectCleared");
693     JNIEnv* env = getJNIEnv();
694
695     env->CallVoidMethod(mJavaFrame->frame(env).get(), mJavaFrame->mWindowObjectCleared, (int)frame);
696     checkException(env);
697 }
698
699 void
700 WebFrame::setProgress(float newProgress)
701 {
702 #ifdef ANDROID_INSTRUMENT
703     TimeCounterAuto counter(TimeCounter::JavaCallbackTimeCounter);
704 #endif
705     JNIEnv* env = getJNIEnv();
706     int progress = (int) (100 * newProgress);
707     env->CallVoidMethod(mJavaFrame->frame(env).get(), mJavaFrame->mSetProgress, progress);
708     checkException(env);
709 }
710
711 const WTF::String
712 WebFrame::userAgentForURL(const WebCore::KURL* url)
713 {
714     return mUserAgent;
715 }
716
717 void
718 WebFrame::didReceiveIcon(WebCore::Image* icon)
719 {
720 #ifdef ANDROID_INSTRUMENT
721     TimeCounterAuto counter(TimeCounter::JavaCallbackTimeCounter);
722 #endif
723     LOG_ASSERT(icon, "DidReceiveIcon called without an image!");
724     JNIEnv* env = getJNIEnv();
725     jobject bitmap = webcoreImageToJavaBitmap(env, icon);
726     if (!bitmap)
727         return;
728
729     env->CallVoidMethod(mJavaFrame->frame(env).get(), mJavaFrame->mDidReceiveIcon, bitmap);
730     env->DeleteLocalRef(bitmap);
731     checkException(env);
732 }
733
734 void
735 WebFrame::didReceiveTouchIconURL(const WTF::String& url, bool precomposed)
736 {
737 #ifdef ANDROID_INSTRUMENT
738     TimeCounterAuto counter(TimeCounter::JavaCallbackTimeCounter);
739 #endif
740     JNIEnv* env = getJNIEnv();
741     jstring jUrlStr = wtfStringToJstring(env, url);
742
743     env->CallVoidMethod(mJavaFrame->frame(env).get(),
744             mJavaFrame->mDidReceiveTouchIconUrl, jUrlStr, precomposed);
745     env->DeleteLocalRef(jUrlStr);
746     checkException(env);
747 }
748
749 void
750 WebFrame::updateVisitedHistory(const WebCore::KURL& url, bool reload)
751 {
752 #ifdef ANDROID_INSTRUMENT
753     TimeCounterAuto counter(TimeCounter::JavaCallbackTimeCounter);
754 #endif
755     const WTF::String& urlStr = url.string();
756     JNIEnv* env = getJNIEnv();
757     jstring jUrlStr = wtfStringToJstring(env, urlStr);
758
759     env->CallVoidMethod(mJavaFrame->frame(env).get(), mJavaFrame->mUpdateVisitedHistory, jUrlStr, reload);
760     env->DeleteLocalRef(jUrlStr);
761     checkException(env);
762 }
763
764 bool
765 WebFrame::canHandleRequest(const WebCore::ResourceRequest& request)
766 {
767 #ifdef ANDROID_INSTRUMENT
768     TimeCounterAuto counter(TimeCounter::JavaCallbackTimeCounter);
769 #endif
770     // always handle "POST" in place
771     if (equalIgnoringCase(request.httpMethod(), "POST"))
772         return true;
773     const WebCore::KURL& requestUrl = request.url();
774     bool isUserGesture = UserGestureIndicator::processingUserGesture();
775     if (!mUserInitiatedAction && !isUserGesture &&
776             (requestUrl.protocolIs("http") || requestUrl.protocolIs("https") ||
777             requestUrl.protocolIs("file") || requestUrl.protocolIs("about") ||
778             WebCore::protocolIsJavaScript(requestUrl.string())))
779         return true;
780     const WTF::String& url = requestUrl.string();
781     // Empty urls should not be sent to java
782     if (url.isEmpty())
783         return true;
784     JNIEnv* env = getJNIEnv();
785     jstring jUrlStr = wtfStringToJstring(env, url);
786
787     // check to see whether browser app wants to hijack url loading.
788     // if browser app handles the url, we will return false to bail out WebCore loading
789     jboolean ret = env->CallBooleanMethod(mJavaFrame->frame(env).get(), mJavaFrame->mHandleUrl, jUrlStr);
790     checkException(env);
791     env->DeleteLocalRef(jUrlStr);
792     return (ret == 0);
793 }
794
795 bool
796 WebFrame::shouldSaveFormData()
797 {
798     JNIEnv* env = getJNIEnv();
799     jboolean ret = env->CallBooleanMethod(mJavaFrame->frame(env).get(),
800             mJavaFrame->mShouldSaveFormData);
801     checkException(env);
802     return ret;
803 }
804
805 WebCore::Frame*
806 WebFrame::createWindow(bool dialog, bool userGesture)
807 {
808 #ifdef ANDROID_INSTRUMENT
809     TimeCounterAuto counter(TimeCounter::JavaCallbackTimeCounter);
810 #endif
811     JNIEnv* env = getJNIEnv();
812     jobject obj = env->CallObjectMethod(mJavaFrame->frame(env).get(),
813             mJavaFrame->mCreateWindow, dialog, userGesture);
814     if (obj) {
815         WebCore::Frame* frame = GET_NATIVE_FRAME(env, obj);
816         return frame;
817     }
818     return NULL;
819 }
820
821 void
822 WebFrame::requestFocus() const
823 {
824 #ifdef ANDROID_INSTRUMENT
825     TimeCounterAuto counter(TimeCounter::JavaCallbackTimeCounter);
826 #endif
827     JNIEnv* env = getJNIEnv();
828     env->CallVoidMethod(mJavaFrame->frame(env).get(), mJavaFrame->mRequestFocus);
829     checkException(env);
830 }
831
832 void
833 WebFrame::closeWindow(WebViewCore* webViewCore)
834 {
835 #ifdef ANDROID_INSTRUMENT
836     TimeCounterAuto counter(TimeCounter::JavaCallbackTimeCounter);
837 #endif
838     assert(webViewCore);
839     JNIEnv* env = getJNIEnv();
840     env->CallVoidMethod(mJavaFrame->frame(env).get(), mJavaFrame->mCloseWindow,
841             webViewCore->getJavaObject().get());
842 }
843
844 struct PolicyFunctionWrapper {
845     WebCore::FramePolicyFunction func;
846 };
847
848 void
849 WebFrame::decidePolicyForFormResubmission(WebCore::FramePolicyFunction func)
850 {
851 #ifdef ANDROID_INSTRUMENT
852     TimeCounterAuto counter(TimeCounter::JavaCallbackTimeCounter);
853 #endif
854     JNIEnv* env = getJNIEnv();
855     PolicyFunctionWrapper* p = new PolicyFunctionWrapper;
856     p->func = func;
857     env->CallVoidMethod(mJavaFrame->frame(env).get(), mJavaFrame->mDecidePolicyForFormResubmission, p);
858 }
859
860 WTF::String
861 WebFrame::getRawResourceFilename(WebCore::PlatformBridge::rawResId id) const
862 {
863     JNIEnv* env = getJNIEnv();
864     jstring ret = (jstring) env->CallObjectMethod(mJavaFrame->frame(env).get(),
865             mJavaFrame->mGetRawResFilename, (int)id);
866
867     return jstringToWtfString(env, ret);
868 }
869
870 float
871 WebFrame::density() const
872 {
873     JNIEnv* env = getJNIEnv();
874     jfloat dpi = env->CallFloatMethod(mJavaFrame->frame(env).get(), mJavaFrame->mDensity);
875     checkException(env);
876     return dpi;
877 }
878
879 #if USE(CHROME_NETWORK_STACK)
880 void
881 WebFrame::didReceiveAuthenticationChallenge(WebUrlLoaderClient* client, const std::string& host, const std::string& realm, bool useCachedCredentials)
882 {
883 #ifdef ANDROID_INSTRUMENT
884     TimeCounterAuto counter(TimeCounter::JavaCallbackTimeCounter);
885 #endif
886     JNIEnv* env = getJNIEnv();
887     int jHandle = reinterpret_cast<int>(client);
888     jstring jHost = stdStringToJstring(env, host, true);
889     jstring jRealm = stdStringToJstring(env, realm, true);
890
891     env->CallVoidMethod(mJavaFrame->frame(env).get(),
892             mJavaFrame->mDidReceiveAuthenticationChallenge, jHandle, jHost, jRealm, useCachedCredentials);
893     env->DeleteLocalRef(jHost);
894     env->DeleteLocalRef(jRealm);
895     checkException(env);
896 }
897 #endif
898
899 void
900 WebFrame::reportSslCertError(WebUrlLoaderClient* client, int cert_error, const std::string& cert)
901 {
902 #ifdef ANDROID_INSTRUMENT
903     TimeCounterAuto counter(TimeCounter::JavaCallbackTimeCounter);
904 #endif
905     JNIEnv* env = getJNIEnv();
906     int jHandle = reinterpret_cast<int>(client);
907
908     int len = cert.length();
909     jbyteArray jCert = env->NewByteArray(len);
910     jbyte* bytes = env->GetByteArrayElements(jCert, NULL);
911     cert.copy(reinterpret_cast<char*>(bytes), len);
912
913     env->CallVoidMethod(mJavaFrame->frame(env).get(),
914             mJavaFrame->mReportSslCertError, jHandle, cert_error, jCert);
915     env->DeleteLocalRef(jCert);
916     checkException(env);
917 }
918
919 #if USE(CHROME_NETWORK_STACK)
920 void
921 WebFrame::downloadStart(const std::string& url, const std::string& userAgent, const std::string& contentDisposition, const std::string& mimetype, long long contentLength)
922 {
923 #ifdef ANDROID_INSTRUMENT
924     TimeCounterAuto counter(TimeCounter::JavaCallbackTimeCounter);
925 #endif
926     JNIEnv* env = getJNIEnv();
927     jstring jUrl = stdStringToJstring(env, url, true);
928     jstring jUserAgent = stdStringToJstring(env, userAgent, true);
929     jstring jContentDisposition = stdStringToJstring(env, contentDisposition, true);
930     jstring jMimetype = stdStringToJstring(env, mimetype, true);
931
932     env->CallVoidMethod(mJavaFrame->frame(env).get(),
933             mJavaFrame->mDownloadStart, jUrl, jUserAgent, jContentDisposition, jMimetype, contentLength);
934
935     env->DeleteLocalRef(jUrl);
936     env->DeleteLocalRef(jUserAgent);
937     env->DeleteLocalRef(jContentDisposition);
938     env->DeleteLocalRef(jMimetype);
939     checkException(env);
940 }
941
942 void
943 WebFrame::didReceiveData(const char* data, int size) {
944 #ifdef ANDROID_INSTRUMENT
945     TimeCounterAuto counter(TimeCounter::JavaCallbackTimeCounter);
946 #endif
947     JNIEnv* env = getJNIEnv();
948
949     jbyteArray jData = env->NewByteArray(size);
950     jbyte* bytes = env->GetByteArrayElements(jData, NULL);
951     memcpy(reinterpret_cast<char*>(bytes), data, size);
952
953     env->CallVoidMethod(mJavaFrame->frame(env).get(),
954             mJavaFrame->mDidReceiveData, jData, size);
955     env->DeleteLocalRef(jData);
956     checkException(env);
957 }
958
959 void
960 WebFrame::didFinishLoading() {
961 #ifdef ANDROID_INSTRUMENT
962     TimeCounterAuto counter(TimeCounter::JavaCallbackTimeCounter);
963 #endif
964     JNIEnv* env = getJNIEnv();
965
966     env->CallVoidMethod(mJavaFrame->frame(env).get(), mJavaFrame->mDidFinishLoading);
967     checkException(env);
968 }
969
970 #endif
971
972 #if USE(CHROME_NETWORK_STACK)
973 void WebFrame::setCertificate(const std::string& cert)
974 {
975 #ifdef ANDROID_INSTRUMENT
976     TimeCounterAuto counter(TimeCounter::JavaCallbackTimeCounter);
977 #endif
978     JNIEnv* env = getJNIEnv();
979
980     int len = cert.length();
981     jbyteArray jCert = env->NewByteArray(len);
982     jbyte* bytes = env->GetByteArrayElements(jCert, NULL);
983     cert.copy(reinterpret_cast<char*>(bytes), len);
984
985     env->CallVoidMethod(mJavaFrame->frame(env).get(), mJavaFrame->mSetCertificate, jCert);
986
987     env->DeleteLocalRef(jCert);
988     checkException(env);
989 }
990 #endif
991
992 void WebFrame::autoLogin(const std::string& loginHeader)
993 {
994 #ifdef ANDROID_INSTRUMENT
995     TimeCounterAuto counter(TimerCoutner::JavaCallbackTimeCounter);
996 #endif
997     WTF::String header(loginHeader.c_str(), loginHeader.length());
998     WTF::Vector<WTF::String> split;
999     header.split('&', split);
1000     if (!split.isEmpty()) {
1001         WTF::String realm;
1002         WTF::String account;
1003         WTF::String args;
1004         int len = split.size();
1005         while (len--) {
1006             WTF::String& str = split[len];
1007             size_t equals = str.find('=');
1008             if (equals == WTF::notFound)
1009                 continue;
1010
1011             WTF::String* result = 0;
1012             if (str.startsWith("realm", false))
1013                 result = &realm;
1014             else if (str.startsWith("account", false))
1015                 result = &account;
1016             else if (str.startsWith("args", false))
1017                 result = &args;
1018
1019             if (result)
1020                 // Decode url escape sequences before sending to the app.
1021                 *result = WebCore::decodeURLEscapeSequences(str.substring(equals + 1));
1022         }
1023
1024         // realm and args are required parameters.
1025         if (realm.isEmpty() || args.isEmpty())
1026             return;
1027
1028         JNIEnv* env = getJNIEnv();
1029         jstring jRealm = wtfStringToJstring(env, realm, true);
1030         jstring jAccount = wtfStringToJstring(env, account);
1031         jstring jArgs = wtfStringToJstring(env, args, true);
1032         env->CallVoidMethod(mJavaFrame->frame(env).get(),
1033                 mJavaFrame->mAutoLogin, jRealm, jAccount, jArgs);
1034     }
1035 }
1036
1037 void WebFrame::maybeSavePassword(WebCore::Frame* frame, const WebCore::ResourceRequest& request)
1038 {
1039     if (request.httpMethod() != "POST")
1040         return;
1041
1042     WTF::String username;
1043     WTF::String password;
1044     if (!getUsernamePasswordFromDom(frame, username, password))
1045         return;
1046
1047     JNIEnv* env = getJNIEnv();
1048     jstring jUsername = wtfStringToJstring(env, username);
1049     jstring jPassword = wtfStringToJstring(env, password);
1050     jbyteArray jPostData = getPostData(request);
1051     if (jPostData) {
1052         env->CallVoidMethod(mJavaFrame->frame(env).get(),
1053                 mJavaFrame->mMaybeSavePassword, jPostData, jUsername, jPassword);
1054     }
1055
1056     env->DeleteLocalRef(jPostData);
1057     env->DeleteLocalRef(jUsername);
1058     env->DeleteLocalRef(jPassword);
1059     checkException(env);
1060 }
1061
1062 bool WebFrame::getUsernamePasswordFromDom(WebCore::Frame* frame, WTF::String& username, WTF::String& password)
1063 {
1064     bool found = false;
1065     WTF::PassRefPtr<WebCore::HTMLCollection> form = frame->document()->forms();
1066     WebCore::Node* node = form->firstItem();
1067     while (node && !found && !node->namespaceURI().isNull() &&
1068            !node->namespaceURI().isEmpty()) {
1069         const WTF::Vector<WebCore::HTMLFormControlElement*>& elements =
1070             ((WebCore::HTMLFormElement*)node)->associatedElements();
1071         size_t size = elements.size();
1072         for (size_t i = 0; i< size && !found; i++) {
1073             WebCore::HTMLFormControlElement* e = elements[i];
1074             if (e->hasLocalName(WebCore::HTMLNames::inputTag)) {
1075                 WebCore::HTMLInputElement* input = (WebCore::HTMLInputElement*)e;
1076                 if (input->autoComplete() == false)
1077                     continue;
1078                 if (input->isPasswordField())
1079                     password = input->value();
1080                 else if (input->isTextField() || input->isEmailField())
1081                     username = input->value();
1082                 if (!username.isNull() && !password.isNull())
1083                     found = true;
1084             }
1085         }
1086         node = form->nextItem();
1087     }
1088     return found;
1089 }
1090
1091 jbyteArray WebFrame::getPostData(const WebCore::ResourceRequest& request)
1092 {
1093     jbyteArray jPostDataStr = NULL;
1094     WebCore::FormData* formdata = request.httpBody();
1095     if (formdata) {
1096         JNIEnv* env = getJNIEnv();
1097         AutoJObject obj = mJavaFrame->frame(env);
1098
1099         // We can use the formdata->flatten() but it will result in two
1100         // memcpys, first through loading up the vector with the form data
1101         // then another to copy it out of the vector and into the java byte
1102         // array. Instead, we copy the form data ourselves below saving a
1103         // memcpy.
1104         const WTF::Vector<WebCore::FormDataElement>& elements =
1105                 formdata->elements();
1106
1107         // Sizing pass
1108         int size = 0;
1109         size_t n = elements.size();
1110         FileInfo** fileinfos = new FileInfo*[n];
1111         for (size_t i = 0; i < n; ++i) {
1112             fileinfos[i] = 0;
1113             const WebCore::FormDataElement& e = elements[i];
1114             if (e.m_type == WebCore::FormDataElement::data) {
1115                 size += e.m_data.size();
1116             } else if (e.m_type == WebCore::FormDataElement::encodedFile) {
1117                 fileinfos[i] = new FileInfo(env, e.m_filename);
1118                 int delta = env->CallIntMethod(obj.get(),
1119                     mJavaFrame->mGetFileSize, fileinfos[i]->getUri());
1120                 checkException(env);
1121                 fileinfos[i]->setSize(delta);
1122                 size += delta;
1123             }
1124         }
1125
1126         // Only create the byte array if there is POST data to pass up.
1127         // The Java code is expecting null if there is no data.
1128         if (size > 0) {
1129             // Copy the actual form data.
1130             jPostDataStr = env->NewByteArray(size);
1131             if (jPostDataStr) {
1132                 // Write  the form data to the java array.
1133                 jbyte* bytes = env->GetByteArrayElements(jPostDataStr, NULL);
1134                 int offset = 0;
1135                 for (size_t i = 0; i < n; ++i) {
1136                     const WebCore::FormDataElement& e = elements[i];
1137                     if (e.m_type == WebCore::FormDataElement::data) {
1138                         int delta = e.m_data.size();
1139                         memcpy(bytes + offset, e.m_data.data(), delta);
1140                         offset += delta;
1141                     } else if (e.m_type
1142                             == WebCore::FormDataElement::encodedFile) {
1143                         int delta = env->CallIntMethod(obj.get(),
1144                             mJavaFrame->mGetFile, fileinfos[i]->getUri(),
1145                             jPostDataStr, offset, fileinfos[i]->getSize());
1146                         checkException(env);
1147                         offset += delta;
1148                     }
1149                 }
1150                 env->ReleaseByteArrayElements(jPostDataStr, bytes, 0);
1151             }
1152         }
1153         delete[] fileinfos;
1154     }
1155     return jPostDataStr;
1156 }
1157
1158 // ----------------------------------------------------------------------------
1159
1160 static void CallPolicyFunction(JNIEnv* env, jobject obj, jint func, jint decision)
1161 {
1162 #ifdef ANDROID_INSTRUMENT
1163     TimeCounterAuto counter(TimeCounter::NativeCallbackTimeCounter);
1164 #endif
1165     WebCore::Frame* pFrame = GET_NATIVE_FRAME(env, obj);
1166     LOG_ASSERT(pFrame, "nativeCallPolicyFunction must take a valid frame pointer!");
1167     PolicyFunctionWrapper* pFunc = (PolicyFunctionWrapper*)func;
1168     LOG_ASSERT(pFunc, "nativeCallPolicyFunction must take a valid function pointer!");
1169
1170     // If we are resending the form then we should reset the multiple submission protection.
1171     if (decision == WebCore::PolicyUse)
1172         pFrame->loader()->resetMultipleFormSubmissionProtection();
1173
1174     (pFrame->loader()->policyChecker()->*(pFunc->func))((WebCore::PolicyAction)decision);
1175 }
1176
1177 static void CreateFrame(JNIEnv* env, jobject obj, jobject javaview, jobject jAssetManager, jobject historyList)
1178 {
1179     ScriptController::initializeThreading();
1180
1181 #if USE(CHROME_NETWORK_STACK)
1182     // needs to be called before any other chromium code
1183     initChromium();
1184 #endif
1185
1186 #ifdef ANDROID_INSTRUMENT
1187 #if USE(V8)
1188     V8Counters::initCounters();
1189 #endif
1190     TimeCounterAuto counter(TimeCounter::NativeCallbackTimeCounter);
1191 #endif
1192     // Create a new page
1193     ChromeClientAndroid* chromeC = new ChromeClientAndroid;
1194     EditorClientAndroid* editorC = new EditorClientAndroid;
1195     DeviceMotionClientAndroid* deviceMotionC = new DeviceMotionClientAndroid;
1196     DeviceOrientationClientAndroid* deviceOrientationC = new DeviceOrientationClientAndroid;
1197
1198     WebCore::Page::PageClients pageClients;
1199     pageClients.chromeClient = chromeC;
1200     pageClients.contextMenuClient = new ContextMenuClientAndroid;
1201     pageClients.editorClient = editorC;
1202     pageClients.dragClient = new DragClientAndroid;
1203     pageClients.inspectorClient = new InspectorClientAndroid;
1204     pageClients.deviceMotionClient = deviceMotionC;
1205     pageClients.deviceOrientationClient = deviceOrientationC;
1206     WebCore::Page* page = new WebCore::Page(pageClients);
1207
1208     editorC->setPage(page);
1209     page->setGroupName("android.webkit");
1210
1211     // Create a WebFrame to access the Java BrowserFrame associated with this page
1212     WebFrame* webFrame = new WebFrame(env, obj, historyList, page);
1213     // Attach webFrame to pageClients.chromeClient and release our ownership
1214     chromeC->setWebFrame(webFrame);
1215     Release(webFrame);
1216
1217     FrameLoaderClientAndroid* loaderC = new FrameLoaderClientAndroid(webFrame);
1218     // Create a Frame and the page holds its reference
1219     WebCore::Frame* frame = WebCore::Frame::create(page, NULL, loaderC).get();
1220     loaderC->setFrame(frame);
1221 #if ENABLE(WDS)
1222     WDS::server()->addFrame(frame);
1223 #endif
1224
1225     // Create a WebViewCore to access the Java WebViewCore associated with this page
1226     WebViewCore* webViewCore = new WebViewCore(env, javaview, frame);
1227
1228 #if ENABLE(WEB_AUTOFILL)
1229     editorC->getAutoFill()->setWebViewCore(webViewCore);
1230 #endif
1231
1232     // Create a FrameView
1233     RefPtr<WebCore::FrameView> frameView = WebCore::FrameView::create(frame);
1234     // Create a WebFrameView
1235     WebFrameView* webFrameView = new WebFrameView(frameView.get(), webViewCore);
1236     // As webFrameView Retains webViewCore, release our ownership
1237     Release(webViewCore);
1238     // As frameView Retains webFrameView, release our ownership
1239     Release(webFrameView);
1240     // Attach the frameView to the frame and release our ownership
1241     frame->setView(frameView);
1242     // Set the frame to active to turn on keyboard focus.
1243     frame->init();
1244     frame->selection()->setFocused(true);
1245     frame->page()->focusController()->setFocused(true);
1246     deviceMotionC->setWebViewCore(webViewCore);
1247     deviceOrientationC->setWebViewCore(webViewCore);
1248
1249     // Allow local access to file:/// and substitute data
1250     WebCore::SecurityOrigin::setLocalLoadPolicy(
1251             WebCore::SecurityOrigin::AllowLocalLoadsForLocalAndSubstituteData);
1252
1253     LOGV("::WebCore:: createFrame %p", frame);
1254
1255     // Set the mNativeFrame field in Frame
1256     SET_NATIVE_FRAME(env, obj, (int)frame);
1257
1258     String directory = webFrame->getRawResourceFilename(
1259             WebCore::PlatformBridge::DrawableDir);
1260     if (directory.isEmpty())
1261         LOGE("Can't find the drawable directory");
1262     else {
1263         // Setup the asset manager.
1264         AssetManager* am = assetManagerForJavaObject(env, jAssetManager);
1265         // Initialize our skinning classes
1266         webFrame->setRenderSkins(new WebCore::RenderSkinAndroid(am, directory));
1267     }
1268     for (int i = WebCore::PlatformBridge::FileUploadLabel;
1269             i <= WebCore::PlatformBridge::FileUploadNoFileChosenLabel; i++)
1270         initGlobalLocalizedName(
1271                 static_cast<WebCore::PlatformBridge::rawResId>(i), webFrame);
1272 }
1273
1274 static void DestroyFrame(JNIEnv* env, jobject obj)
1275 {
1276 #ifdef ANDROID_INSTRUMENT
1277     TimeCounterAuto counter(TimeCounter::NativeCallbackTimeCounter);
1278 #endif
1279     WebCore::Frame* pFrame = GET_NATIVE_FRAME(env, obj);
1280     LOG_ASSERT(pFrame, "nativeDestroyFrame must take a valid frame pointer!");
1281
1282     LOGV("::WebCore:: deleting frame %p", pFrame);
1283
1284     WebCore::FrameView* view = pFrame->view();
1285     view->ref();
1286     // detachFromParent will cause the page to be closed.
1287     WebCore::FrameLoader* fl = pFrame->loader();
1288     // retain a pointer because detachFromParent will set the page to null.
1289     WebCore::Page* page = pFrame->page();
1290     if (fl)
1291         fl->detachFromParent();
1292     delete page;
1293     view->deref();
1294
1295     SET_NATIVE_FRAME(env, obj, 0);
1296 #if ENABLE(WDS)
1297     WDS::server()->removeFrame(pFrame);
1298 #endif
1299 }
1300
1301 static void LoadUrl(JNIEnv *env, jobject obj, jstring url, jobject headers)
1302 {
1303 #ifdef ANDROID_INSTRUMENT
1304     TimeCounterAuto counter(TimeCounter::NativeCallbackTimeCounter);
1305 #endif
1306     WebCore::Frame* pFrame = GET_NATIVE_FRAME(env, obj);
1307     LOG_ASSERT(pFrame, "nativeLoadUrl must take a valid frame pointer!");
1308
1309     WTF::String webcoreUrl = jstringToWtfString(env, url);
1310     WebCore::KURL kurl(WebCore::KURL(), webcoreUrl);
1311     WebCore::ResourceRequest request(kurl);
1312     if (headers) {
1313         // dalvikvm will raise exception if any of these fail
1314         jclass mapClass = env->FindClass("java/util/Map");
1315         jmethodID entrySet = env->GetMethodID(mapClass, "entrySet",
1316                 "()Ljava/util/Set;");
1317         jobject set = env->CallObjectMethod(headers, entrySet);
1318
1319         jclass setClass = env->FindClass("java/util/Set");
1320         jmethodID iterator = env->GetMethodID(setClass, "iterator",
1321                 "()Ljava/util/Iterator;");
1322         jobject iter = env->CallObjectMethod(set, iterator);
1323
1324         jclass iteratorClass = env->FindClass("java/util/Iterator");
1325         jmethodID hasNext = env->GetMethodID(iteratorClass, "hasNext", "()Z");
1326         jmethodID next = env->GetMethodID(iteratorClass, "next",
1327                 "()Ljava/lang/Object;");
1328         jclass entryClass = env->FindClass("java/util/Map$Entry");
1329         jmethodID getKey = env->GetMethodID(entryClass, "getKey",
1330                 "()Ljava/lang/Object;");
1331         jmethodID getValue = env->GetMethodID(entryClass, "getValue",
1332                 "()Ljava/lang/Object;");
1333
1334         while (env->CallBooleanMethod(iter, hasNext)) {
1335             jobject entry = env->CallObjectMethod(iter, next);
1336             jstring key = (jstring) env->CallObjectMethod(entry, getKey);
1337             jstring value = (jstring) env->CallObjectMethod(entry, getValue);
1338             request.setHTTPHeaderField(jstringToWtfString(env, key), jstringToWtfString(env, value));
1339             env->DeleteLocalRef(entry);
1340             env->DeleteLocalRef(key);
1341             env->DeleteLocalRef(value);
1342         }
1343
1344         env->DeleteLocalRef(entryClass);
1345         env->DeleteLocalRef(iteratorClass);
1346         env->DeleteLocalRef(iter);
1347         env->DeleteLocalRef(setClass);
1348         env->DeleteLocalRef(set);
1349         env->DeleteLocalRef(mapClass);
1350     }
1351     LOGV("LoadUrl %s", kurl.string().latin1().data());
1352     pFrame->loader()->load(request, false);
1353 }
1354
1355 static void PostUrl(JNIEnv *env, jobject obj, jstring url, jbyteArray postData)
1356 {
1357 #ifdef ANDROID_INSTRUMENT
1358     TimeCounterAuto counter(TimeCounter::NativeCallbackTimeCounter);
1359 #endif
1360     WebCore::Frame* pFrame = GET_NATIVE_FRAME(env, obj);
1361     LOG_ASSERT(pFrame, "nativePostUrl must take a valid frame pointer!");
1362
1363     WebCore::KURL kurl(WebCore::KURL(), jstringToWtfString(env, url));
1364     WebCore::ResourceRequest request(kurl);
1365     request.setHTTPMethod("POST");
1366     request.setHTTPContentType("application/x-www-form-urlencoded");
1367
1368     if (postData) {
1369         jsize size = env->GetArrayLength(postData);
1370         jbyte* bytes = env->GetByteArrayElements(postData, NULL);
1371         RefPtr<FormData> formData = FormData::create((const void*)bytes, size);
1372         // the identifier uses the same logic as generateFormDataIdentifier() in
1373         // HTMLFormElement.cpp
1374         formData->setIdentifier(static_cast<int64_t>(WTF::currentTime() * 1000000.0));
1375         request.setHTTPBody(formData);
1376         env->ReleaseByteArrayElements(postData, bytes, 0);
1377     }
1378
1379     LOGV("PostUrl %s", kurl.string().latin1().data());
1380     WebCore::FrameLoadRequest frameRequest(request);
1381     pFrame->loader()->loadFrameRequest(frameRequest, false, false, 0, 0, WebCore::SendReferrer);
1382 }
1383
1384 static void LoadData(JNIEnv *env, jobject obj, jstring baseUrl, jstring data,
1385         jstring mimeType, jstring encoding, jstring failUrl)
1386 {
1387 #ifdef ANDROID_INSTRUMENT
1388     TimeCounterAuto counter(TimeCounter::NativeCallbackTimeCounter);
1389 #endif
1390     WebCore::Frame* pFrame = GET_NATIVE_FRAME(env, obj);
1391     LOG_ASSERT(pFrame, "nativeLoadData must take a valid frame pointer!");
1392
1393     // Setup the resource request
1394     WebCore::ResourceRequest request(jstringToWtfString(env, baseUrl));
1395
1396     // Setup the substituteData
1397     const char* dataStr = env->GetStringUTFChars(data, NULL);
1398     WTF::PassRefPtr<WebCore::SharedBuffer> sharedBuffer =
1399         WebCore::SharedBuffer::create();
1400     LOG_ASSERT(dataStr, "nativeLoadData has a null data string.");
1401     sharedBuffer->append(dataStr, strlen(dataStr));
1402     env->ReleaseStringUTFChars(data, dataStr);
1403
1404     WebCore::SubstituteData substituteData(sharedBuffer,
1405             jstringToWtfString(env, mimeType), jstringToWtfString(env, encoding),
1406             WebCore::KURL(ParsedURLString, jstringToWtfString(env, failUrl)));
1407
1408     // Perform the load
1409     pFrame->loader()->load(request, substituteData, false);
1410 }
1411
1412 static void StopLoading(JNIEnv *env, jobject obj)
1413 {
1414 #ifdef ANDROID_INSTRUMENT
1415     TimeCounterAuto counter(TimeCounter::NativeCallbackTimeCounter);
1416 #endif
1417     WebCore::Frame* pFrame = GET_NATIVE_FRAME(env, obj);
1418     LOG_ASSERT(pFrame, "nativeStopLoading must take a valid frame pointer!");
1419     LOGV("::WebCore:: stopLoading %p", pFrame);
1420
1421     // Stop loading the page and do not send an unload event
1422     pFrame->loader()->stopForUserCancel();
1423 }
1424
1425 #if ENABLE(ARCHIVE)
1426 static String saveArchiveAutoname(String basename, String name, String extension) {
1427     if (name.isNull() || name.isEmpty()) {
1428         name = String("index");
1429     }
1430
1431     String testname = basename;
1432     testname.append(name);
1433     testname.append(extension);
1434
1435     errno = 0;
1436     struct stat permissions;
1437     if (stat(testname.utf8().data(), &permissions) < 0) {
1438         if (errno == ENOENT)
1439             return testname;
1440         return String();
1441     }
1442
1443     const int maxAttempts = 100;
1444     for (int i = 1; i < maxAttempts; i++) {
1445         String testname = basename;
1446         testname.append(name);
1447         testname.append("-");
1448         testname.append(String::number(i));
1449         testname.append(extension);
1450
1451         errno = 0;
1452         if (stat(testname.utf8().data(), &permissions) < 0) {
1453             if (errno == ENOENT)
1454                 return testname;
1455             return String();
1456         }
1457     }
1458
1459     return String();
1460 }
1461 #endif
1462
1463 static jstring SaveWebArchive(JNIEnv *env, jobject obj, jstring basename, jboolean autoname)
1464 {
1465 #if ENABLE(ARCHIVE)
1466     WebCore::Frame* pFrame = GET_NATIVE_FRAME(env, obj);
1467     LOG_ASSERT(pFrame, "nativeSaveWebArchive must take a valid frame pointer!");
1468     String mimeType = pFrame->loader()->documentLoader()->mainResource()->mimeType();
1469     if ((mimeType != "text/html") && (mimeType != "application/xhtml+xml"))
1470         return NULL;
1471
1472     const char* basenameNative = getCharactersFromJStringInEnv(env, basename);
1473     String basenameString = String::fromUTF8(basenameNative);
1474     String filename;
1475
1476     if (autoname) {
1477         String name = pFrame->loader()->documentLoader()->originalURL().lastPathComponent();
1478         String extension = String(".webarchivexml");
1479         filename = saveArchiveAutoname(basenameString, name, extension);
1480     } else {
1481         filename = basenameString;
1482     }
1483
1484     if (filename.isNull() || filename.isEmpty()) {
1485         LOGD("saveWebArchive: Failed to select a filename to save.");
1486         releaseCharactersForJStringInEnv(env, basename, basenameNative);
1487         return NULL;
1488     }
1489
1490     const int noCompression = 0;
1491     xmlTextWriterPtr writer = xmlNewTextWriterFilename(filename.utf8().data(), noCompression);
1492     if (writer == NULL) {
1493         LOGD("saveWebArchive: Failed to initialize xml writer.");
1494         releaseCharactersForJStringInEnv(env, basename, basenameNative);
1495         return NULL;
1496     }
1497
1498     RefPtr<WebArchiveAndroid> archive = WebCore::WebArchiveAndroid::create(pFrame);
1499
1500     bool result = archive->saveWebArchive(writer);
1501
1502     releaseCharactersForJStringInEnv(env, basename, basenameNative);
1503     xmlFreeTextWriter(writer);
1504
1505     if (result)
1506         return wtfStringToJstring(env, filename);
1507
1508     return NULL;
1509 #endif
1510 }
1511
1512 static jstring ExternalRepresentation(JNIEnv *env, jobject obj)
1513 {
1514 #ifdef ANDROID_INSTRUMENT
1515     TimeCounterAuto counter(TimeCounter::NativeCallbackTimeCounter);
1516 #endif
1517     WebCore::Frame* pFrame = GET_NATIVE_FRAME(env, obj);
1518     LOG_ASSERT(pFrame, "android_webcore_nativeExternalRepresentation must take a valid frame pointer!");
1519
1520     // Request external representation of the render tree
1521     WTF::String renderDump = WebCore::externalRepresentation(pFrame);
1522     return wtfStringToJstring(env, renderDump);
1523 }
1524
1525 static StringBuilder FrameAsText(WebCore::Frame *pFrame, jboolean dumpChildFrames) {
1526     StringBuilder renderDump;
1527     if (!pFrame)
1528         return renderDump;
1529     WebCore::Element *documentElement = pFrame->document()->documentElement();
1530     if (!documentElement)
1531         return renderDump;
1532     if (pFrame->tree()->parent()) {
1533         renderDump.append("\n--------\nFrame: '");
1534         renderDump.append(pFrame->tree()->name());
1535         renderDump.append("'\n--------\n");
1536     }
1537     renderDump.append(((WebCore::HTMLElement*)documentElement)->innerText());
1538     renderDump.append("\n");
1539     if (dumpChildFrames) {
1540         for (unsigned i = 0; i < pFrame->tree()->childCount(); ++i) {
1541             renderDump.append(FrameAsText(pFrame->tree()->child(i), dumpChildFrames).toString());
1542         }
1543     }
1544     return renderDump;
1545 }
1546
1547 static jstring DocumentAsText(JNIEnv *env, jobject obj)
1548 {
1549 #ifdef ANDROID_INSTRUMENT
1550     TimeCounterAuto counter(TimeCounter::NativeCallbackTimeCounter);
1551 #endif
1552     WebCore::Frame* pFrame = GET_NATIVE_FRAME(env, obj);
1553     LOG_ASSERT(pFrame, "android_webcore_nativeDocumentAsText must take a valid frame pointer!");
1554
1555     WTF::String renderDump = FrameAsText(pFrame, false /* dumpChildFrames */).toString();
1556     return wtfStringToJstring(env, renderDump);
1557 }
1558
1559 static jstring ChildFramesAsText(JNIEnv *env, jobject obj)
1560 {
1561 #ifdef ANDROID_INSTRUMENT
1562     TimeCounterAuto counter(TimeCounter::NativeCallbackTimeCounter);
1563 #endif
1564     WebCore::Frame* pFrame = GET_NATIVE_FRAME(env, obj);
1565     LOG_ASSERT(pFrame, "android_webcore_nativeDocumentAsText must take a valid frame pointer!");
1566
1567     StringBuilder renderDumpBuilder;
1568     for (unsigned i = 0; i < pFrame->tree()->childCount(); ++i) {
1569         renderDumpBuilder.append(FrameAsText(pFrame->tree()->child(i), true /* dumpChildFrames */).toString());
1570     }
1571     WTF::String renderDump = renderDumpBuilder.toString();
1572     return wtfStringToJstring(env, renderDump);
1573 }
1574
1575 static void Reload(JNIEnv *env, jobject obj, jboolean allowStale)
1576 {
1577 #ifdef ANDROID_INSTRUMENT
1578     TimeCounterAuto counter(TimeCounter::NativeCallbackTimeCounter);
1579 #endif
1580     WebCore::Frame* pFrame = GET_NATIVE_FRAME(env, obj);
1581     LOG_ASSERT(pFrame, "nativeReload must take a valid frame pointer!");
1582
1583     WebCore::FrameLoader* loader = pFrame->loader();
1584     if (allowStale) {
1585         // load the current page with FrameLoadTypeIndexedBackForward so that it
1586         // will use cache when it is possible
1587         WebCore::Page* page = pFrame->page();
1588         WebCore::HistoryItem* item = page->backForwardList()->currentItem();
1589         if (item)
1590             page->goToItem(item, FrameLoadTypeIndexedBackForward);
1591     } else
1592         loader->reload(true);
1593 }
1594
1595 static void GoBackOrForward(JNIEnv *env, jobject obj, jint pos)
1596 {
1597 #ifdef ANDROID_INSTRUMENT
1598     TimeCounterAuto counter(TimeCounter::NativeCallbackTimeCounter);
1599 #endif
1600     WebCore::Frame* pFrame = GET_NATIVE_FRAME(env, obj);
1601     LOG_ASSERT(pFrame, "nativeGoBackOrForward must take a valid frame pointer!");
1602
1603     if (pos == 1)
1604         pFrame->page()->goForward();
1605     else if (pos == -1)
1606         pFrame->page()->goBack();
1607     else
1608         pFrame->page()->goBackOrForward(pos);
1609 }
1610
1611 static jobject StringByEvaluatingJavaScriptFromString(JNIEnv *env, jobject obj, jstring script)
1612 {
1613 #ifdef ANDROID_INSTRUMENT
1614     TimeCounterAuto counter(TimeCounter::NativeCallbackTimeCounter);
1615 #endif
1616     WebCore::Frame* pFrame = GET_NATIVE_FRAME(env, obj);
1617     LOG_ASSERT(pFrame, "stringByEvaluatingJavaScriptFromString must take a valid frame pointer!");
1618
1619     WebCore::ScriptValue value =
1620             pFrame->script()->executeScript(jstringToWtfString(env, script), true);
1621     WTF::String result = WTF::String();
1622     ScriptState* scriptState = mainWorldScriptState(pFrame);
1623     if (!value.getString(scriptState, result))
1624         return NULL;
1625     return wtfStringToJstring(env, result);
1626 }
1627
1628 // Wrap the JavaInstance used when binding custom javascript interfaces. Use a
1629 // weak reference so that the gc can collect the WebView. Override virtualBegin
1630 // and virtualEnd and swap the weak reference for the real object.
1631 class WeakJavaInstance : public JavaInstance {
1632 public:
1633 #if USE(JSC)
1634     static PassRefPtr<WeakJavaInstance> create(jobject obj, PassRefPtr<RootObject> root)
1635     {
1636         return adoptRef(new WeakJavaInstance(obj, root));
1637     }
1638 #elif USE(V8)
1639     static PassRefPtr<WeakJavaInstance> create(jobject obj)
1640     {
1641         return adoptRef(new WeakJavaInstance(obj));
1642     }
1643 #endif
1644
1645 private:
1646 #if USE(JSC)
1647     WeakJavaInstance(jobject instance, PassRefPtr<RootObject> rootObject)
1648         : JavaInstance(instance, rootObject)
1649 #elif USE(V8)
1650     WeakJavaInstance(jobject instance)
1651         : JavaInstance(instance)
1652 #endif
1653         , m_beginEndDepth(0)
1654     {
1655         JNIEnv* env = getJNIEnv();
1656         // JavaInstance creates a global ref to instance in its constructor.
1657         env->DeleteGlobalRef(m_instance->instance());
1658         // Set the object to a weak reference.
1659         m_instance->setInstance(env->NewWeakGlobalRef(instance));
1660     }
1661     ~WeakJavaInstance()
1662     {
1663         JNIEnv* env = getJNIEnv();
1664         // Store the weak reference so we can delete it later.
1665         jweak weak = m_instance->instance();
1666         // The JavaInstance destructor attempts to delete the global ref stored
1667         // in m_instance. Since we replaced it in our constructor with a weak
1668         // reference, restore the global ref here so the vm will not complain.
1669         m_instance->setInstance(env->NewGlobalRef(
1670                 getRealObject(env, m_instance->instance()).get()));
1671         // Delete the weak reference.
1672         env->DeleteWeakGlobalRef(weak);
1673     }
1674
1675     virtual void virtualBegin()
1676     {
1677         if (m_beginEndDepth++ > 0)
1678             return;
1679         m_weakRef = m_instance->instance();
1680         JNIEnv* env = getJNIEnv();
1681         // This is odd. getRealObject returns an AutoJObject which is used to
1682         // cleanly create and delete a local reference. But, here we need to
1683         // maintain the local reference across calls to virtualBegin() and
1684         // virtualEnd(). So, release the local reference from the AutoJObject
1685         // and delete the local reference in virtualEnd().
1686         m_realObject = getRealObject(env, m_weakRef).release();
1687         // Point to the real object
1688         m_instance->setInstance(m_realObject);
1689         // Call the base class method
1690         INHERITED::virtualBegin();
1691     }
1692
1693     virtual void virtualEnd()
1694     {
1695         if (--m_beginEndDepth > 0)
1696             return;
1697         // Call the base class method first to pop the local frame.
1698         INHERITED::virtualEnd();
1699         // Get rid of the local reference to the real object.
1700         getJNIEnv()->DeleteLocalRef(m_realObject);
1701         // Point back to the WeakReference.
1702         m_instance->setInstance(m_weakRef);
1703     }
1704
1705 private:
1706     typedef JavaInstance INHERITED;
1707     jobject m_realObject;
1708     jweak m_weakRef;
1709     // The current depth of nested calls to virtualBegin and virtualEnd.
1710     int m_beginEndDepth;
1711 };
1712
1713 static void AddJavascriptInterface(JNIEnv *env, jobject obj, jint nativeFramePointer,
1714         jobject javascriptObj, jstring interfaceName)
1715 {
1716 #ifdef ANDROID_INSTRUMENT
1717     TimeCounterAuto counter(TimeCounter::NativeCallbackTimeCounter);
1718 #endif
1719     WebCore::Frame* pFrame = 0;
1720     if (nativeFramePointer == 0)
1721         pFrame = GET_NATIVE_FRAME(env, obj);
1722     else
1723         pFrame = (WebCore::Frame*)nativeFramePointer;
1724     LOG_ASSERT(pFrame, "nativeAddJavascriptInterface must take a valid frame pointer!");
1725
1726     JavaVM* vm;
1727     env->GetJavaVM(&vm);
1728     LOGV("::WebCore:: addJSInterface: %p", pFrame);
1729
1730 #if USE(JSC)
1731     // Copied from qwebframe.cpp
1732     JSC::JSLock lock(JSC::SilenceAssertionsOnly);
1733     WebCore::JSDOMWindow *window = WebCore::toJSDOMWindow(pFrame, mainThreadNormalWorld());
1734     if (window) {
1735         RootObject *root = pFrame->script()->bindingRootObject();
1736         setJavaVM(vm);
1737         // Add the binding to JS environment
1738         JSC::ExecState* exec = window->globalExec();
1739         JSC::JSObject* addedObject = WeakJavaInstance::create(javascriptObj,
1740                 root)->createRuntimeObject(exec);
1741         const jchar* s = env->GetStringChars(interfaceName, NULL);
1742         if (s) {
1743             // Add the binding name to the window's table of child objects.
1744             JSC::PutPropertySlot slot;
1745             window->put(exec, JSC::Identifier(exec, (const UChar *)s,
1746                     env->GetStringLength(interfaceName)), addedObject, slot);
1747             env->ReleaseStringChars(interfaceName, s);
1748             checkException(env);
1749         }
1750     }
1751 #elif USE(V8)
1752     if (pFrame) {
1753         RefPtr<JavaInstance> addedObject = WeakJavaInstance::create(javascriptObj);
1754         const char* name = getCharactersFromJStringInEnv(env, interfaceName);
1755         // Pass ownership of the added object to bindToWindowObject.
1756         NPObject* npObject = JavaInstanceToNPObject(addedObject.get());
1757         pFrame->script()->bindToWindowObject(pFrame, name, npObject);
1758         // bindToWindowObject calls NPN_RetainObject on the
1759         // returned one (see createV8ObjectForNPObject in V8NPObject.cpp).
1760         // bindToWindowObject also increases obj's ref count and decreases
1761         // the ref count when the object is not reachable from JavaScript
1762         // side. Code here must release the reference count increased by
1763         // bindToWindowObject.
1764
1765         // Note that while this function is declared in WebCore/bridge/npruntime.h, for V8 builds
1766         // we use WebCore/bindings/v8/npruntime.cpp (rather than
1767         // WebCore/bridge/npruntime.cpp), so the function is implemented there.
1768         // TODO: Combine the two versions of these NPAPI files.
1769         NPN_ReleaseObject(npObject);
1770         releaseCharactersForJString(interfaceName, name);
1771     }
1772 #endif
1773
1774 }
1775
1776 static void SetCacheDisabled(JNIEnv *env, jobject obj, jboolean disabled)
1777 {
1778 #ifdef ANDROID_INSTRUMENT
1779     TimeCounterAuto counter(TimeCounter::NativeCallbackTimeCounter);
1780 #endif
1781     WebCore::cache()->setDisabled(disabled);
1782 }
1783
1784 static jboolean CacheDisabled(JNIEnv *env, jobject obj)
1785 {
1786 #ifdef ANDROID_INSTRUMENT
1787     TimeCounterAuto counter(TimeCounter::NativeCallbackTimeCounter);
1788 #endif
1789     return WebCore::cache()->disabled();
1790 }
1791
1792 static void ClearWebCoreCache()
1793 {
1794     if (!WebCore::cache()->disabled()) {
1795         // Disabling the cache will remove all resources from the cache.  They may
1796         // still live on if they are referenced by some Web page though.
1797         WebCore::cache()->setDisabled(true);
1798         WebCore::cache()->setDisabled(false);
1799     }
1800
1801     // clear page cache
1802     int pageCapacity = WebCore::pageCache()->capacity();
1803     // Setting size to 0, makes all pages be released.
1804     WebCore::pageCache()->setCapacity(0);
1805     WebCore::pageCache()->releaseAutoreleasedPagesNow();
1806     WebCore::pageCache()->setCapacity(pageCapacity);
1807 }
1808
1809 static void ClearWebViewCache()
1810 {
1811 #if USE(CHROME_NETWORK_STACK)
1812     WebCache::get(false /*privateBrowsing*/)->clear();
1813 #else
1814     // The Android network stack provides a WebView cache in CacheManager.java.
1815     // Clearing this is handled entirely Java-side.
1816 #endif
1817 }
1818
1819 static void ClearCache(JNIEnv *env, jobject obj)
1820 {
1821 #ifdef ANDROID_INSTRUMENT
1822     TimeCounterAuto counter(TimeCounter::NativeCallbackTimeCounter);
1823 #if USE(JSC)
1824     JSC::JSLock lock(false);
1825     JSC::Heap::Statistics jsHeapStatistics = WebCore::JSDOMWindow::commonJSGlobalData()->heap.statistics();
1826     LOGD("About to gc and JavaScript heap size is %d and has %d bytes free",
1827             jsHeapStatistics.size, jsHeapStatistics.free);
1828 #endif  // USE(JSC)
1829     LOGD("About to clear cache and current cache has %d bytes live and %d bytes dead",
1830             cache()->getLiveSize(), cache()->getDeadSize());
1831 #endif  // ANDROID_INSTRUMENT
1832     ClearWebCoreCache();
1833     ClearWebViewCache();
1834 #if USE(JSC)
1835     // force JavaScript to GC when clear cache
1836     WebCore::gcController().garbageCollectSoon();
1837 #elif USE(V8)
1838     WebCore::Frame* pFrame = GET_NATIVE_FRAME(env, obj);
1839     pFrame->script()->lowMemoryNotification();
1840 #endif  // USE(JSC)
1841 }
1842
1843 static jboolean DocumentHasImages(JNIEnv *env, jobject obj)
1844 {
1845 #ifdef ANDROID_INSTRUMENT
1846     TimeCounterAuto counter(TimeCounter::NativeCallbackTimeCounter);
1847 #endif
1848     WebCore::Frame* pFrame = GET_NATIVE_FRAME(env, obj);
1849     LOG_ASSERT(pFrame, "DocumentHasImages must take a valid frame pointer!");
1850
1851     return pFrame->document()->images()->length() > 0;
1852 }
1853
1854 static jboolean HasPasswordField(JNIEnv *env, jobject obj)
1855 {
1856 #ifdef ANDROID_INSTRUMENT
1857     TimeCounterAuto counter(TimeCounter::NativeCallbackTimeCounter);
1858 #endif
1859     WebCore::Frame* pFrame = GET_NATIVE_FRAME(env, obj);
1860     LOG_ASSERT(pFrame, "HasPasswordField must take a valid frame pointer!");
1861
1862     bool found = false;
1863     WTF::PassRefPtr<WebCore::HTMLCollection> form = pFrame->document()->forms();
1864     WebCore::Node* node = form->firstItem();
1865     // Null/Empty namespace means that node is not created in HTMLFormElement
1866     // class, but just normal Element class.
1867     while (node && !found && !node->namespaceURI().isNull() &&
1868            !node->namespaceURI().isEmpty()) {
1869         const WTF::Vector<WebCore::HTMLFormControlElement*>& elements =
1870             ((WebCore::HTMLFormElement*)node)->associatedElements();
1871         size_t size = elements.size();
1872         for (size_t i = 0; i< size && !found; i++) {
1873             WebCore::HTMLFormControlElement* e = elements[i];
1874             if (e->hasLocalName(WebCore::HTMLNames::inputTag)) {
1875                 if (static_cast<WebCore::HTMLInputElement*>(e)->isPasswordField())
1876                     found = true;
1877             }
1878         }
1879         node = form->nextItem();
1880     }
1881     return found;
1882 }
1883
1884 static jobjectArray GetUsernamePassword(JNIEnv *env, jobject obj)
1885 {
1886 #ifdef ANDROID_INSTRUMENT
1887     TimeCounterAuto counter(TimeCounter::NativeCallbackTimeCounter);
1888 #endif
1889     WebCore::Frame* pFrame = GET_NATIVE_FRAME(env, obj);
1890     LOG_ASSERT(pFrame, "GetUsernamePassword must take a valid frame pointer!");
1891     jobjectArray strArray = NULL;
1892     WTF::String username;
1893     WTF::String password;
1894     if (WebFrame::getWebFrame(pFrame)->getUsernamePasswordFromDom(pFrame, username, password)) {
1895         jclass stringClass = env->FindClass("java/lang/String");
1896         strArray = env->NewObjectArray(2, stringClass, NULL);
1897         env->DeleteLocalRef(stringClass);
1898         env->SetObjectArrayElement(strArray, 0, wtfStringToJstring(env, username));
1899         env->SetObjectArrayElement(strArray, 1, wtfStringToJstring(env, password));
1900     }
1901     return strArray;
1902 }
1903
1904 static void SetUsernamePassword(JNIEnv *env, jobject obj,
1905     jstring username, jstring password)
1906 {
1907 #ifdef ANDROID_INSTRUMENT
1908     TimeCounterAuto counter(TimeCounter::NativeCallbackTimeCounter);
1909 #endif
1910     WebCore::Frame* pFrame = GET_NATIVE_FRAME(env, obj);
1911     LOG_ASSERT(pFrame, "SetUsernamePassword must take a valid frame pointer!");
1912
1913     WebCore::HTMLInputElement* usernameEle = NULL;
1914     WebCore::HTMLInputElement* passwordEle = NULL;
1915     bool found = false;
1916     WTF::PassRefPtr<WebCore::HTMLCollection> form = pFrame->document()->forms();
1917     WebCore::Node* node = form->firstItem();
1918     while (node && !found && !node->namespaceURI().isNull() &&
1919            !node->namespaceURI().isEmpty()) {
1920         const WTF::Vector<WebCore::HTMLFormControlElement*>& elements =
1921             ((WebCore::HTMLFormElement*)node)->associatedElements();
1922         size_t size = elements.size();
1923         for (size_t i = 0; i< size && !found; i++) {
1924             WebCore::HTMLFormControlElement* e = elements[i];
1925             if (e->hasLocalName(WebCore::HTMLNames::inputTag)) {
1926                 WebCore::HTMLInputElement* input = (WebCore::HTMLInputElement*)e;
1927                 if (input->autoComplete() == false)
1928                     continue;
1929                 if (input->isPasswordField())
1930                     passwordEle = input;
1931                 else if (input->isTextField() || input->isEmailField())
1932                     usernameEle = input;
1933                 if (usernameEle != NULL && passwordEle != NULL)
1934                     found = true;
1935             }
1936         }
1937         node = form->nextItem();
1938     }
1939     if (found) {
1940         usernameEle->setValue(jstringToWtfString(env, username));
1941         passwordEle->setValue(jstringToWtfString(env, password));
1942     }
1943 }
1944
1945 void
1946 WebFrame::saveFormData(HTMLFormElement* form)
1947 {
1948     if (form->autoComplete()) {
1949         JNIEnv* env = getJNIEnv();
1950         jclass mapClass = env->FindClass("java/util/HashMap");
1951         LOG_ASSERT(mapClass, "Could not find HashMap class!");
1952         jmethodID init = env->GetMethodID(mapClass, "<init>", "(I)V");
1953         LOG_ASSERT(init, "Could not find constructor for HashMap");
1954         jobject hashMap = env->NewObject(mapClass, init, 1);
1955         LOG_ASSERT(hashMap, "Could not create a new HashMap");
1956         jmethodID put = env->GetMethodID(mapClass, "put",
1957                 "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
1958         LOG_ASSERT(put, "Could not find put method on HashMap");
1959         WTF::Vector<WebCore::HTMLFormControlElement*> elements = form->associatedElements();
1960         size_t size = elements.size();
1961         for (size_t i = 0; i < size; i++) {
1962             WebCore::HTMLFormControlElement* e = elements[i];
1963             if (e->hasTagName(WebCore::HTMLNames::inputTag)) {
1964                 WebCore::HTMLInputElement* input = static_cast<WebCore::HTMLInputElement*>(e);
1965                 if (input->isTextField() && !input->isPasswordField()
1966                         && input->autoComplete()) {
1967                     WTF::String value = input->value();
1968                     int len = value.length();
1969                     if (len) {
1970                         const WTF::AtomicString& name = input->name();
1971                         jstring key = wtfStringToJstring(env, name);
1972                         jstring val = wtfStringToJstring(env, value);
1973                         LOG_ASSERT(key && val, "name or value not set");
1974                         env->CallObjectMethod(hashMap, put, key, val);
1975                         env->DeleteLocalRef(key);
1976                         env->DeleteLocalRef(val);
1977                     }
1978                 }
1979             }
1980         }
1981         env->CallVoidMethod(mJavaFrame->frame(env).get(), mJavaFrame->mSaveFormData, hashMap);
1982         env->DeleteLocalRef(hashMap);
1983         env->DeleteLocalRef(mapClass);
1984     }
1985 }
1986
1987 static void OrientationChanged(JNIEnv *env, jobject obj, int orientation)
1988 {
1989 #ifdef ANDROID_INSTRUMENT
1990     TimeCounterAuto counter(TimeCounter::NativeCallbackTimeCounter);
1991 #endif
1992     WebCore::Frame* pFrame = GET_NATIVE_FRAME(env, obj);
1993     LOGV("Sending orientation: %d", orientation);
1994     pFrame->sendOrientationChangeEvent(orientation);
1995 }
1996
1997 #if USE(CHROME_NETWORK_STACK)
1998
1999 static void AuthenticationProceed(JNIEnv *env, jobject obj, int handle, jstring jUsername, jstring jPassword)
2000 {
2001     WebUrlLoaderClient* client = reinterpret_cast<WebUrlLoaderClient*>(handle);
2002     std::string username = jstringToStdString(env, jUsername);
2003     std::string password = jstringToStdString(env, jPassword);
2004     client->setAuth(username, password);
2005 }
2006
2007 static void AuthenticationCancel(JNIEnv *env, jobject obj, int handle)
2008 {
2009     WebUrlLoaderClient* client = reinterpret_cast<WebUrlLoaderClient*>(handle);
2010     client->cancelAuth();
2011 }
2012
2013 static void SslCertErrorProceed(JNIEnv *env, jobject obj, int handle)
2014 {
2015     WebUrlLoaderClient* client = reinterpret_cast<WebUrlLoaderClient*>(handle);
2016     client->proceedSslCertError();
2017 }
2018
2019 static void SslCertErrorCancel(JNIEnv *env, jobject obj, int handle, int cert_error)
2020 {
2021     WebUrlLoaderClient* client = reinterpret_cast<WebUrlLoaderClient*>(handle);
2022     client->cancelSslCertError(cert_error);
2023 }
2024
2025 #else
2026
2027 static void AuthenticationProceed(JNIEnv *env, jobject obj, int handle, jstring jUsername, jstring jPassword)
2028 {
2029     LOGW("Chromium authentication API called, but libchromium is not available");
2030 }
2031
2032 static void AuthenticationCancel(JNIEnv *env, jobject obj, int handle)
2033 {
2034     LOGW("Chromium authentication API called, but libchromium is not available");
2035 }
2036
2037 static void SslCertErrorProceed(JNIEnv *env, jobject obj, int handle)
2038 {
2039     LOGW("Chromium SSL API called, but libchromium is not available");
2040 }
2041
2042 static void SslCertErrorCancel(JNIEnv *env, jobject obj, int handle, int cert_error)
2043 {
2044     LOGW("Chromium SSL API called, but libchromium is not available");
2045 }
2046
2047 #endif // USE(CHROME_NETWORK_STACK)
2048
2049 // ----------------------------------------------------------------------------
2050
2051 /*
2052  * JNI registration.
2053  */
2054 static JNINativeMethod gBrowserFrameNativeMethods[] = {
2055     /* name, signature, funcPtr */
2056     { "nativeCallPolicyFunction", "(II)V",
2057         (void*) CallPolicyFunction },
2058     { "nativeCreateFrame", "(Landroid/webkit/WebViewCore;Landroid/content/res/AssetManager;Landroid/webkit/WebBackForwardList;)V",
2059         (void*) CreateFrame },
2060     { "nativeDestroyFrame", "()V",
2061         (void*) DestroyFrame },
2062     { "nativeStopLoading", "()V",
2063         (void*) StopLoading },
2064     { "nativeLoadUrl", "(Ljava/lang/String;Ljava/util/Map;)V",
2065         (void*) LoadUrl },
2066     { "nativePostUrl", "(Ljava/lang/String;[B)V",
2067         (void*) PostUrl },
2068     { "nativeLoadData", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V",
2069         (void*) LoadData },
2070     { "nativeSaveWebArchive", "(Ljava/lang/String;Z)Ljava/lang/String;",
2071         (void*) SaveWebArchive },
2072     { "externalRepresentation", "()Ljava/lang/String;",
2073         (void*) ExternalRepresentation },
2074     { "documentAsText", "()Ljava/lang/String;",
2075         (void*) DocumentAsText },
2076     { "childFramesAsText", "()Ljava/lang/String;",
2077         (void*) ChildFramesAsText },
2078     { "reload", "(Z)V",
2079         (void*) Reload },
2080     { "nativeGoBackOrForward", "(I)V",
2081         (void*) GoBackOrForward },
2082     { "nativeAddJavascriptInterface", "(ILjava/lang/Object;Ljava/lang/String;)V",
2083         (void*) AddJavascriptInterface },
2084     { "stringByEvaluatingJavaScriptFromString",
2085             "(Ljava/lang/String;)Ljava/lang/String;",
2086         (void*) StringByEvaluatingJavaScriptFromString },
2087     { "setCacheDisabled", "(Z)V",
2088         (void*) SetCacheDisabled },
2089     { "cacheDisabled", "()Z",
2090         (void*) CacheDisabled },
2091     { "clearCache", "()V",
2092         (void*) ClearCache },
2093     { "documentHasImages", "()Z",
2094         (void*) DocumentHasImages },
2095     { "hasPasswordField", "()Z",
2096         (void*) HasPasswordField },
2097     { "getUsernamePassword", "()[Ljava/lang/String;",
2098         (void*) GetUsernamePassword },
2099     { "setUsernamePassword", "(Ljava/lang/String;Ljava/lang/String;)V",
2100         (void*) SetUsernamePassword },
2101     { "nativeOrientationChanged", "(I)V",
2102         (void*) OrientationChanged },
2103     { "nativeAuthenticationProceed", "(ILjava/lang/String;Ljava/lang/String;)V",
2104         (void*) AuthenticationProceed },
2105     { "nativeAuthenticationCancel", "(I)V",
2106         (void*) AuthenticationCancel },
2107     { "nativeSslCertErrorProceed", "(I)V",
2108         (void*) SslCertErrorProceed },
2109     { "nativeSslCertErrorCancel", "(II)V",
2110         (void*) SslCertErrorCancel },
2111 };
2112
2113 int registerWebFrame(JNIEnv* env)
2114 {
2115     jclass clazz = env->FindClass("android/webkit/BrowserFrame");
2116     LOG_ASSERT(clazz, "Cannot find BrowserFrame");
2117     gFrameField = env->GetFieldID(clazz, "mNativeFrame", "I");
2118     LOG_ASSERT(gFrameField, "Cannot find mNativeFrame on BrowserFrame");
2119     env->DeleteLocalRef(clazz);
2120
2121     return jniRegisterNativeMethods(env, "android/webkit/BrowserFrame",
2122             gBrowserFrameNativeMethods, NELEM(gBrowserFrameNativeMethods));
2123 }
2124
2125 } /* namespace android */