Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / android_webview / native / aw_contents.cc
blob4c8a4f288a66cdbc1951fee059e2655cfa9d7d3e
1 // Copyright 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "android_webview/native/aw_contents.h"
7 #include <limits>
9 #include "android_webview/browser/aw_browser_context.h"
10 #include "android_webview/browser/aw_browser_main_parts.h"
11 #include "android_webview/browser/aw_resource_context.h"
12 #include "android_webview/browser/browser_view_renderer.h"
13 #include "android_webview/browser/deferred_gpu_command_service.h"
14 #include "android_webview/browser/gpu_memory_buffer_factory_impl.h"
15 #include "android_webview/browser/hardware_renderer.h"
16 #include "android_webview/browser/net_disk_cache_remover.h"
17 #include "android_webview/browser/renderer_host/aw_resource_dispatcher_host_delegate.h"
18 #include "android_webview/browser/scoped_app_gl_state_restore.h"
19 #include "android_webview/common/aw_hit_test_data.h"
20 #include "android_webview/common/devtools_instrumentation.h"
21 #include "android_webview/native/aw_autofill_client.h"
22 #include "android_webview/native/aw_browser_dependency_factory.h"
23 #include "android_webview/native/aw_contents_client_bridge.h"
24 #include "android_webview/native/aw_contents_io_thread_client_impl.h"
25 #include "android_webview/native/aw_pdf_exporter.h"
26 #include "android_webview/native/aw_picture.h"
27 #include "android_webview/native/aw_web_contents_delegate.h"
28 #include "android_webview/native/java_browser_view_renderer_helper.h"
29 #include "android_webview/native/permission/aw_permission_request.h"
30 #include "android_webview/native/permission/permission_request_handler.h"
31 #include "android_webview/native/permission/simple_permission_request.h"
32 #include "android_webview/native/state_serializer.h"
33 #include "android_webview/public/browser/draw_gl.h"
34 #include "base/android/jni_android.h"
35 #include "base/android/jni_array.h"
36 #include "base/android/jni_string.h"
37 #include "base/android/scoped_java_ref.h"
38 #include "base/atomicops.h"
39 #include "base/bind.h"
40 #include "base/callback.h"
41 #include "base/memory/memory_pressure_listener.h"
42 #include "base/message_loop/message_loop.h"
43 #include "base/pickle.h"
44 #include "base/strings/string16.h"
45 #include "base/supports_user_data.h"
46 #include "components/autofill/content/browser/content_autofill_driver.h"
47 #include "components/autofill/core/browser/autofill_manager.h"
48 #include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
49 #include "components/data_reduction_proxy/browser/data_reduction_proxy_settings.h"
50 #include "components/navigation_interception/intercept_navigation_delegate.h"
51 #include "content/public/browser/android/content_view_core.h"
52 #include "content/public/browser/browser_thread.h"
53 #include "content/public/browser/cert_store.h"
54 #include "content/public/browser/favicon_status.h"
55 #include "content/public/browser/navigation_entry.h"
56 #include "content/public/browser/render_frame_host.h"
57 #include "content/public/browser/render_process_host.h"
58 #include "content/public/browser/render_view_host.h"
59 #include "content/public/browser/web_contents.h"
60 #include "content/public/common/renderer_preferences.h"
61 #include "content/public/common/ssl_status.h"
62 #include "jni/AwContents_jni.h"
63 #include "net/base/auth.h"
64 #include "net/cert/x509_certificate.h"
65 #include "third_party/skia/include/core/SkPicture.h"
66 #include "ui/base/l10n/l10n_util_android.h"
67 #include "ui/gfx/android/java_bitmap.h"
68 #include "ui/gfx/image/image.h"
69 #include "ui/gfx/size.h"
71 struct AwDrawSWFunctionTable;
72 struct AwDrawGLFunctionTable;
74 using autofill::ContentAutofillDriver;
75 using autofill::AutofillManager;
76 using base::android::AttachCurrentThread;
77 using base::android::ConvertJavaStringToUTF16;
78 using base::android::ConvertJavaStringToUTF8;
79 using base::android::ConvertUTF16ToJavaString;
80 using base::android::ConvertUTF8ToJavaString;
81 using base::android::JavaRef;
82 using base::android::ScopedJavaGlobalRef;
83 using base::android::ScopedJavaLocalRef;
84 using data_reduction_proxy::DataReductionProxySettings;
85 using navigation_interception::InterceptNavigationDelegate;
86 using content::BrowserThread;
87 using content::ContentViewCore;
88 using content::WebContents;
90 extern "C" {
91 static AwDrawGLFunction DrawGLFunction;
92 static void DrawGLFunction(long view_context,
93 AwDrawGLInfo* draw_info,
94 void* spare) {
95 // |view_context| is the value that was returned from the java
96 // AwContents.onPrepareDrawGL; this cast must match the code there.
97 reinterpret_cast<android_webview::AwContents*>(view_context)
98 ->DrawGL(draw_info);
102 namespace android_webview {
104 namespace {
106 bool g_should_download_favicons = false;
108 const void* kAwContentsUserDataKey = &kAwContentsUserDataKey;
110 class AwContentsUserData : public base::SupportsUserData::Data {
111 public:
112 AwContentsUserData(AwContents* ptr) : contents_(ptr) {}
114 static AwContents* GetContents(WebContents* web_contents) {
115 if (!web_contents)
116 return NULL;
117 AwContentsUserData* data = reinterpret_cast<AwContentsUserData*>(
118 web_contents->GetUserData(kAwContentsUserDataKey));
119 return data ? data->contents_ : NULL;
122 private:
123 AwContents* contents_;
126 base::subtle::Atomic32 g_instance_count = 0;
128 void OnIoThreadClientReady(content::RenderFrameHost* rfh) {
129 int render_process_id = rfh->GetProcess()->GetID();
130 int render_frame_id = rfh->GetRoutingID();
131 AwResourceDispatcherHostDelegate::OnIoThreadClientReady(
132 render_process_id, render_frame_id);
135 } // namespace
137 // static
138 AwContents* AwContents::FromWebContents(WebContents* web_contents) {
139 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
140 return AwContentsUserData::GetContents(web_contents);
143 // static
144 AwContents* AwContents::FromID(int render_process_id, int render_view_id) {
145 const content::RenderViewHost* rvh =
146 content::RenderViewHost::FromID(render_process_id, render_view_id);
147 if (!rvh) return NULL;
148 content::WebContents* web_contents =
149 content::WebContents::FromRenderViewHost(rvh);
150 if (!web_contents) return NULL;
151 return FromWebContents(web_contents);
154 // static
155 AwBrowserPermissionRequestDelegate* AwBrowserPermissionRequestDelegate::FromID(
156 int render_process_id, int render_view_id) {
157 AwContents* aw_contents = AwContents::FromID(render_process_id,
158 render_view_id);
159 return implicit_cast<AwBrowserPermissionRequestDelegate*>(aw_contents);
162 AwContents::AwContents(scoped_ptr<WebContents> web_contents)
163 : web_contents_(web_contents.Pass()),
164 shared_renderer_state_(
165 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI),
166 this),
167 browser_view_renderer_(
168 this,
169 &shared_renderer_state_,
170 web_contents_.get(),
171 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI)),
172 renderer_manager_key_(GLViewRendererManager::GetInstance()->NullKey()) {
173 base::subtle::NoBarrier_AtomicIncrement(&g_instance_count, 1);
174 icon_helper_.reset(new IconHelper(web_contents_.get()));
175 icon_helper_->SetListener(this);
176 web_contents_->SetUserData(kAwContentsUserDataKey,
177 new AwContentsUserData(this));
178 render_view_host_ext_.reset(
179 new AwRenderViewHostExt(this, web_contents_.get()));
181 permission_request_handler_.reset(
182 new PermissionRequestHandler(this, web_contents_.get()));
184 AwAutofillClient* autofill_manager_delegate =
185 AwAutofillClient::FromWebContents(web_contents_.get());
186 InitDataReductionProxyIfNecessary();
187 if (autofill_manager_delegate)
188 InitAutofillIfNecessary(autofill_manager_delegate->GetSaveFormData());
191 void AwContents::SetJavaPeers(JNIEnv* env,
192 jobject obj,
193 jobject aw_contents,
194 jobject web_contents_delegate,
195 jobject contents_client_bridge,
196 jobject io_thread_client,
197 jobject intercept_navigation_delegate) {
198 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
199 // The |aw_content| param is technically spurious as it duplicates |obj| but
200 // is passed over anyway to make the binding more explicit.
201 java_ref_ = JavaObjectWeakGlobalRef(env, aw_contents);
203 web_contents_delegate_.reset(
204 new AwWebContentsDelegate(env, web_contents_delegate));
205 web_contents_->SetDelegate(web_contents_delegate_.get());
207 contents_client_bridge_.reset(
208 new AwContentsClientBridge(env, contents_client_bridge));
209 AwContentsClientBridgeBase::Associate(web_contents_.get(),
210 contents_client_bridge_.get());
212 AwContentsIoThreadClientImpl::Associate(
213 web_contents_.get(), ScopedJavaLocalRef<jobject>(env, io_thread_client));
215 InterceptNavigationDelegate::Associate(
216 web_contents_.get(),
217 make_scoped_ptr(new InterceptNavigationDelegate(
218 env, intercept_navigation_delegate)));
220 // Finally, having setup the associations, release any deferred requests
221 web_contents_->ForEachFrame(base::Bind(&OnIoThreadClientReady));
224 void AwContents::SetSaveFormData(bool enabled) {
225 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
226 InitAutofillIfNecessary(enabled);
227 // We need to check for the existence, since autofill_manager_delegate
228 // may not be created when the setting is false.
229 if (ContentAutofillDriver::FromWebContents(web_contents_.get())) {
230 AwAutofillClient::FromWebContents(web_contents_.get())->
231 SetSaveFormData(enabled);
235 void AwContents::InitDataReductionProxyIfNecessary() {
236 AwBrowserContext* browser_context =
237 AwBrowserContext::FromWebContents(web_contents_.get());
238 browser_context->CreateUserPrefServiceIfNecessary();
241 void AwContents::InitAutofillIfNecessary(bool enabled) {
242 // Do not initialize if the feature is not enabled.
243 if (!enabled)
244 return;
245 // Check if the autofill driver already exists.
246 content::WebContents* web_contents = web_contents_.get();
247 if (ContentAutofillDriver::FromWebContents(web_contents))
248 return;
250 AwBrowserContext::FromWebContents(web_contents)->
251 CreateUserPrefServiceIfNecessary();
252 AwAutofillClient::CreateForWebContents(web_contents);
253 ContentAutofillDriver::CreateForWebContentsAndDelegate(
254 web_contents,
255 AwAutofillClient::FromWebContents(web_contents),
256 l10n_util::GetDefaultLocale(),
257 AutofillManager::DISABLE_AUTOFILL_DOWNLOAD_MANAGER);
260 void AwContents::SetAwAutofillClient(jobject client) {
261 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
262 JNIEnv* env = AttachCurrentThread();
263 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
264 if (obj.is_null())
265 return;
266 Java_AwContents_setAwAutofillClient(env, obj.obj(), client);
269 AwContents::~AwContents() {
270 DCHECK(AwContents::FromWebContents(web_contents_.get()) == this);
271 DCHECK(!hardware_renderer_.get());
272 web_contents_->RemoveUserData(kAwContentsUserDataKey);
273 if (find_helper_.get())
274 find_helper_->SetListener(NULL);
275 if (icon_helper_.get())
276 icon_helper_->SetListener(NULL);
277 base::subtle::NoBarrier_AtomicIncrement(&g_instance_count, -1);
278 // When the last WebView is destroyed free all discardable memory allocated by
279 // Chromium, because the app process may continue to run for a long time
280 // without ever using another WebView.
281 if (base::subtle::NoBarrier_Load(&g_instance_count) == 0) {
282 base::MemoryPressureListener::NotifyMemoryPressure(
283 base::MemoryPressureListener::MEMORY_PRESSURE_CRITICAL);
287 jlong AwContents::GetWebContents(JNIEnv* env, jobject obj) {
288 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
289 DCHECK(web_contents_);
290 return reinterpret_cast<intptr_t>(web_contents_.get());
293 void AwContents::Destroy(JNIEnv* env, jobject obj) {
294 java_ref_.reset();
296 // We clear the contents_client_bridge_ here so that we break the link with
297 // the java peer. This is important for the popup window case, where we are
298 // swapping AwContents out that share the same java AwContentsClientBridge.
299 // See b/15074651.
300 contents_client_bridge_.reset();
302 // We do not delete AwContents immediately. Some applications try to delete
303 // Webview in ShouldOverrideUrlLoading callback, which is a sync IPC from
304 // Webkit.
305 BrowserThread::DeleteSoon(BrowserThread::UI, FROM_HERE, this);
308 static jlong Init(JNIEnv* env, jclass, jobject browser_context) {
309 // TODO(joth): Use |browser_context| to get the native BrowserContext, rather
310 // than hard-code the default instance lookup here.
311 scoped_ptr<WebContents> web_contents(content::WebContents::Create(
312 content::WebContents::CreateParams(AwBrowserContext::GetDefault())));
313 // Return an 'uninitialized' instance; most work is deferred until the
314 // subsequent SetJavaPeers() call.
315 return reinterpret_cast<intptr_t>(new AwContents(web_contents.Pass()));
318 static void SetAwDrawSWFunctionTable(JNIEnv* env, jclass,
319 jlong function_table) {
320 JavaBrowserViewRendererHelper::SetAwDrawSWFunctionTable(
321 reinterpret_cast<AwDrawSWFunctionTable*>(function_table));
324 static void SetAwDrawGLFunctionTable(JNIEnv* env, jclass,
325 jlong function_table) {
326 GpuMemoryBufferFactoryImpl::SetAwDrawGLFunctionTable(
327 reinterpret_cast<AwDrawGLFunctionTable*>(function_table));
330 static jlong GetAwDrawGLFunction(JNIEnv* env, jclass) {
331 return reinterpret_cast<intptr_t>(&DrawGLFunction);
334 // static
335 jint GetNativeInstanceCount(JNIEnv* env, jclass) {
336 return base::subtle::NoBarrier_Load(&g_instance_count);
339 jlong AwContents::GetAwDrawGLViewContext(JNIEnv* env, jobject obj) {
340 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
341 return reinterpret_cast<intptr_t>(this);
344 void AwContents::DrawGL(AwDrawGLInfo* draw_info) {
345 if (draw_info->mode == AwDrawGLInfo::kModeSync) {
346 if (hardware_renderer_)
347 hardware_renderer_->CommitFrame();
348 return;
352 GLViewRendererManager* manager = GLViewRendererManager::GetInstance();
353 base::AutoLock lock(render_thread_lock_);
354 if (renderer_manager_key_ != manager->NullKey()) {
355 manager->DidDrawGL(renderer_manager_key_);
359 ScopedAppGLStateRestore state_restore(
360 draw_info->mode == AwDrawGLInfo::kModeDraw
361 ? ScopedAppGLStateRestore::MODE_DRAW
362 : ScopedAppGLStateRestore::MODE_RESOURCE_MANAGEMENT);
363 ScopedAllowGL allow_gl;
365 if (draw_info->mode == AwDrawGLInfo::kModeProcessNoContext) {
366 LOG(ERROR) << "Received unexpected kModeProcessNoContext";
369 // kModeProcessNoContext should never happen because we tear down hardware
370 // in onTrimMemory. However that guarantee is maintained outside of chromium
371 // code. Not notifying shared state in kModeProcessNoContext can lead to
372 // immediate deadlock, which is slightly more catastrophic than leaks or
373 // corruption.
374 if (draw_info->mode == AwDrawGLInfo::kModeProcess ||
375 draw_info->mode == AwDrawGLInfo::kModeProcessNoContext) {
376 shared_renderer_state_.DidDrawGLProcess();
379 if (shared_renderer_state_.IsInsideHardwareRelease()) {
380 hardware_renderer_.reset();
381 // Flush the idle queue in tear down.
382 DeferredGpuCommandService::GetInstance()->PerformAllIdleWork();
383 return;
386 if (draw_info->mode != AwDrawGLInfo::kModeDraw) {
387 if (draw_info->mode == AwDrawGLInfo::kModeProcess) {
388 DeferredGpuCommandService::GetInstance()->PerformIdleWork(true);
390 return;
393 if (!hardware_renderer_) {
394 hardware_renderer_.reset(new HardwareRenderer(&shared_renderer_state_));
395 hardware_renderer_->CommitFrame();
398 hardware_renderer_->DrawGL(state_restore.stencil_enabled(),
399 state_restore.framebuffer_binding_ext(),
400 draw_info);
401 DeferredGpuCommandService::GetInstance()->PerformIdleWork(false);
404 namespace {
405 void DocumentHasImagesCallback(const ScopedJavaGlobalRef<jobject>& message,
406 bool has_images) {
407 Java_AwContents_onDocumentHasImagesResponse(AttachCurrentThread(),
408 has_images,
409 message.obj());
411 } // namespace
413 void AwContents::DocumentHasImages(JNIEnv* env, jobject obj, jobject message) {
414 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
415 ScopedJavaGlobalRef<jobject> j_message;
416 j_message.Reset(env, message);
417 render_view_host_ext_->DocumentHasImages(
418 base::Bind(&DocumentHasImagesCallback, j_message));
421 namespace {
422 void GenerateMHTMLCallback(ScopedJavaGlobalRef<jobject>* callback,
423 const base::FilePath& path, int64 size) {
424 JNIEnv* env = AttachCurrentThread();
425 // Android files are UTF8, so the path conversion below is safe.
426 Java_AwContents_generateMHTMLCallback(
427 env,
428 ConvertUTF8ToJavaString(env, path.AsUTF8Unsafe()).obj(),
429 size, callback->obj());
431 } // namespace
433 void AwContents::GenerateMHTML(JNIEnv* env, jobject obj,
434 jstring jpath, jobject callback) {
435 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
436 ScopedJavaGlobalRef<jobject>* j_callback = new ScopedJavaGlobalRef<jobject>();
437 j_callback->Reset(env, callback);
438 base::FilePath target_path(ConvertJavaStringToUTF8(env, jpath));
439 web_contents_->GenerateMHTML(
440 target_path,
441 base::Bind(&GenerateMHTMLCallback, base::Owned(j_callback), target_path));
444 void AwContents::CreatePdfExporter(JNIEnv* env,
445 jobject obj,
446 jobject pdfExporter) {
447 pdf_exporter_.reset(
448 new AwPdfExporter(env,
449 pdfExporter,
450 web_contents_.get()));
453 bool AwContents::OnReceivedHttpAuthRequest(const JavaRef<jobject>& handler,
454 const std::string& host,
455 const std::string& realm) {
456 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
457 JNIEnv* env = AttachCurrentThread();
458 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
459 if (obj.is_null())
460 return false;
462 ScopedJavaLocalRef<jstring> jhost = ConvertUTF8ToJavaString(env, host);
463 ScopedJavaLocalRef<jstring> jrealm = ConvertUTF8ToJavaString(env, realm);
464 devtools_instrumentation::ScopedEmbedderCallbackTask embedder_callback(
465 "onReceivedHttpAuthRequest");
466 Java_AwContents_onReceivedHttpAuthRequest(env, obj.obj(), handler.obj(),
467 jhost.obj(), jrealm.obj());
468 return true;
471 void AwContents::AddVisitedLinks(JNIEnv* env,
472 jobject obj,
473 jobjectArray jvisited_links) {
474 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
475 std::vector<base::string16> visited_link_strings;
476 base::android::AppendJavaStringArrayToStringVector(
477 env, jvisited_links, &visited_link_strings);
479 std::vector<GURL> visited_link_gurls;
480 std::vector<base::string16>::const_iterator itr;
481 for (itr = visited_link_strings.begin(); itr != visited_link_strings.end();
482 ++itr) {
483 visited_link_gurls.push_back(GURL(*itr));
486 AwBrowserContext::FromWebContents(web_contents_.get())
487 ->AddVisitedURLs(visited_link_gurls);
490 bool RegisterAwContents(JNIEnv* env) {
491 return RegisterNativesImpl(env);
494 namespace {
496 void ShowGeolocationPromptHelperTask(const JavaObjectWeakGlobalRef& java_ref,
497 const GURL& origin) {
498 JNIEnv* env = AttachCurrentThread();
499 ScopedJavaLocalRef<jobject> j_ref = java_ref.get(env);
500 if (j_ref.obj()) {
501 ScopedJavaLocalRef<jstring> j_origin(
502 ConvertUTF8ToJavaString(env, origin.spec()));
503 devtools_instrumentation::ScopedEmbedderCallbackTask embedder_callback(
504 "onGeolocationPermissionsShowPrompt");
505 Java_AwContents_onGeolocationPermissionsShowPrompt(env,
506 j_ref.obj(),
507 j_origin.obj());
511 void ShowGeolocationPromptHelper(const JavaObjectWeakGlobalRef& java_ref,
512 const GURL& origin) {
513 JNIEnv* env = AttachCurrentThread();
514 if (java_ref.get(env).obj()) {
515 content::BrowserThread::PostTask(
516 content::BrowserThread::UI,
517 FROM_HERE,
518 base::Bind(&ShowGeolocationPromptHelperTask,
519 java_ref,
520 origin));
524 } // anonymous namespace
526 void AwContents::ShowGeolocationPrompt(const GURL& requesting_frame,
527 base::Callback<void(bool)> callback) {
528 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
530 GURL origin = requesting_frame.GetOrigin();
531 bool show_prompt = pending_geolocation_prompts_.empty();
532 pending_geolocation_prompts_.push_back(OriginCallback(origin, callback));
533 if (show_prompt) {
534 ShowGeolocationPromptHelper(java_ref_, origin);
538 // Invoked from Java
539 void AwContents::InvokeGeolocationCallback(JNIEnv* env,
540 jobject obj,
541 jboolean value,
542 jstring origin) {
543 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
545 GURL callback_origin(base::android::ConvertJavaStringToUTF16(env, origin));
546 if (callback_origin.GetOrigin() ==
547 pending_geolocation_prompts_.front().first) {
548 pending_geolocation_prompts_.front().second.Run(value);
549 pending_geolocation_prompts_.pop_front();
550 if (!pending_geolocation_prompts_.empty()) {
551 ShowGeolocationPromptHelper(java_ref_,
552 pending_geolocation_prompts_.front().first);
557 void AwContents::HideGeolocationPrompt(const GURL& origin) {
558 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
559 bool removed_current_outstanding_callback = false;
560 std::list<OriginCallback>::iterator it = pending_geolocation_prompts_.begin();
561 while (it != pending_geolocation_prompts_.end()) {
562 if ((*it).first == origin.GetOrigin()) {
563 if (it == pending_geolocation_prompts_.begin()) {
564 removed_current_outstanding_callback = true;
566 it = pending_geolocation_prompts_.erase(it);
567 } else {
568 ++it;
572 if (removed_current_outstanding_callback) {
573 JNIEnv* env = AttachCurrentThread();
574 ScopedJavaLocalRef<jobject> j_ref = java_ref_.get(env);
575 if (j_ref.obj()) {
576 devtools_instrumentation::ScopedEmbedderCallbackTask embedder_callback(
577 "onGeolocationPermissionsHidePrompt");
578 Java_AwContents_onGeolocationPermissionsHidePrompt(env, j_ref.obj());
580 if (!pending_geolocation_prompts_.empty()) {
581 ShowGeolocationPromptHelper(java_ref_,
582 pending_geolocation_prompts_.front().first);
587 void AwContents::OnPermissionRequest(AwPermissionRequest* request) {
588 JNIEnv* env = AttachCurrentThread();
589 ScopedJavaLocalRef<jobject> j_request = request->CreateJavaPeer();
590 ScopedJavaLocalRef<jobject> j_ref = java_ref_.get(env);
591 if (j_request.is_null() || j_ref.is_null()) {
592 permission_request_handler_->CancelRequest(
593 request->GetOrigin(), request->GetResources());
594 return;
597 Java_AwContents_onPermissionRequest(env, j_ref.obj(), j_request.obj());
600 void AwContents::OnPermissionRequestCanceled(AwPermissionRequest* request) {
601 JNIEnv* env = AttachCurrentThread();
602 ScopedJavaLocalRef<jobject> j_request = request->GetJavaObject();
603 ScopedJavaLocalRef<jobject> j_ref = java_ref_.get(env);
604 if (j_request.is_null() || j_ref.is_null())
605 return;
607 Java_AwContents_onPermissionRequestCanceled(
608 env, j_ref.obj(), j_request.obj());
611 void AwContents::PreauthorizePermission(
612 JNIEnv* env,
613 jobject obj,
614 jstring origin,
615 jlong resources) {
616 permission_request_handler_->PreauthorizePermission(
617 GURL(base::android::ConvertJavaStringToUTF8(env, origin)), resources);
620 void AwContents::RequestProtectedMediaIdentifierPermission(
621 const GURL& origin,
622 const base::Callback<void(bool)>& callback) {
623 permission_request_handler_->SendRequest(
624 scoped_ptr<AwPermissionRequestDelegate>(new SimplePermissionRequest(
625 origin, AwPermissionRequest::ProtectedMediaId, callback)));
628 void AwContents::CancelProtectedMediaIdentifierPermissionRequests(
629 const GURL& origin) {
630 permission_request_handler_->CancelRequest(
631 origin, AwPermissionRequest::ProtectedMediaId);
634 void AwContents::RequestGeolocationPermission(
635 const GURL& origin,
636 const base::Callback<void(bool)>& callback) {
637 JNIEnv* env = AttachCurrentThread();
638 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
639 if (obj.is_null())
640 return;
642 if (Java_AwContents_useLegacyGeolocationPermissionAPI(env, obj.obj())) {
643 ShowGeolocationPrompt(origin, callback);
644 return;
646 permission_request_handler_->SendRequest(
647 scoped_ptr<AwPermissionRequestDelegate>(new SimplePermissionRequest(
648 origin, AwPermissionRequest::Geolocation, callback)));
651 void AwContents::CancelGeolocationPermissionRequests(const GURL& origin) {
652 JNIEnv* env = AttachCurrentThread();
653 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
654 if (obj.is_null())
655 return;
657 if (Java_AwContents_useLegacyGeolocationPermissionAPI(env, obj.obj())) {
658 HideGeolocationPrompt(origin);
659 return;
661 permission_request_handler_->CancelRequest(
662 origin, AwPermissionRequest::Geolocation);
665 void AwContents::FindAllAsync(JNIEnv* env, jobject obj, jstring search_string) {
666 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
667 GetFindHelper()->FindAllAsync(ConvertJavaStringToUTF16(env, search_string));
670 void AwContents::FindNext(JNIEnv* env, jobject obj, jboolean forward) {
671 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
672 GetFindHelper()->FindNext(forward);
675 void AwContents::ClearMatches(JNIEnv* env, jobject obj) {
676 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
677 GetFindHelper()->ClearMatches();
680 void AwContents::ClearCache(
681 JNIEnv* env,
682 jobject obj,
683 jboolean include_disk_files) {
684 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
685 render_view_host_ext_->ClearCache();
687 if (include_disk_files) {
688 RemoveHttpDiskCache(web_contents_->GetBrowserContext(),
689 web_contents_->GetRoutingID());
693 FindHelper* AwContents::GetFindHelper() {
694 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
695 if (!find_helper_.get()) {
696 find_helper_.reset(new FindHelper(web_contents_.get()));
697 find_helper_->SetListener(this);
699 return find_helper_.get();
702 void AwContents::OnFindResultReceived(int active_ordinal,
703 int match_count,
704 bool finished) {
705 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
706 JNIEnv* env = AttachCurrentThread();
707 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
708 if (obj.is_null())
709 return;
711 Java_AwContents_onFindResultReceived(
712 env, obj.obj(), active_ordinal, match_count, finished);
715 bool AwContents::ShouldDownloadFavicon(const GURL& icon_url) {
716 return g_should_download_favicons;
719 void AwContents::OnReceivedIcon(const GURL& icon_url, const SkBitmap& bitmap) {
720 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
721 JNIEnv* env = AttachCurrentThread();
722 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
723 if (obj.is_null())
724 return;
726 content::NavigationEntry* entry =
727 web_contents_->GetController().GetActiveEntry();
729 if (entry) {
730 entry->GetFavicon().valid = true;
731 entry->GetFavicon().url = icon_url;
732 entry->GetFavicon().image = gfx::Image::CreateFrom1xBitmap(bitmap);
735 Java_AwContents_onReceivedIcon(
736 env, obj.obj(), gfx::ConvertToJavaBitmap(&bitmap).obj());
739 void AwContents::OnReceivedTouchIconUrl(const std::string& url,
740 bool precomposed) {
741 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
742 JNIEnv* env = AttachCurrentThread();
743 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
744 if (obj.is_null())
745 return;
747 Java_AwContents_onReceivedTouchIconUrl(
748 env, obj.obj(), ConvertUTF8ToJavaString(env, url).obj(), precomposed);
751 bool AwContents::RequestDrawGL(jobject canvas, bool wait_for_completion) {
752 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
753 DCHECK(!canvas || !wait_for_completion);
754 JNIEnv* env = AttachCurrentThread();
755 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
756 if (obj.is_null())
757 return false;
758 return Java_AwContents_requestDrawGL(
759 env, obj.obj(), canvas, wait_for_completion);
762 void AwContents::PostInvalidate() {
763 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
764 JNIEnv* env = AttachCurrentThread();
765 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
766 if (!obj.is_null())
767 Java_AwContents_postInvalidateOnAnimation(env, obj.obj());
770 void AwContents::UpdateParentDrawConstraints() {
771 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
772 browser_view_renderer_.UpdateParentDrawConstraints();
775 void AwContents::OnNewPicture() {
776 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
777 JNIEnv* env = AttachCurrentThread();
778 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
779 if (!obj.is_null()) {
780 devtools_instrumentation::ScopedEmbedderCallbackTask embedder_callback(
781 "onNewPicture");
782 Java_AwContents_onNewPicture(env, obj.obj());
786 base::android::ScopedJavaLocalRef<jbyteArray>
787 AwContents::GetCertificate(JNIEnv* env,
788 jobject obj) {
789 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
790 content::NavigationEntry* entry =
791 web_contents_->GetController().GetActiveEntry();
792 if (!entry)
793 return ScopedJavaLocalRef<jbyteArray>();
794 // Get the certificate
795 int cert_id = entry->GetSSL().cert_id;
796 scoped_refptr<net::X509Certificate> cert;
797 bool ok = content::CertStore::GetInstance()->RetrieveCert(cert_id, &cert);
798 if (!ok)
799 return ScopedJavaLocalRef<jbyteArray>();
801 // Convert the certificate and return it
802 std::string der_string;
803 net::X509Certificate::GetDEREncoded(cert->os_cert_handle(), &der_string);
804 return base::android::ToJavaByteArray(env,
805 reinterpret_cast<const uint8*>(der_string.data()), der_string.length());
808 void AwContents::RequestNewHitTestDataAt(JNIEnv* env, jobject obj,
809 jint x, jint y) {
810 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
811 render_view_host_ext_->RequestNewHitTestDataAt(x, y);
814 void AwContents::UpdateLastHitTestData(JNIEnv* env, jobject obj) {
815 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
816 if (!render_view_host_ext_->HasNewHitTestData()) return;
818 const AwHitTestData& data = render_view_host_ext_->GetLastHitTestData();
819 render_view_host_ext_->MarkHitTestDataRead();
821 // Make sure to null the Java object if data is empty/invalid.
822 ScopedJavaLocalRef<jstring> extra_data_for_type;
823 if (data.extra_data_for_type.length())
824 extra_data_for_type = ConvertUTF8ToJavaString(
825 env, data.extra_data_for_type);
827 ScopedJavaLocalRef<jstring> href;
828 if (data.href.length())
829 href = ConvertUTF16ToJavaString(env, data.href);
831 ScopedJavaLocalRef<jstring> anchor_text;
832 if (data.anchor_text.length())
833 anchor_text = ConvertUTF16ToJavaString(env, data.anchor_text);
835 ScopedJavaLocalRef<jstring> img_src;
836 if (data.img_src.is_valid())
837 img_src = ConvertUTF8ToJavaString(env, data.img_src.spec());
839 Java_AwContents_updateHitTestData(env,
840 obj,
841 data.type,
842 extra_data_for_type.obj(),
843 href.obj(),
844 anchor_text.obj(),
845 img_src.obj());
848 void AwContents::OnSizeChanged(JNIEnv* env, jobject obj,
849 int w, int h, int ow, int oh) {
850 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
851 browser_view_renderer_.OnSizeChanged(w, h);
854 void AwContents::SetViewVisibility(JNIEnv* env, jobject obj, bool visible) {
855 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
856 browser_view_renderer_.SetViewVisibility(visible);
859 void AwContents::SetWindowVisibility(JNIEnv* env, jobject obj, bool visible) {
860 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
861 browser_view_renderer_.SetWindowVisibility(visible);
864 void AwContents::SetIsPaused(JNIEnv* env, jobject obj, bool paused) {
865 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
866 browser_view_renderer_.SetIsPaused(paused);
867 ContentViewCore* cvc =
868 ContentViewCore::FromWebContents(web_contents_.get());
869 if (cvc) {
870 cvc->PauseOrResumeGeolocation(paused);
871 if (paused) {
872 cvc->PauseVideo();
877 void AwContents::OnAttachedToWindow(JNIEnv* env, jobject obj, int w, int h) {
878 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
879 browser_view_renderer_.OnAttachedToWindow(w, h);
882 void AwContents::InitializeHardwareDrawIfNeeded() {
883 GLViewRendererManager* manager = GLViewRendererManager::GetInstance();
885 base::AutoLock lock(render_thread_lock_);
886 if (renderer_manager_key_ == manager->NullKey()) {
887 renderer_manager_key_ = manager->PushBack(&shared_renderer_state_);
888 DeferredGpuCommandService::SetInstance();
892 void AwContents::OnDetachedFromWindow(JNIEnv* env, jobject obj) {
893 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
894 ReleaseHardwareDrawIfNeeded();
895 browser_view_renderer_.OnDetachedFromWindow();
898 void AwContents::ReleaseHardwareDrawIfNeeded() {
899 InsideHardwareReleaseReset inside_reset(&shared_renderer_state_);
901 bool hardware_initialized = browser_view_renderer_.hardware_enabled();
902 if (hardware_initialized) {
903 bool draw_functor_succeeded = RequestDrawGL(NULL, true);
904 if (!draw_functor_succeeded) {
905 LOG(ERROR) << "Unable to free GL resources. Has the Window leaked?";
906 // Calling release on wrong thread intentionally.
907 AwDrawGLInfo info;
908 info.mode = AwDrawGLInfo::kModeProcess;
909 DrawGL(&info);
911 browser_view_renderer_.ReleaseHardware();
913 DCHECK(!hardware_renderer_);
915 GLViewRendererManager* manager = GLViewRendererManager::GetInstance();
918 base::AutoLock lock(render_thread_lock_);
919 if (renderer_manager_key_ != manager->NullKey()) {
920 manager->Remove(renderer_manager_key_);
921 renderer_manager_key_ = manager->NullKey();
925 if (hardware_initialized) {
926 // Flush any invoke functors that's caused by OnDetachedFromWindow.
927 RequestDrawGL(NULL, true);
931 base::android::ScopedJavaLocalRef<jbyteArray>
932 AwContents::GetOpaqueState(JNIEnv* env, jobject obj) {
933 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
934 // Required optimization in WebViewClassic to not save any state if
935 // there has been no navigations.
936 if (!web_contents_->GetController().GetEntryCount())
937 return ScopedJavaLocalRef<jbyteArray>();
939 Pickle pickle;
940 if (!WriteToPickle(*web_contents_, &pickle)) {
941 return ScopedJavaLocalRef<jbyteArray>();
942 } else {
943 return base::android::ToJavaByteArray(env,
944 reinterpret_cast<const uint8*>(pickle.data()), pickle.size());
948 jboolean AwContents::RestoreFromOpaqueState(
949 JNIEnv* env, jobject obj, jbyteArray state) {
950 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
951 // TODO(boliu): This copy can be optimized out if this is a performance
952 // problem.
953 std::vector<uint8> state_vector;
954 base::android::JavaByteArrayToByteVector(env, state, &state_vector);
956 Pickle pickle(reinterpret_cast<const char*>(state_vector.begin()),
957 state_vector.size());
958 PickleIterator iterator(pickle);
960 return RestoreFromPickle(&iterator, web_contents_.get());
963 bool AwContents::OnDraw(JNIEnv* env,
964 jobject obj,
965 jobject canvas,
966 jboolean is_hardware_accelerated,
967 jint scroll_x,
968 jint scroll_y,
969 jint visible_left,
970 jint visible_top,
971 jint visible_right,
972 jint visible_bottom) {
973 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
974 if (is_hardware_accelerated)
975 InitializeHardwareDrawIfNeeded();
976 return browser_view_renderer_.OnDraw(
977 canvas,
978 is_hardware_accelerated,
979 gfx::Vector2d(scroll_x, scroll_y),
980 gfx::Rect(visible_left,
981 visible_top,
982 visible_right - visible_left,
983 visible_bottom - visible_top));
986 void AwContents::SetPendingWebContentsForPopup(
987 scoped_ptr<content::WebContents> pending) {
988 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
989 if (pending_contents_.get()) {
990 // TODO(benm): Support holding multiple pop up window requests.
991 LOG(WARNING) << "Blocking popup window creation as an outstanding "
992 << "popup window is still pending.";
993 base::MessageLoop::current()->DeleteSoon(FROM_HERE, pending.release());
994 return;
996 pending_contents_.reset(new AwContents(pending.Pass()));
999 void AwContents::FocusFirstNode(JNIEnv* env, jobject obj) {
1000 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1001 web_contents_->FocusThroughTabTraversal(false);
1004 void AwContents::SetBackgroundColor(JNIEnv* env, jobject obj, jint color) {
1005 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1006 render_view_host_ext_->SetBackgroundColor(color);
1009 jlong AwContents::ReleasePopupAwContents(JNIEnv* env, jobject obj) {
1010 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1011 return reinterpret_cast<intptr_t>(pending_contents_.release());
1014 gfx::Point AwContents::GetLocationOnScreen() {
1015 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1016 JNIEnv* env = AttachCurrentThread();
1017 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
1018 if (obj.is_null())
1019 return gfx::Point();
1020 std::vector<int> location;
1021 base::android::JavaIntArrayToIntVector(
1022 env,
1023 Java_AwContents_getLocationOnScreen(env, obj.obj()).obj(),
1024 &location);
1025 return gfx::Point(location[0], location[1]);
1028 void AwContents::ScrollContainerViewTo(gfx::Vector2d new_value) {
1029 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1030 JNIEnv* env = AttachCurrentThread();
1031 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
1032 if (obj.is_null())
1033 return;
1034 Java_AwContents_scrollContainerViewTo(
1035 env, obj.obj(), new_value.x(), new_value.y());
1038 bool AwContents::IsFlingActive() const {
1039 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1040 JNIEnv* env = AttachCurrentThread();
1041 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
1042 if (obj.is_null())
1043 return false;
1044 return Java_AwContents_isFlingActive(env, obj.obj());
1047 void AwContents::UpdateScrollState(gfx::Vector2d max_scroll_offset,
1048 gfx::SizeF contents_size_dip,
1049 float page_scale_factor,
1050 float min_page_scale_factor,
1051 float max_page_scale_factor) {
1052 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1053 JNIEnv* env = AttachCurrentThread();
1054 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
1055 if (obj.is_null())
1056 return;
1057 Java_AwContents_updateScrollState(env,
1058 obj.obj(),
1059 max_scroll_offset.x(),
1060 max_scroll_offset.y(),
1061 contents_size_dip.width(),
1062 contents_size_dip.height(),
1063 page_scale_factor,
1064 min_page_scale_factor,
1065 max_page_scale_factor);
1068 void AwContents::DidOverscroll(gfx::Vector2d overscroll_delta) {
1069 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1070 JNIEnv* env = AttachCurrentThread();
1071 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
1072 if (obj.is_null())
1073 return;
1074 Java_AwContents_didOverscroll(
1075 env, obj.obj(), overscroll_delta.x(), overscroll_delta.y());
1078 const BrowserViewRenderer* AwContents::GetBrowserViewRenderer() const {
1079 return &browser_view_renderer_;
1082 void AwContents::SetDipScale(JNIEnv* env, jobject obj, jfloat dip_scale) {
1083 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1084 browser_view_renderer_.SetDipScale(dip_scale);
1087 void AwContents::ScrollTo(JNIEnv* env, jobject obj, jint x, jint y) {
1088 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1089 browser_view_renderer_.ScrollTo(gfx::Vector2d(x, y));
1092 void AwContents::OnWebLayoutPageScaleFactorChanged(float page_scale_factor) {
1093 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1094 JNIEnv* env = AttachCurrentThread();
1095 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
1096 if (obj.is_null())
1097 return;
1098 Java_AwContents_onWebLayoutPageScaleFactorChanged(env, obj.obj(),
1099 page_scale_factor);
1102 void AwContents::OnWebLayoutContentsSizeChanged(
1103 const gfx::Size& contents_size) {
1104 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1105 JNIEnv* env = AttachCurrentThread();
1106 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
1107 if (obj.is_null())
1108 return;
1109 Java_AwContents_onWebLayoutContentsSizeChanged(
1110 env, obj.obj(), contents_size.width(), contents_size.height());
1113 jlong AwContents::CapturePicture(JNIEnv* env,
1114 jobject obj,
1115 int width,
1116 int height) {
1117 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1118 return reinterpret_cast<intptr_t>(
1119 new AwPicture(browser_view_renderer_.CapturePicture(width, height)));
1122 void AwContents::EnableOnNewPicture(JNIEnv* env,
1123 jobject obj,
1124 jboolean enabled) {
1125 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1126 browser_view_renderer_.EnableOnNewPicture(enabled);
1129 void AwContents::ClearView(JNIEnv* env, jobject obj) {
1130 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1131 browser_view_renderer_.ClearView();
1134 void AwContents::SetExtraHeadersForUrl(JNIEnv* env, jobject obj,
1135 jstring url, jstring jextra_headers) {
1136 std::string extra_headers;
1137 if (jextra_headers)
1138 extra_headers = ConvertJavaStringToUTF8(env, jextra_headers);
1139 AwResourceContext* resource_context = static_cast<AwResourceContext*>(
1140 AwBrowserContext::FromWebContents(web_contents_.get())->
1141 GetResourceContext());
1142 resource_context->SetExtraHeaders(GURL(ConvertJavaStringToUTF8(env, url)),
1143 extra_headers);
1146 void AwContents::SendCheckRenderThreadResponsiveness(JNIEnv* env, jobject obj) {
1147 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1148 render_view_host_ext_->SendCheckRenderThreadResponsiveness();
1151 void AwContents::SetJsOnlineProperty(JNIEnv* env,
1152 jobject obj,
1153 jboolean network_up) {
1154 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1155 render_view_host_ext_->SetJsOnlineProperty(network_up);
1158 void AwContents::TrimMemory(JNIEnv* env,
1159 jobject obj,
1160 jint level,
1161 jboolean visible) {
1162 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1163 enum {
1164 TRIM_MEMORY_MODERATE = 60,
1166 if (level >= TRIM_MEMORY_MODERATE) {
1167 ReleaseHardwareDrawIfNeeded();
1168 return;
1171 browser_view_renderer_.TrimMemory(level, visible);
1174 void SetShouldDownloadFavicons(JNIEnv* env, jclass jclazz) {
1175 g_should_download_favicons = true;
1178 } // namespace android_webview