Mime sniffer: reduce table from 256 bytes to 4
[chromium-blink-merge.git] / android_webview / native / aw_contents.cc
blobcc65cd7a3fa094106181e48da69d96678c93d6e3
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/net_disk_cache_remover.h"
15 #include "android_webview/browser/renderer_host/aw_resource_dispatcher_host_delegate.h"
16 #include "android_webview/browser/scoped_app_gl_state_restore.h"
17 #include "android_webview/browser/shared_renderer_state.h"
18 #include "android_webview/common/aw_hit_test_data.h"
19 #include "android_webview/common/devtools_instrumentation.h"
20 #include "android_webview/native/aw_autofill_client.h"
21 #include "android_webview/native/aw_browser_dependency_factory.h"
22 #include "android_webview/native/aw_contents_client_bridge.h"
23 #include "android_webview/native/aw_contents_io_thread_client_impl.h"
24 #include "android_webview/native/aw_message_port_service_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/locale_utils.h"
38 #include "base/android/scoped_java_ref.h"
39 #include "base/atomicops.h"
40 #include "base/bind.h"
41 #include "base/callback.h"
42 #include "base/memory/memory_pressure_listener.h"
43 #include "base/message_loop/message_loop.h"
44 #include "base/pickle.h"
45 #include "base/strings/string16.h"
46 #include "base/supports_user_data.h"
47 #include "components/autofill/content/browser/content_autofill_driver_factory.h"
48 #include "components/autofill/core/browser/autofill_manager.h"
49 #include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
50 #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_settings.h"
51 #include "components/navigation_interception/intercept_navigation_delegate.h"
52 #include "content/public/browser/android/content_view_core.h"
53 #include "content/public/browser/android/synchronous_compositor.h"
54 #include "content/public/browser/browser_thread.h"
55 #include "content/public/browser/cert_store.h"
56 #include "content/public/browser/favicon_status.h"
57 #include "content/public/browser/message_port_provider.h"
58 #include "content/public/browser/navigation_entry.h"
59 #include "content/public/browser/render_frame_host.h"
60 #include "content/public/browser/render_process_host.h"
61 #include "content/public/browser/render_view_host.h"
62 #include "content/public/browser/web_contents.h"
63 #include "content/public/common/message_port_types.h"
64 #include "content/public/common/renderer_preferences.h"
65 #include "content/public/common/ssl_status.h"
66 #include "jni/AwContents_jni.h"
67 #include "net/base/auth.h"
68 #include "net/cert/x509_certificate.h"
69 #include "third_party/skia/include/core/SkPicture.h"
70 #include "ui/gfx/android/java_bitmap.h"
71 #include "ui/gfx/geometry/rect_f.h"
72 #include "ui/gfx/geometry/size.h"
73 #include "ui/gfx/image/image.h"
75 struct AwDrawSWFunctionTable;
77 using autofill::ContentAutofillDriverFactory;
78 using autofill::AutofillManager;
79 using base::android::AttachCurrentThread;
80 using base::android::ConvertJavaStringToUTF16;
81 using base::android::ConvertJavaStringToUTF8;
82 using base::android::ConvertUTF16ToJavaString;
83 using base::android::ConvertUTF8ToJavaString;
84 using base::android::JavaRef;
85 using base::android::ScopedJavaGlobalRef;
86 using base::android::ScopedJavaLocalRef;
87 using data_reduction_proxy::DataReductionProxySettings;
88 using navigation_interception::InterceptNavigationDelegate;
89 using content::BrowserThread;
90 using content::ContentViewCore;
91 using content::WebContents;
93 extern "C" {
94 static AwDrawGLFunction DrawGLFunction;
95 static void DrawGLFunction(long view_context,
96 AwDrawGLInfo* draw_info,
97 void* spare) {
98 // |view_context| is the value that was returned from the java
99 // AwContents.onPrepareDrawGL; this cast must match the code there.
100 reinterpret_cast<android_webview::SharedRendererState*>(view_context)
101 ->DrawGL(draw_info);
105 namespace android_webview {
107 namespace {
109 bool g_should_download_favicons = false;
111 const void* kAwContentsUserDataKey = &kAwContentsUserDataKey;
113 class AwContentsUserData : public base::SupportsUserData::Data {
114 public:
115 AwContentsUserData(AwContents* ptr) : contents_(ptr) {}
117 static AwContents* GetContents(WebContents* web_contents) {
118 if (!web_contents)
119 return NULL;
120 AwContentsUserData* data = static_cast<AwContentsUserData*>(
121 web_contents->GetUserData(kAwContentsUserDataKey));
122 return data ? data->contents_ : NULL;
125 private:
126 AwContents* contents_;
129 base::subtle::Atomic32 g_instance_count = 0;
131 void OnIoThreadClientReady(content::RenderFrameHost* rfh) {
132 int render_process_id = rfh->GetProcess()->GetID();
133 int render_frame_id = rfh->GetRoutingID();
134 AwResourceDispatcherHostDelegate::OnIoThreadClientReady(
135 render_process_id, render_frame_id);
138 } // namespace
140 // static
141 AwContents* AwContents::FromWebContents(WebContents* web_contents) {
142 DCHECK_CURRENTLY_ON(BrowserThread::UI);
143 return AwContentsUserData::GetContents(web_contents);
146 // static
147 AwContents* AwContents::FromID(int render_process_id, int render_view_id) {
148 const content::RenderViewHost* rvh =
149 content::RenderViewHost::FromID(render_process_id, render_view_id);
150 if (!rvh) return NULL;
151 content::WebContents* web_contents =
152 content::WebContents::FromRenderViewHost(rvh);
153 if (!web_contents) return NULL;
154 return FromWebContents(web_contents);
157 // static
158 AwBrowserPermissionRequestDelegate* AwBrowserPermissionRequestDelegate::FromID(
159 int render_process_id, int render_view_id) {
160 AwContents* aw_contents = AwContents::FromID(render_process_id,
161 render_view_id);
162 return implicit_cast<AwBrowserPermissionRequestDelegate*>(aw_contents);
165 AwContents::AwContents(scoped_ptr<WebContents> web_contents)
166 : web_contents_(web_contents.Pass()),
167 browser_view_renderer_(
168 this,
169 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI)),
170 renderer_manager_key_(GLViewRendererManager::GetInstance()->NullKey()) {
171 base::subtle::NoBarrier_AtomicIncrement(&g_instance_count, 1);
172 icon_helper_.reset(new IconHelper(web_contents_.get()));
173 icon_helper_->SetListener(this);
174 web_contents_->SetUserData(android_webview::kAwContentsUserDataKey,
175 new AwContentsUserData(this));
176 browser_view_renderer_.RegisterWithWebContents(web_contents_.get());
177 render_view_host_ext_.reset(
178 new AwRenderViewHostExt(this, web_contents_.get()));
180 permission_request_handler_.reset(
181 new PermissionRequestHandler(this, web_contents_.get()));
183 AwAutofillClient* autofill_manager_delegate =
184 AwAutofillClient::FromWebContents(web_contents_.get());
185 InitDataReductionProxyIfNecessary();
186 if (autofill_manager_delegate)
187 InitAutofillIfNecessary(autofill_manager_delegate->GetSaveFormData());
188 content::SynchronousCompositor::SetClientForWebContents(
189 web_contents_.get(), &browser_view_renderer_);
192 void AwContents::SetJavaPeers(JNIEnv* env,
193 jobject obj,
194 jobject aw_contents,
195 jobject web_contents_delegate,
196 jobject contents_client_bridge,
197 jobject io_thread_client,
198 jobject intercept_navigation_delegate) {
199 DCHECK_CURRENTLY_ON(BrowserThread::UI);
200 // The |aw_content| param is technically spurious as it duplicates |obj| but
201 // is passed over anyway to make the binding more explicit.
202 java_ref_ = JavaObjectWeakGlobalRef(env, aw_contents);
204 web_contents_delegate_.reset(
205 new AwWebContentsDelegate(env, web_contents_delegate));
206 web_contents_->SetDelegate(web_contents_delegate_.get());
208 contents_client_bridge_.reset(
209 new AwContentsClientBridge(env, contents_client_bridge));
210 AwContentsClientBridgeBase::Associate(web_contents_.get(),
211 contents_client_bridge_.get());
213 AwContentsIoThreadClientImpl::Associate(
214 web_contents_.get(), ScopedJavaLocalRef<jobject>(env, io_thread_client));
216 InterceptNavigationDelegate::Associate(
217 web_contents_.get(),
218 make_scoped_ptr(new InterceptNavigationDelegate(
219 env, intercept_navigation_delegate)));
221 // Finally, having setup the associations, release any deferred requests
222 web_contents_->ForEachFrame(base::Bind(&OnIoThreadClientReady));
225 void AwContents::SetSaveFormData(bool enabled) {
226 DCHECK_CURRENTLY_ON(BrowserThread::UI);
227 InitAutofillIfNecessary(enabled);
228 // We need to check for the existence, since autofill_manager_delegate
229 // may not be created when the setting is false.
230 if (AwAutofillClient::FromWebContents(web_contents_.get())) {
231 AwAutofillClient::FromWebContents(web_contents_.get())->
232 SetSaveFormData(enabled);
236 void AwContents::InitDataReductionProxyIfNecessary() {
237 AwBrowserContext* browser_context =
238 AwBrowserContext::FromWebContents(web_contents_.get());
239 browser_context->CreateUserPrefServiceIfNecessary();
242 void AwContents::InitAutofillIfNecessary(bool enabled) {
243 // Do not initialize if the feature is not enabled.
244 if (!enabled)
245 return;
246 // Check if the autofill driver factory already exists.
247 content::WebContents* web_contents = web_contents_.get();
248 if (ContentAutofillDriverFactory::FromWebContents(web_contents))
249 return;
251 AwBrowserContext::FromWebContents(web_contents)->
252 CreateUserPrefServiceIfNecessary();
253 AwAutofillClient::CreateForWebContents(web_contents);
254 ContentAutofillDriverFactory::CreateForWebContentsAndDelegate(
255 web_contents, AwAutofillClient::FromWebContents(web_contents),
256 base::android::GetDefaultLocale(),
257 AutofillManager::DISABLE_AUTOFILL_DOWNLOAD_MANAGER);
260 void AwContents::SetAwAutofillClient(jobject client) {
261 DCHECK_CURRENTLY_ON(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_EQ(this, AwContents::FromWebContents(web_contents_.get()));
271 content::SynchronousCompositor::SetClientForWebContents(web_contents_.get(),
272 NULL);
273 web_contents_->RemoveUserData(kAwContentsUserDataKey);
274 if (find_helper_.get())
275 find_helper_->SetListener(NULL);
276 if (icon_helper_.get())
277 icon_helper_->SetListener(NULL);
278 base::subtle::NoBarrier_AtomicIncrement(&g_instance_count, -1);
279 // When the last WebView is destroyed free all discardable memory allocated by
280 // Chromium, because the app process may continue to run for a long time
281 // without ever using another WebView.
282 if (base::subtle::NoBarrier_Load(&g_instance_count) == 0) {
283 base::MemoryPressureListener::NotifyMemoryPressure(
284 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL);
288 base::android::ScopedJavaLocalRef<jobject>
289 AwContents::GetWebContents(JNIEnv* env, jobject obj) {
290 DCHECK_CURRENTLY_ON(BrowserThread::UI);
291 DCHECK(web_contents_);
292 if (!web_contents_)
293 return base::android::ScopedJavaLocalRef<jobject>();
295 return web_contents_->GetJavaWebContents();
298 void AwContents::Destroy(JNIEnv* env, jobject obj) {
299 java_ref_.reset();
300 delete this;
303 static jlong Init(JNIEnv* env, jclass, jobject browser_context) {
304 // TODO(joth): Use |browser_context| to get the native BrowserContext, rather
305 // than hard-code the default instance lookup here.
306 scoped_ptr<WebContents> web_contents(content::WebContents::Create(
307 content::WebContents::CreateParams(AwBrowserContext::GetDefault())));
308 // Return an 'uninitialized' instance; most work is deferred until the
309 // subsequent SetJavaPeers() call.
310 return reinterpret_cast<intptr_t>(new AwContents(web_contents.Pass()));
313 static void SetAwDrawSWFunctionTable(JNIEnv* env, jclass,
314 jlong function_table) {
315 RasterHelperSetAwDrawSWFunctionTable(
316 reinterpret_cast<AwDrawSWFunctionTable*>(function_table));
319 static void SetAwDrawGLFunctionTable(JNIEnv* env, jclass,
320 jlong function_table) {
323 static jlong GetAwDrawGLFunction(JNIEnv* env, jclass) {
324 return reinterpret_cast<intptr_t>(&DrawGLFunction);
327 // static
328 jint GetNativeInstanceCount(JNIEnv* env, jclass) {
329 return base::subtle::NoBarrier_Load(&g_instance_count);
332 jlong AwContents::GetAwDrawGLViewContext(JNIEnv* env, jobject obj) {
333 DCHECK_CURRENTLY_ON(BrowserThread::UI);
334 return reinterpret_cast<intptr_t>(
335 browser_view_renderer_.GetAwDrawGLViewContext());
338 namespace {
339 void DocumentHasImagesCallback(const ScopedJavaGlobalRef<jobject>& message,
340 bool has_images) {
341 Java_AwContents_onDocumentHasImagesResponse(AttachCurrentThread(),
342 has_images,
343 message.obj());
345 } // namespace
347 void AwContents::DocumentHasImages(JNIEnv* env, jobject obj, jobject message) {
348 DCHECK_CURRENTLY_ON(BrowserThread::UI);
349 ScopedJavaGlobalRef<jobject> j_message;
350 j_message.Reset(env, message);
351 render_view_host_ext_->DocumentHasImages(
352 base::Bind(&DocumentHasImagesCallback, j_message));
355 namespace {
356 void GenerateMHTMLCallback(ScopedJavaGlobalRef<jobject>* callback,
357 const base::FilePath& path, int64 size) {
358 JNIEnv* env = AttachCurrentThread();
359 // Android files are UTF8, so the path conversion below is safe.
360 Java_AwContents_generateMHTMLCallback(
361 env,
362 ConvertUTF8ToJavaString(env, path.AsUTF8Unsafe()).obj(),
363 size, callback->obj());
365 } // namespace
367 void AwContents::GenerateMHTML(JNIEnv* env, jobject obj,
368 jstring jpath, jobject callback) {
369 DCHECK_CURRENTLY_ON(BrowserThread::UI);
370 ScopedJavaGlobalRef<jobject>* j_callback = new ScopedJavaGlobalRef<jobject>();
371 j_callback->Reset(env, callback);
372 base::FilePath target_path(ConvertJavaStringToUTF8(env, jpath));
373 web_contents_->GenerateMHTML(
374 target_path,
375 base::Bind(&GenerateMHTMLCallback, base::Owned(j_callback), target_path));
378 void AwContents::CreatePdfExporter(JNIEnv* env,
379 jobject obj,
380 jobject pdfExporter) {
381 pdf_exporter_.reset(
382 new AwPdfExporter(env,
383 pdfExporter,
384 web_contents_.get()));
387 bool AwContents::OnReceivedHttpAuthRequest(const JavaRef<jobject>& handler,
388 const std::string& host,
389 const std::string& realm) {
390 DCHECK_CURRENTLY_ON(BrowserThread::UI);
391 JNIEnv* env = AttachCurrentThread();
392 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
393 if (obj.is_null())
394 return false;
396 ScopedJavaLocalRef<jstring> jhost = ConvertUTF8ToJavaString(env, host);
397 ScopedJavaLocalRef<jstring> jrealm = ConvertUTF8ToJavaString(env, realm);
398 devtools_instrumentation::ScopedEmbedderCallbackTask embedder_callback(
399 "onReceivedHttpAuthRequest");
400 Java_AwContents_onReceivedHttpAuthRequest(env, obj.obj(), handler.obj(),
401 jhost.obj(), jrealm.obj());
402 return true;
405 void AwContents::SetOffscreenPreRaster(bool enabled) {
406 DCHECK_CURRENTLY_ON(BrowserThread::UI);
407 browser_view_renderer_.SetOffscreenPreRaster(enabled);
410 void AwContents::AddVisitedLinks(JNIEnv* env,
411 jobject obj,
412 jobjectArray jvisited_links) {
413 DCHECK_CURRENTLY_ON(BrowserThread::UI);
414 std::vector<base::string16> visited_link_strings;
415 base::android::AppendJavaStringArrayToStringVector(
416 env, jvisited_links, &visited_link_strings);
418 std::vector<GURL> visited_link_gurls;
419 std::vector<base::string16>::const_iterator itr;
420 for (itr = visited_link_strings.begin(); itr != visited_link_strings.end();
421 ++itr) {
422 visited_link_gurls.push_back(GURL(*itr));
425 AwBrowserContext::FromWebContents(web_contents_.get())
426 ->AddVisitedURLs(visited_link_gurls);
429 bool RegisterAwContents(JNIEnv* env) {
430 return RegisterNativesImpl(env);
433 namespace {
435 void ShowGeolocationPromptHelperTask(const JavaObjectWeakGlobalRef& java_ref,
436 const GURL& origin) {
437 JNIEnv* env = AttachCurrentThread();
438 ScopedJavaLocalRef<jobject> j_ref = java_ref.get(env);
439 if (j_ref.obj()) {
440 ScopedJavaLocalRef<jstring> j_origin(
441 ConvertUTF8ToJavaString(env, origin.spec()));
442 devtools_instrumentation::ScopedEmbedderCallbackTask embedder_callback(
443 "onGeolocationPermissionsShowPrompt");
444 Java_AwContents_onGeolocationPermissionsShowPrompt(env,
445 j_ref.obj(),
446 j_origin.obj());
450 void ShowGeolocationPromptHelper(const JavaObjectWeakGlobalRef& java_ref,
451 const GURL& origin) {
452 JNIEnv* env = AttachCurrentThread();
453 if (java_ref.get(env).obj()) {
454 content::BrowserThread::PostTask(
455 content::BrowserThread::UI,
456 FROM_HERE,
457 base::Bind(&ShowGeolocationPromptHelperTask,
458 java_ref,
459 origin));
463 } // anonymous namespace
465 void AwContents::ShowGeolocationPrompt(const GURL& requesting_frame,
466 base::Callback<void(bool)> callback) {
467 DCHECK_CURRENTLY_ON(BrowserThread::UI);
469 GURL origin = requesting_frame.GetOrigin();
470 bool show_prompt = pending_geolocation_prompts_.empty();
471 pending_geolocation_prompts_.push_back(OriginCallback(origin, callback));
472 if (show_prompt) {
473 ShowGeolocationPromptHelper(java_ref_, origin);
477 // Invoked from Java
478 void AwContents::InvokeGeolocationCallback(JNIEnv* env,
479 jobject obj,
480 jboolean value,
481 jstring origin) {
482 DCHECK_CURRENTLY_ON(BrowserThread::UI);
484 GURL callback_origin(base::android::ConvertJavaStringToUTF16(env, origin));
485 if (callback_origin.GetOrigin() ==
486 pending_geolocation_prompts_.front().first) {
487 pending_geolocation_prompts_.front().second.Run(value);
488 pending_geolocation_prompts_.pop_front();
489 if (!pending_geolocation_prompts_.empty()) {
490 ShowGeolocationPromptHelper(java_ref_,
491 pending_geolocation_prompts_.front().first);
496 void AwContents::HideGeolocationPrompt(const GURL& origin) {
497 DCHECK_CURRENTLY_ON(BrowserThread::UI);
498 bool removed_current_outstanding_callback = false;
499 std::list<OriginCallback>::iterator it = pending_geolocation_prompts_.begin();
500 while (it != pending_geolocation_prompts_.end()) {
501 if ((*it).first == origin.GetOrigin()) {
502 if (it == pending_geolocation_prompts_.begin()) {
503 removed_current_outstanding_callback = true;
505 it = pending_geolocation_prompts_.erase(it);
506 } else {
507 ++it;
511 if (removed_current_outstanding_callback) {
512 JNIEnv* env = AttachCurrentThread();
513 ScopedJavaLocalRef<jobject> j_ref = java_ref_.get(env);
514 if (j_ref.obj()) {
515 devtools_instrumentation::ScopedEmbedderCallbackTask embedder_callback(
516 "onGeolocationPermissionsHidePrompt");
517 Java_AwContents_onGeolocationPermissionsHidePrompt(env, j_ref.obj());
519 if (!pending_geolocation_prompts_.empty()) {
520 ShowGeolocationPromptHelper(java_ref_,
521 pending_geolocation_prompts_.front().first);
526 void AwContents::OnPermissionRequest(
527 base::android::ScopedJavaLocalRef<jobject> j_request,
528 AwPermissionRequest* request) {
529 DCHECK(!j_request.is_null());
530 DCHECK(request);
532 JNIEnv* env = AttachCurrentThread();
533 ScopedJavaLocalRef<jobject> j_ref = java_ref_.get(env);
534 if (j_ref.is_null()) {
535 permission_request_handler_->CancelRequest(request->GetOrigin(),
536 request->GetResources());
537 return;
540 Java_AwContents_onPermissionRequest(env, j_ref.obj(), j_request.obj());
543 void AwContents::OnPermissionRequestCanceled(AwPermissionRequest* request) {
544 JNIEnv* env = AttachCurrentThread();
545 ScopedJavaLocalRef<jobject> j_request = request->GetJavaObject();
546 ScopedJavaLocalRef<jobject> j_ref = java_ref_.get(env);
547 if (j_request.is_null() || j_ref.is_null())
548 return;
550 Java_AwContents_onPermissionRequestCanceled(
551 env, j_ref.obj(), j_request.obj());
554 void AwContents::PreauthorizePermission(
555 JNIEnv* env,
556 jobject obj,
557 jstring origin,
558 jlong resources) {
559 permission_request_handler_->PreauthorizePermission(
560 GURL(base::android::ConvertJavaStringToUTF8(env, origin)), resources);
563 void AwContents::RequestProtectedMediaIdentifierPermission(
564 const GURL& origin,
565 const base::Callback<void(bool)>& callback) {
566 permission_request_handler_->SendRequest(
567 scoped_ptr<AwPermissionRequestDelegate>(new SimplePermissionRequest(
568 origin, AwPermissionRequest::ProtectedMediaId, callback)));
571 void AwContents::CancelProtectedMediaIdentifierPermissionRequests(
572 const GURL& origin) {
573 permission_request_handler_->CancelRequest(
574 origin, AwPermissionRequest::ProtectedMediaId);
577 void AwContents::RequestGeolocationPermission(
578 const GURL& origin,
579 const base::Callback<void(bool)>& callback) {
580 JNIEnv* env = AttachCurrentThread();
581 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
582 if (obj.is_null())
583 return;
585 if (Java_AwContents_useLegacyGeolocationPermissionAPI(env, obj.obj())) {
586 ShowGeolocationPrompt(origin, callback);
587 return;
589 permission_request_handler_->SendRequest(
590 scoped_ptr<AwPermissionRequestDelegate>(new SimplePermissionRequest(
591 origin, AwPermissionRequest::Geolocation, callback)));
594 void AwContents::CancelGeolocationPermissionRequests(const GURL& origin) {
595 JNIEnv* env = AttachCurrentThread();
596 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
597 if (obj.is_null())
598 return;
600 if (Java_AwContents_useLegacyGeolocationPermissionAPI(env, obj.obj())) {
601 HideGeolocationPrompt(origin);
602 return;
604 permission_request_handler_->CancelRequest(
605 origin, AwPermissionRequest::Geolocation);
608 void AwContents::FindAllAsync(JNIEnv* env, jobject obj, jstring search_string) {
609 DCHECK_CURRENTLY_ON(BrowserThread::UI);
610 GetFindHelper()->FindAllAsync(ConvertJavaStringToUTF16(env, search_string));
613 void AwContents::FindNext(JNIEnv* env, jobject obj, jboolean forward) {
614 DCHECK_CURRENTLY_ON(BrowserThread::UI);
615 GetFindHelper()->FindNext(forward);
618 void AwContents::ClearMatches(JNIEnv* env, jobject obj) {
619 DCHECK_CURRENTLY_ON(BrowserThread::UI);
620 GetFindHelper()->ClearMatches();
623 void AwContents::ClearCache(
624 JNIEnv* env,
625 jobject obj,
626 jboolean include_disk_files) {
627 DCHECK_CURRENTLY_ON(BrowserThread::UI);
628 render_view_host_ext_->ClearCache();
630 if (include_disk_files) {
631 RemoveHttpDiskCache(web_contents_->GetBrowserContext(),
632 web_contents_->GetRoutingID());
636 FindHelper* AwContents::GetFindHelper() {
637 DCHECK_CURRENTLY_ON(BrowserThread::UI);
638 if (!find_helper_.get()) {
639 find_helper_.reset(new FindHelper(web_contents_.get()));
640 find_helper_->SetListener(this);
642 return find_helper_.get();
645 void AwContents::OnFindResultReceived(int active_ordinal,
646 int match_count,
647 bool finished) {
648 DCHECK_CURRENTLY_ON(BrowserThread::UI);
649 JNIEnv* env = AttachCurrentThread();
650 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
651 if (obj.is_null())
652 return;
654 Java_AwContents_onFindResultReceived(
655 env, obj.obj(), active_ordinal, match_count, finished);
658 bool AwContents::ShouldDownloadFavicon(const GURL& icon_url) {
659 return g_should_download_favicons;
662 void AwContents::OnReceivedIcon(const GURL& icon_url, const SkBitmap& bitmap) {
663 DCHECK_CURRENTLY_ON(BrowserThread::UI);
664 JNIEnv* env = AttachCurrentThread();
665 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
666 if (obj.is_null())
667 return;
669 content::NavigationEntry* entry =
670 web_contents_->GetController().GetActiveEntry();
672 if (entry) {
673 entry->GetFavicon().valid = true;
674 entry->GetFavicon().url = icon_url;
675 entry->GetFavicon().image = gfx::Image::CreateFrom1xBitmap(bitmap);
678 Java_AwContents_onReceivedIcon(
679 env, obj.obj(), gfx::ConvertToJavaBitmap(&bitmap).obj());
682 void AwContents::OnReceivedTouchIconUrl(const std::string& url,
683 bool precomposed) {
684 DCHECK_CURRENTLY_ON(BrowserThread::UI);
685 JNIEnv* env = AttachCurrentThread();
686 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
687 if (obj.is_null())
688 return;
690 Java_AwContents_onReceivedTouchIconUrl(
691 env, obj.obj(), ConvertUTF8ToJavaString(env, url).obj(), precomposed);
694 bool AwContents::RequestDrawGL(bool wait_for_completion) {
695 DCHECK_CURRENTLY_ON(BrowserThread::UI);
696 JNIEnv* env = AttachCurrentThread();
697 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
698 if (obj.is_null())
699 return false;
700 return Java_AwContents_requestDrawGL(env, obj.obj(), wait_for_completion);
703 void AwContents::PostInvalidate() {
704 DCHECK_CURRENTLY_ON(BrowserThread::UI);
705 JNIEnv* env = AttachCurrentThread();
706 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
707 if (!obj.is_null())
708 Java_AwContents_postInvalidateOnAnimation(env, obj.obj());
711 void AwContents::OnNewPicture() {
712 DCHECK_CURRENTLY_ON(BrowserThread::UI);
713 JNIEnv* env = AttachCurrentThread();
714 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
715 if (!obj.is_null()) {
716 devtools_instrumentation::ScopedEmbedderCallbackTask embedder_callback(
717 "onNewPicture");
718 Java_AwContents_onNewPicture(env, obj.obj());
722 base::android::ScopedJavaLocalRef<jbyteArray>
723 AwContents::GetCertificate(JNIEnv* env,
724 jobject obj) {
725 DCHECK_CURRENTLY_ON(BrowserThread::UI);
726 content::NavigationEntry* entry =
727 web_contents_->GetController().GetActiveEntry();
728 if (!entry)
729 return ScopedJavaLocalRef<jbyteArray>();
730 // Get the certificate
731 int cert_id = entry->GetSSL().cert_id;
732 scoped_refptr<net::X509Certificate> cert;
733 bool ok = content::CertStore::GetInstance()->RetrieveCert(cert_id, &cert);
734 if (!ok)
735 return ScopedJavaLocalRef<jbyteArray>();
737 // Convert the certificate and return it
738 std::string der_string;
739 net::X509Certificate::GetDEREncoded(cert->os_cert_handle(), &der_string);
740 return base::android::ToJavaByteArray(env,
741 reinterpret_cast<const uint8*>(der_string.data()), der_string.length());
744 void AwContents::RequestNewHitTestDataAt(JNIEnv* env,
745 jobject obj,
746 jfloat x,
747 jfloat y,
748 jfloat touch_major) {
749 DCHECK_CURRENTLY_ON(BrowserThread::UI);
750 gfx::PointF touch_center(x, y);
751 gfx::SizeF touch_area(touch_major, touch_major);
752 render_view_host_ext_->RequestNewHitTestDataAt(touch_center, touch_area);
755 void AwContents::UpdateLastHitTestData(JNIEnv* env, jobject obj) {
756 DCHECK_CURRENTLY_ON(BrowserThread::UI);
757 if (!render_view_host_ext_->HasNewHitTestData()) return;
759 const AwHitTestData& data = render_view_host_ext_->GetLastHitTestData();
760 render_view_host_ext_->MarkHitTestDataRead();
762 // Make sure to null the Java object if data is empty/invalid.
763 ScopedJavaLocalRef<jstring> extra_data_for_type;
764 if (data.extra_data_for_type.length())
765 extra_data_for_type = ConvertUTF8ToJavaString(
766 env, data.extra_data_for_type);
768 ScopedJavaLocalRef<jstring> href;
769 if (data.href.length())
770 href = ConvertUTF16ToJavaString(env, data.href);
772 ScopedJavaLocalRef<jstring> anchor_text;
773 if (data.anchor_text.length())
774 anchor_text = ConvertUTF16ToJavaString(env, data.anchor_text);
776 ScopedJavaLocalRef<jstring> img_src;
777 if (data.img_src.is_valid())
778 img_src = ConvertUTF8ToJavaString(env, data.img_src.spec());
780 Java_AwContents_updateHitTestData(env,
781 obj,
782 data.type,
783 extra_data_for_type.obj(),
784 href.obj(),
785 anchor_text.obj(),
786 img_src.obj());
789 void AwContents::OnSizeChanged(JNIEnv* env, jobject obj,
790 int w, int h, int ow, int oh) {
791 DCHECK_CURRENTLY_ON(BrowserThread::UI);
792 browser_view_renderer_.OnSizeChanged(w, h);
795 void AwContents::SetViewVisibility(JNIEnv* env, jobject obj, bool visible) {
796 DCHECK_CURRENTLY_ON(BrowserThread::UI);
797 browser_view_renderer_.SetViewVisibility(visible);
800 void AwContents::SetWindowVisibility(JNIEnv* env, jobject obj, bool visible) {
801 DCHECK_CURRENTLY_ON(BrowserThread::UI);
802 browser_view_renderer_.SetWindowVisibility(visible);
805 void AwContents::SetIsPaused(JNIEnv* env, jobject obj, bool paused) {
806 DCHECK_CURRENTLY_ON(BrowserThread::UI);
807 browser_view_renderer_.SetIsPaused(paused);
808 ContentViewCore* cvc =
809 ContentViewCore::FromWebContents(web_contents_.get());
810 if (cvc) {
811 cvc->PauseOrResumeGeolocation(paused);
815 void AwContents::OnAttachedToWindow(JNIEnv* env, jobject obj, int w, int h) {
816 DCHECK_CURRENTLY_ON(BrowserThread::UI);
817 browser_view_renderer_.OnAttachedToWindow(w, h);
820 void AwContents::OnDetachedFromWindow(JNIEnv* env, jobject obj) {
821 DCHECK_CURRENTLY_ON(BrowserThread::UI);
822 browser_view_renderer_.OnDetachedFromWindow();
825 void AwContents::DetachFunctorFromView() {
826 JNIEnv* env = AttachCurrentThread();
827 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
828 if (!obj.is_null())
829 Java_AwContents_detachFunctorFromView(env, obj.obj());
832 base::android::ScopedJavaLocalRef<jbyteArray>
833 AwContents::GetOpaqueState(JNIEnv* env, jobject obj) {
834 DCHECK_CURRENTLY_ON(BrowserThread::UI);
835 // Required optimization in WebViewClassic to not save any state if
836 // there has been no navigations.
837 if (!web_contents_->GetController().GetEntryCount())
838 return ScopedJavaLocalRef<jbyteArray>();
840 Pickle pickle;
841 if (!WriteToPickle(*web_contents_, &pickle)) {
842 return ScopedJavaLocalRef<jbyteArray>();
843 } else {
844 return base::android::ToJavaByteArray(env,
845 reinterpret_cast<const uint8*>(pickle.data()), pickle.size());
849 jboolean AwContents::RestoreFromOpaqueState(
850 JNIEnv* env, jobject obj, jbyteArray state) {
851 DCHECK_CURRENTLY_ON(BrowserThread::UI);
852 // TODO(boliu): This copy can be optimized out if this is a performance
853 // problem.
854 std::vector<uint8> state_vector;
855 base::android::JavaByteArrayToByteVector(env, state, &state_vector);
857 Pickle pickle(reinterpret_cast<const char*>(state_vector.data()),
858 state_vector.size());
859 PickleIterator iterator(pickle);
861 return RestoreFromPickle(&iterator, web_contents_.get());
864 bool AwContents::OnDraw(JNIEnv* env,
865 jobject obj,
866 jobject canvas,
867 jboolean is_hardware_accelerated,
868 jint scroll_x,
869 jint scroll_y,
870 jint visible_left,
871 jint visible_top,
872 jint visible_right,
873 jint visible_bottom) {
874 DCHECK_CURRENTLY_ON(BrowserThread::UI);
875 gfx::Vector2d scroll(scroll_x, scroll_y);
876 browser_view_renderer_.PrepareToDraw(
877 scroll, gfx::Rect(visible_left, visible_top, visible_right - visible_left,
878 visible_bottom - visible_top));
879 if (is_hardware_accelerated && browser_view_renderer_.attached_to_window()) {
880 return browser_view_renderer_.OnDrawHardware();
883 gfx::Size view_size = browser_view_renderer_.size();
884 if (view_size.IsEmpty()) {
885 TRACE_EVENT_INSTANT0("android_webview", "EarlyOut_EmptySize",
886 TRACE_EVENT_SCOPE_THREAD);
887 return false;
890 // TODO(hush): Right now webview size is passed in as the auxiliary bitmap
891 // size, which might hurt performace (only for software draws with auxiliary
892 // bitmap). For better performance, get global visible rect, transform it
893 // from screen space to view space, then intersect with the webview in
894 // viewspace. Use the resulting rect as the auxiliary bitmap.
895 scoped_ptr<SoftwareCanvasHolder> canvas_holder =
896 SoftwareCanvasHolder::Create(canvas, scroll, view_size);
897 if (!canvas_holder || !canvas_holder->GetCanvas()) {
898 TRACE_EVENT_INSTANT0("android_webview", "EarlyOut_EmptySize",
899 TRACE_EVENT_SCOPE_THREAD);
900 return false;
902 return browser_view_renderer_.OnDrawSoftware(canvas_holder->GetCanvas());
905 void AwContents::SetPendingWebContentsForPopup(
906 scoped_ptr<content::WebContents> pending) {
907 DCHECK_CURRENTLY_ON(BrowserThread::UI);
908 if (pending_contents_.get()) {
909 // TODO(benm): Support holding multiple pop up window requests.
910 LOG(WARNING) << "Blocking popup window creation as an outstanding "
911 << "popup window is still pending.";
912 base::MessageLoop::current()->DeleteSoon(FROM_HERE, pending.release());
913 return;
915 pending_contents_.reset(new AwContents(pending.Pass()));
916 // Set dip_scale for pending contents, which is necessary for the later
917 // SynchronousCompositor and InputHandler setup.
918 pending_contents_->SetDipScaleInternal(browser_view_renderer_.dip_scale());
921 void AwContents::FocusFirstNode(JNIEnv* env, jobject obj) {
922 DCHECK_CURRENTLY_ON(BrowserThread::UI);
923 web_contents_->FocusThroughTabTraversal(false);
926 void AwContents::SetBackgroundColor(JNIEnv* env, jobject obj, jint color) {
927 DCHECK_CURRENTLY_ON(BrowserThread::UI);
928 render_view_host_ext_->SetBackgroundColor(color);
931 jlong AwContents::ReleasePopupAwContents(JNIEnv* env, jobject obj) {
932 DCHECK_CURRENTLY_ON(BrowserThread::UI);
933 return reinterpret_cast<intptr_t>(pending_contents_.release());
936 gfx::Point AwContents::GetLocationOnScreen() {
937 DCHECK_CURRENTLY_ON(BrowserThread::UI);
938 JNIEnv* env = AttachCurrentThread();
939 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
940 if (obj.is_null())
941 return gfx::Point();
942 std::vector<int> location;
943 base::android::JavaIntArrayToIntVector(
944 env,
945 Java_AwContents_getLocationOnScreen(env, obj.obj()).obj(),
946 &location);
947 return gfx::Point(location[0], location[1]);
950 void AwContents::ScrollContainerViewTo(gfx::Vector2d new_value) {
951 DCHECK_CURRENTLY_ON(BrowserThread::UI);
952 JNIEnv* env = AttachCurrentThread();
953 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
954 if (obj.is_null())
955 return;
956 Java_AwContents_scrollContainerViewTo(
957 env, obj.obj(), new_value.x(), new_value.y());
960 bool AwContents::IsFlingActive() const {
961 DCHECK_CURRENTLY_ON(BrowserThread::UI);
962 JNIEnv* env = AttachCurrentThread();
963 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
964 if (obj.is_null())
965 return false;
966 return Java_AwContents_isFlingActive(env, obj.obj());
969 void AwContents::UpdateScrollState(gfx::Vector2d max_scroll_offset,
970 gfx::SizeF contents_size_dip,
971 float page_scale_factor,
972 float min_page_scale_factor,
973 float max_page_scale_factor) {
974 DCHECK_CURRENTLY_ON(BrowserThread::UI);
975 JNIEnv* env = AttachCurrentThread();
976 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
977 if (obj.is_null())
978 return;
979 Java_AwContents_updateScrollState(env,
980 obj.obj(),
981 max_scroll_offset.x(),
982 max_scroll_offset.y(),
983 contents_size_dip.width(),
984 contents_size_dip.height(),
985 page_scale_factor,
986 min_page_scale_factor,
987 max_page_scale_factor);
990 void AwContents::DidOverscroll(gfx::Vector2d overscroll_delta) {
991 DCHECK_CURRENTLY_ON(BrowserThread::UI);
992 JNIEnv* env = AttachCurrentThread();
993 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
994 if (obj.is_null())
995 return;
996 Java_AwContents_didOverscroll(
997 env, obj.obj(), overscroll_delta.x(), overscroll_delta.y());
1000 void AwContents::SetDipScale(JNIEnv* env, jobject obj, jfloat dip_scale) {
1001 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1002 SetDipScaleInternal(dip_scale);
1005 void AwContents::SetDipScaleInternal(float dip_scale) {
1006 browser_view_renderer_.SetDipScale(dip_scale);
1009 void AwContents::ScrollTo(JNIEnv* env, jobject obj, jint x, jint y) {
1010 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1011 browser_view_renderer_.ScrollTo(gfx::Vector2d(x, y));
1014 void AwContents::OnWebLayoutPageScaleFactorChanged(float page_scale_factor) {
1015 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1016 JNIEnv* env = AttachCurrentThread();
1017 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
1018 if (obj.is_null())
1019 return;
1020 Java_AwContents_onWebLayoutPageScaleFactorChanged(env, obj.obj(),
1021 page_scale_factor);
1024 void AwContents::OnWebLayoutContentsSizeChanged(
1025 const gfx::Size& contents_size) {
1026 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1027 JNIEnv* env = AttachCurrentThread();
1028 ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
1029 if (obj.is_null())
1030 return;
1031 Java_AwContents_onWebLayoutContentsSizeChanged(
1032 env, obj.obj(), contents_size.width(), contents_size.height());
1035 jlong AwContents::CapturePicture(JNIEnv* env,
1036 jobject obj,
1037 int width,
1038 int height) {
1039 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1040 return reinterpret_cast<intptr_t>(
1041 new AwPicture(browser_view_renderer_.CapturePicture(width, height)));
1044 void AwContents::EnableOnNewPicture(JNIEnv* env,
1045 jobject obj,
1046 jboolean enabled) {
1047 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1048 browser_view_renderer_.EnableOnNewPicture(enabled);
1051 namespace {
1052 void InvokeVisualStateCallback(const JavaObjectWeakGlobalRef& java_ref,
1053 long request_id,
1054 ScopedJavaGlobalRef<jobject>* callback,
1055 bool result) {
1056 JNIEnv* env = AttachCurrentThread();
1057 ScopedJavaLocalRef<jobject> obj = java_ref.get(env);
1058 if (obj.is_null())
1059 return;
1060 Java_AwContents_invokeVisualStateCallback(
1061 env, obj.obj(), callback->obj(), request_id);
1063 } // namespace
1065 void AwContents::InsertVisualStateCallback(
1066 JNIEnv* env, jobject obj, long request_id, jobject callback) {
1067 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1068 ScopedJavaGlobalRef<jobject>* j_callback = new ScopedJavaGlobalRef<jobject>();
1069 j_callback->Reset(env, callback);
1070 web_contents_->GetMainFrame()->InsertVisualStateCallback(
1071 base::Bind(&InvokeVisualStateCallback, java_ref_, request_id,
1072 base::Owned(j_callback)));
1075 void AwContents::ClearView(JNIEnv* env, jobject obj) {
1076 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1077 browser_view_renderer_.ClearView();
1080 void AwContents::SetExtraHeadersForUrl(JNIEnv* env, jobject obj,
1081 jstring url, jstring jextra_headers) {
1082 std::string extra_headers;
1083 if (jextra_headers)
1084 extra_headers = ConvertJavaStringToUTF8(env, jextra_headers);
1085 AwResourceContext* resource_context = static_cast<AwResourceContext*>(
1086 AwBrowserContext::FromWebContents(web_contents_.get())->
1087 GetResourceContext());
1088 resource_context->SetExtraHeaders(GURL(ConvertJavaStringToUTF8(env, url)),
1089 extra_headers);
1092 void AwContents::SetJsOnlineProperty(JNIEnv* env,
1093 jobject obj,
1094 jboolean network_up) {
1095 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1096 render_view_host_ext_->SetJsOnlineProperty(network_up);
1099 void AwContents::TrimMemory(JNIEnv* env,
1100 jobject obj,
1101 jint level,
1102 jboolean visible) {
1103 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1104 browser_view_renderer_.TrimMemory(level, visible);
1107 // TODO(sgurun) add support for posting a frame whose name is known (only
1108 // main frame is supported at this time, see crbug.com/389721)
1109 void AwContents::PostMessageToFrame(JNIEnv* env, jobject obj,
1110 jstring frame_name, jstring message, jstring target_origin,
1111 jintArray sent_ports) {
1113 // Use an empty source origin for android webview.
1114 base::string16 source_origin;
1115 base::string16 j_target_origin(ConvertJavaStringToUTF16(env, target_origin));
1116 base::string16 j_message(ConvertJavaStringToUTF16(env, message));
1117 std::vector<int> j_ports;
1119 if (sent_ports != nullptr) {
1120 base::android::JavaIntArrayToIntVector(env, sent_ports, &j_ports);
1121 BrowserThread::PostTask(
1122 BrowserThread::IO,
1123 FROM_HERE,
1124 base::Bind(&AwMessagePortServiceImpl::RemoveSentPorts,
1125 base::Unretained(AwMessagePortServiceImpl::GetInstance()),
1126 j_ports));
1128 std::vector<content::TransferredMessagePort> ports(j_ports.size());
1129 for (size_t i = 0; i < j_ports.size(); ++i)
1130 ports[i].id = j_ports[i];
1131 content::MessagePortProvider::PostMessageToFrame(web_contents_.get(),
1132 source_origin,
1133 j_target_origin,
1134 j_message,
1135 ports);
1138 scoped_refptr<AwMessagePortMessageFilter>
1139 AwContents::GetMessagePortMessageFilter() {
1140 // Create a message port message filter if necessary
1141 if (message_port_message_filter_.get() == nullptr) {
1142 message_port_message_filter_ =
1143 new AwMessagePortMessageFilter(
1144 web_contents_->GetMainFrame()->GetRoutingID());
1145 web_contents_->GetRenderProcessHost()->AddFilter(
1146 message_port_message_filter_.get());
1148 return message_port_message_filter_;
1151 void AwContents::CreateMessageChannel(JNIEnv* env, jobject obj,
1152 jobjectArray ports) {
1154 AwMessagePortServiceImpl::GetInstance()->CreateMessageChannel(env, ports,
1155 GetMessagePortMessageFilter());
1158 void SetShouldDownloadFavicons(JNIEnv* env, jclass jclazz) {
1159 g_should_download_favicons = true;
1162 } // namespace android_webview