1 // Copyright 2014 Samsung Electronics. 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 "web_contents_delegate_efl.h"
7 #include "base/prefs/pref_service.h"
8 #include "base/strings/utf_string_conversions.h"
9 #include "browser/favicon/favicon_database.h"
10 #include "browser/inputpicker/color_chooser_efl.h"
11 #include "browser/javascript_dialog_manager_efl.h"
12 #include "browser/policy_response_delegate_efl.h"
13 #include "common/render_messages_ewk.h"
14 #include "components/password_manager/core/common/password_manager_pref_names.h"
15 #include "content/browser/renderer_host/render_widget_host_view_efl.h"
16 #include "content/common/content_switches_internal.h"
17 #include "content/common/date_time_suggestion.h"
18 #include "content/common/render_messages_efl.h"
19 #include "content/common/view_messages.h"
20 #include "content/public/browser/browser_thread.h"
21 #include "content/public/browser/favicon_status.h"
22 #include "content/public/browser/invalidate_type.h"
23 #include "content/public/browser/navigation_entry.h"
24 #include "content/public/common/favicon_url.h"
25 #include "eweb_view.h"
26 #include "eweb_view_callbacks.h"
27 #include "net/base/load_states.h"
28 #include "net/http/http_response_headers.h"
29 #include "printing/pdf_metafile_skia.h"
30 #include "private/ewk_certificate_private.h"
31 #include "private/ewk_console_message_private.h"
32 #include "private/ewk_custom_handlers_private.h"
33 #include "private/ewk_error_private.h"
34 #include "private/ewk_policy_decision_private.h"
35 #include "private/ewk_user_media_private.h"
36 #include "private/webview_delegate_ewk.h"
37 #include "public/web/WebInputEvent.h"
41 #include "content/public/browser/media_capture_devices.h"
42 #include "media/capture/video/tizen/video_capture_device_tizen.h"
45 #if defined(TIZEN_AUTOFILL_SUPPORT)
46 #include "browser/autofill/autofill_client_efl.h"
47 #include "components/autofill/content/browser/content_autofill_driver_factory.h"
48 #include "browser/password_manager/password_manager_client_efl.h"
49 #include "components/autofill/core/browser/autofill_client.h"
50 #include "components/autofill/core/browser/autofill_manager.h"
51 #include "components/web_modal/web_contents_modal_dialog_manager.h"
53 using autofill::AutofillManager;
54 using autofill::AutofillClientEfl;
55 using autofill::ContentAutofillDriverFactory;
56 using password_manager::PasswordManagerClientEfl;
63 void WritePdfDataToFile(printing::PdfMetafileSkia* metafile, const base::FilePath& filename) {
64 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
66 base::File file(filename, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
67 metafile->SaveTo(&file);
73 static const content::MediaStreamDevice*
74 GetRequestedVideoDevice(const std::string& device_id) {
75 const content::MediaStreamDevices& video_devices =
76 MediaCaptureDevices::GetInstance()->GetVideoCaptureDevices();
77 if (video_devices.empty())
79 if (device_id.length() == 0)
80 return &(*video_devices.begin());
81 return video_devices.FindById(device_id);
85 WebContentsDelegateEfl::WebContentsDelegateEfl(EWebView* view)
86 : WebContentsObserver(&view->web_contents())
88 , is_fullscreen_(false)
89 , web_contents_(view->web_contents())
90 , document_created_(false)
91 , dialog_manager_(NULL)
92 , weak_ptr_factory_(this) {
93 #if defined(TIZEN_AUTOFILL_SUPPORT)
94 AutofillClientEfl::CreateForWebContents(&web_contents_);
95 AutofillClientEfl* autofill_manager =
96 AutofillClientEfl::FromWebContents(&web_contents_);
97 autofill_manager->SetEWebView(view);
98 PasswordManagerClientEfl::CreateForWebContentsWithAutofillClient(&web_contents_,
100 ContentAutofillDriverFactory::CreateForWebContentsAndDelegate(&web_contents_,
102 EWebView::GetPlatformLocale(),
103 AutofillManager::DISABLE_AUTOFILL_DOWNLOAD_MANAGER);
107 WebContentsDelegateEfl::~WebContentsDelegateEfl() {
108 // It's important to delete web_contents_ before dialog_manager_
109 // destructor of web contents uses dialog_manager_
111 delete dialog_manager_;
114 WebContents* WebContentsDelegateEfl::OpenURLFromTab(
116 const content::OpenURLParams& params) {
118 const GURL& url = params.url;
119 WindowOpenDisposition disposition = params.disposition;
121 if (!source || (disposition != CURRENT_TAB &&
122 disposition != NEW_FOREGROUND_TAB &&
123 disposition != NEW_BACKGROUND_TAB &&
124 disposition != OFF_THE_RECORD)) {
129 if (disposition == NEW_FOREGROUND_TAB ||
130 disposition == NEW_BACKGROUND_TAB ||
131 disposition == OFF_THE_RECORD) {
132 Evas_Object* new_object = NULL;
133 web_view_->SmartCallback<EWebViewCallbacks::CreateNewWindow>().call(&new_object);
138 EWebView* wv = WebViewDelegateEwk::GetInstance().
139 GetWebViewFromEvasObject(new_object);
145 ui::PageTransition transition(ui::PageTransitionFromInt(params.transition));
146 source->GetController().LoadURL(url, params.referrer, transition,
151 void WebContentsDelegateEfl::NavigationStateChanged(
152 WebContents* source, InvalidateTypes changed_flags) {
153 if (changed_flags & content::INVALIDATE_TYPE_URL) {
154 const char* url = source->GetVisibleURL().spec().c_str();
155 web_view_->SmartCallback<EWebViewCallbacks::URLChanged>().call(url);
156 web_view_->SmartCallback<EWebViewCallbacks::URIChanged>().call(url);
160 void WebContentsDelegateEfl::LoadingStateChanged(WebContents* source,
161 bool to_different_document) {
162 if (source->IsLoading())
163 web_view_->SmartCallback<EWebViewCallbacks::LoadProgressStarted>().call();
165 web_view_->SmartCallback<EWebViewCallbacks::LoadProgressFinished>().call();
168 void WebContentsDelegateEfl::LoadProgressChanged(WebContents* source, double progress) {
169 web_view_->SetProgressValue(progress);
170 web_view_->SmartCallback<EWebViewCallbacks::LoadProgress>().call(&progress);
173 bool WebContentsDelegateEfl::ShouldCreateWebContents(
174 WebContents* web_contents,
176 int main_frame_route_id,
177 int main_frame_widget_route_id,
178 WindowContainerType window_container_type,
179 const std::string& frame_name,
180 const GURL& target_url,
181 const std::string& partition_id,
182 SessionStorageNamespace* session_storage_namespace) {
183 // We implement the asynchronous version of the function, this
184 // one should never be invoked.
189 void WebContentsDelegateEfl::CloseContents(WebContents* source) {
190 web_view_->SmartCallback<EWebViewCallbacks::WindowClosed>().call();
193 void WebContentsDelegateEfl::EnterFullscreenModeForTab(content::WebContents* web_contents,
194 const GURL& origin) {
195 is_fullscreen_ = true;
196 web_view_->SmartCallback<EWebViewCallbacks::EnterFullscreen>().call();
199 void WebContentsDelegateEfl::ExitFullscreenModeForTab(content::WebContents* web_contents) {
200 is_fullscreen_ = false;
201 web_view_->SmartCallback<EWebViewCallbacks::ExitFullscreen>().call();
204 bool WebContentsDelegateEfl::IsFullscreenForTabOrPending(
205 const WebContents* web_contents) const {
206 return is_fullscreen_;
209 void WebContentsDelegateEfl::RegisterProtocolHandler(WebContents* web_contents,
210 const std::string& protocol, const GURL& url, bool user_gesture) {
211 Ewk_Custom_Handlers_Data protocol_data(protocol.c_str(),
212 url.host().c_str(), url.spec().c_str());
213 web_view_->SmartCallback<EWebViewCallbacks::RegisterProtocolHandler>().call(&protocol_data);
216 void WebContentsDelegateEfl::UnregisterProtocolHandler(WebContents* web_contents,
217 const std::string& protocol,
220 Ewk_Custom_Handlers_Data protocol_data(protocol.c_str(),
221 url.host().c_str(), url.spec().c_str());
222 web_view_->SmartCallback<EWebViewCallbacks::UnregisterProtocolHandler>()
223 .call(&protocol_data);
226 #if defined(TIZEN_MULTIMEDIA_SUPPORT)
227 void WebContentsDelegateEfl::RequestMediaAccessAllow(
228 const MediaStreamRequest& request,
229 const MediaResponseCallback& callback) {
231 MediaStreamDevices devices;
233 if (request.audio_type == content::MEDIA_DEVICE_AUDIO_CAPTURE) {
234 devices.push_back(MediaStreamDevice(request.audio_type,
235 "default", "Default"));
238 if (request.video_type == content::MEDIA_DEVICE_VIDEO_CAPTURE) {
239 #if defined(OS_TIZEN)
240 const content::MediaStreamDevice* video_device =
241 GetRequestedVideoDevice(request.requested_video_device_id);
243 devices.push_back(*video_device);
246 callback.Run(MediaStreamDevices(), MEDIA_DEVICE_NOT_SUPPORTED,
247 scoped_ptr<MediaStreamUI>());
250 devices.push_back(MediaStreamDevice(request.video_type, "/dev/video0", "1"));
254 callback.Run(devices, MEDIA_DEVICE_OK,scoped_ptr<MediaStreamUI>());
257 void WebContentsDelegateEfl::RequestMediaAccessDeny(
258 const MediaStreamRequest& request,
259 const MediaResponseCallback& callback) {
260 LOG(ERROR) << __FUNCTION__ << " Decline request with empty list";
261 callback.Run(MediaStreamDevices(), MEDIA_DEVICE_NOT_SUPPORTED,
262 scoped_ptr<MediaStreamUI>());
265 bool WebContentsDelegateEfl::CheckMediaAccessPermission(
266 WebContents* web_contents,
267 const GURL& security_origin,
268 MediaStreamType type) {
272 void WebContentsDelegateEfl::RequestMediaAccessPermission(
273 WebContents* web_contents,
274 const MediaStreamRequest& request,
275 const MediaResponseCallback& callback) {
276 scoped_ptr<_Ewk_User_Media_Permission_Request> media_permission_request(
277 new _Ewk_User_Media_Permission_Request(this, request, callback));
279 Eina_Bool callback_result = EINA_FALSE;
280 if (!web_view_->InvokeViewUserMediaPermissionCallback(
281 media_permission_request.get(), &callback_result)) {
282 web_view_->SmartCallback<EWebViewCallbacks::UserMediaPermission>()
283 .call(media_permission_request.get());
286 if (media_permission_request->IsSuspended())
287 media_permission_request.release();
288 else if (!media_permission_request->IsDecided()) {
289 callback.Run(MediaStreamDevices(), MEDIA_DEVICE_NOT_SUPPORTED,
290 scoped_ptr<MediaStreamUI>());
295 void WebContentsDelegateEfl::OnAuthRequired(net::URLRequest* request,
296 const std::string& realm,
297 LoginDelegateEfl* login_delegate) {
298 web_view_->InvokeAuthCallback(login_delegate, request->url(), realm);
301 void WebContentsDelegateEfl::DidStartProvisionalLoadForFrame(RenderFrameHost* render_frame_host,
302 const GURL& validated_url,
304 bool is_iframe_srcdoc) {
305 web_view_->SmartCallback<EWebViewCallbacks::ProvisionalLoadStarted>().call();
308 void WebContentsDelegateEfl::DidCommitProvisionalLoadForFrame(RenderFrameHost* render_frame_host,
310 ui::PageTransition transition_type) {
311 web_view_->SmartCallback<EWebViewCallbacks::LoadCommitted>().call();
315 void WebContentsDelegateEfl::DidNavigateMainFrame(const LoadCommittedDetails& details,
316 const FrameNavigateParams& params) {
317 // The condition checks whether the main frame navigated to a different page,
318 // not scrolled to a fragment inside the current page.
319 if (details.is_navigation_to_different_page())
320 web_view_->SmartCallback<EWebViewCallbacks::LoadStarted>().call();
323 void WebContentsDelegateEfl::DocumentOnLoadCompletedInMainFrame() {
324 web_view_->SmartCallback<EWebViewCallbacks::LoadFinished>().call();
327 void WebContentsDelegateEfl::DidNavigateAnyFrame(RenderFrameHost* render_frame_host, const LoadCommittedDetails& details, const FrameNavigateParams& params) {
328 web_view_->SmartCallback<EWebViewCallbacks::ProvisionalLoadRedirect>().call();
329 static_cast<BrowserContextEfl*>(web_contents_.GetBrowserContext())->AddVisitedURLs(params.redirects);
332 void WebContentsDelegateEfl::DidFinishLoad(RenderFrameHost* render_frame_host,
333 const GURL& validated_url) {
334 if (render_frame_host->GetParent())
337 NavigationEntry *entry = web_contents().GetController().GetVisibleEntry();
341 FaviconStatus &favicon = entry->GetFavicon();
344 // check/update the url and favicon url in favicon database
345 FaviconDatabase::Instance()->SetFaviconURLForPageURL(favicon.url, validated_url);
347 // download favicon if there is no such in database
348 if (!FaviconDatabase::Instance()->ExistsForFaviconURL(favicon.url)) {
349 LOG(ERROR) << "[DidFinishLoad] :: no favicon in database for URL: "
350 << favicon.url.spec();
351 favicon_downloader_.reset(
352 new FaviconDownloader(&web_contents_,
355 &WebContentsDelegateEfl::DidDownloadFavicon,
356 weak_ptr_factory_.GetWeakPtr())));
357 favicon_downloader_->Start();
359 web_view_->SmartCallback<EWebViewCallbacks::IconReceived>().call();
363 web_contents_.Focus();
367 void WebContentsDelegateEfl::DidUpdateFaviconURL(const std::vector<FaviconURL>& candidates) {
368 // select and set proper favicon
369 for (unsigned int i = 0; i < candidates.size(); ++i) {
370 FaviconURL favicon = candidates[i];
371 if (favicon.icon_type == FaviconURL::FAVICON && !favicon.icon_url.is_empty()) {
372 NavigationEntry *entry = web_contents_.GetController().GetVisibleEntry();
375 entry->GetFavicon().url = favicon.icon_url;
376 entry->GetFavicon().valid = true;
383 void WebContentsDelegateEfl::DidDownloadFavicon(bool success, const GURL& icon_url, const SkBitmap& bitmap) {
384 favicon_downloader_.reset();
386 FaviconDatabase::Instance()->SetBitmapForFaviconURL(bitmap, icon_url);
387 // emit "icon,received"
388 web_view_->SmartCallback<EWebViewCallbacks::IconReceived>().call();
392 void WebContentsDelegateEfl::RequestCertificateConfirm(WebContents* /*web_contents*/,
394 const net::SSLInfo& ssl_info,
396 ResourceType /*resource_type*/,
397 bool /*overridable*/,
398 bool /*strict_enforcement*/,
399 const base::Callback<void(bool)>& callback,
400 CertificateRequestResultType* result) {
402 std::string pem_certificate;
403 if (!net::X509Certificate::GetPEMEncoded(ssl_info.cert->os_cert_handle(), &pem_certificate)) {
404 *result = content::CERTIFICATE_REQUEST_RESULT_TYPE_CANCEL;
407 certificate_policy_decision_.reset(new _Ewk_Certificate_Policy_Decision(url,
411 web_view_->SmartCallback<EWebViewCallbacks::RequestCertificateConfirm>().call(
412 certificate_policy_decision_.get());
414 // if policy is suspended, the API takes over the policy object lifetime
415 // and policy will be deleted after decision is made
416 if (certificate_policy_decision_->isSuspended()) {
417 certificate_policy_decision_.release();
419 certificate_policy_decision_->setDecision(true);
423 void WebContentsDelegateEfl::SetContentSecurityPolicy(const std::string& policy, Ewk_CSP_Header_Type header_type) {
424 if (document_created_) {
425 RenderViewHost* rvh = web_contents_.GetRenderViewHost();
426 rvh->Send(new EwkViewMsg_SetCSP(rvh->GetRoutingID(), policy, header_type));
428 DCHECK(!pending_content_security_policy_.get());
429 pending_content_security_policy_.reset(new ContentSecurityPolicy(policy, header_type));
433 void WebContentsDelegateEfl::FindReply(WebContents* web_contents,
435 int number_of_matches,
436 const gfx::Rect& selection_rect,
437 int active_match_ordinal,
439 if (final_update && request_id == web_view_->current_find_request_id()) {
440 unsigned int uint_number_of_matches = static_cast<unsigned int>(number_of_matches);
441 web_view_->SmartCallback<EWebViewCallbacks::TextFound>().call(&uint_number_of_matches);
445 JavaScriptDialogManager* WebContentsDelegateEfl::GetJavaScriptDialogManager(
446 WebContents* source) {
447 if (!dialog_manager_)
448 dialog_manager_ = new JavaScriptDialogManagerEfl();
449 return dialog_manager_;
452 void WebContentsDelegateEfl::OnUpdateSettings(const Ewk_Settings *settings) {
453 #if defined(TIZEN_AUTOFILL_SUPPORT)
454 PasswordManagerClientEfl* client =
455 PasswordManagerClientEfl::FromWebContents(&web_contents_);
457 PrefService* prefs = client->GetPrefs();
458 prefs->SetBoolean(password_manager::prefs::kPasswordManagerSavingEnabled,
459 settings->autofillPasswordForm());
464 bool WebContentsDelegateEfl::OnMessageReceived(const IPC::Message& message) {
466 IPC_BEGIN_MESSAGE_MAP(WebContentsDelegateEfl, message)
467 IPC_MESSAGE_HANDLER_DELAY_REPLY(EwkHostMsg_GetContentSecurityPolicy, OnGetContentSecurityPolicy)
468 IPC_MESSAGE_HANDLER(EwkHostMsg_DidPrintPagesToPdf, OnPrintedMetafileReceived)
469 IPC_MESSAGE_HANDLER(EwkHostMsg_WrtMessage, OnWrtPluginMessage)
470 IPC_MESSAGE_HANDLER_DELAY_REPLY(EwkHostMsg_WrtSyncMessage, OnWrtPluginSyncMessage)
471 IPC_MESSAGE_UNHANDLED(handled = false)
472 IPC_END_MESSAGE_MAP()
477 void WebContentsDelegateEfl::DidFailProvisionalLoad(
478 RenderFrameHost* render_frame_host, const GURL& validated_url,
479 int error_code, const base::string16& error_description,
480 bool was_ignored_by_handler) {
481 DidFailLoad(render_frame_host, validated_url, error_code,
482 error_description, was_ignored_by_handler);
485 void WebContentsDelegateEfl::DidFailLoad(RenderFrameHost* render_frame_host,
486 const GURL& validated_url, int error_code,
487 const base::string16& error_description, bool was_ignored_by_handler) {
488 bool is_main_frame = !render_frame_host->GetParent();
489 std::string description = base::UTF16ToUTF8(error_description);
490 web_view_->InvokeLoadError(validated_url, error_code, description, is_main_frame);
493 void WebContentsDelegateEfl::OnWrtPluginMessage(const Ewk_Wrt_Message_Data& data) {
494 scoped_ptr<Ewk_Wrt_Message_Data> p(new Ewk_Wrt_Message_Data);
496 p->value = data.value;
498 p->reference_id = data.reference_id;
500 web_view_->SmartCallback<EWebViewCallbacks::WrtPluginsMessage>().call(p.get());
503 void WebContentsDelegateEfl::OnWrtPluginSyncMessage(const Ewk_Wrt_Message_Data& data,
504 IPC::Message* reply) {
505 Ewk_Wrt_Message_Data tmp = data;
506 web_view_->SmartCallback<EWebViewCallbacks::WrtPluginsMessage>().call(&tmp);
507 EwkHostMsg_WrtSyncMessage::WriteReplyParams(reply, tmp.value);
511 void WebContentsDelegateEfl::DidFirstVisuallyNonEmptyPaint() {
512 web_view_->SmartCallback<EWebViewCallbacks::LoadNonEmptyLayoutFinished>().call();
513 web_view_->SmartCallback<EWebViewCallbacks::FrameRendered>().call(0);
516 void WebContentsDelegateEfl::OnGetContentSecurityPolicy(IPC::Message* reply_msg) {
517 document_created_ = true;
518 if (!pending_content_security_policy_.get()) {
519 EwkHostMsg_GetContentSecurityPolicy::WriteReplyParams(reply_msg, std::string(), EWK_DEFAULT_POLICY);
521 EwkHostMsg_GetContentSecurityPolicy::WriteReplyParams(reply_msg,
522 pending_content_security_policy_->policy, pending_content_security_policy_->header_type);
523 pending_content_security_policy_.reset();
528 void WebContentsDelegateEfl::OnPrintedMetafileReceived(const DidPrintPagesParams& params) {
529 base::SharedMemory shared_buf(params.metafile_data_handle, true);
530 if (!shared_buf.Map(params.data_size)) {
531 NOTREACHED() << "couldn't map";
534 scoped_ptr<printing::PdfMetafileSkia> metafile(new printing::PdfMetafileSkia);
535 if (!metafile->InitFromData(shared_buf.memory(), params.data_size)) {
536 NOTREACHED() << "Invalid metafile header";
539 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
540 base::Bind(&WritePdfDataToFile, metafile.release(), params.filename));
543 void WebContentsDelegateEfl::NavigationEntryCommitted(const LoadCommittedDetails& load_details) {
544 web_view_->InvokeBackForwardListChangedCallback();
547 void WebContentsDelegateEfl::RenderViewCreated(RenderViewHost* render_view_host) {
548 web_view_->RenderViewCreated(render_view_host);
551 void WebContentsDelegateEfl::RenderProcessGone(base::TerminationStatus status) {
552 // See RenderWidgetHostViewEfl::RenderProcessGone.
553 if (status == base::TERMINATION_STATUS_ABNORMAL_TERMINATION
554 || status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED
555 || status == base::TERMINATION_STATUS_PROCESS_CRASHED) {
556 web_view_->HandleRendererProcessCrash();
560 bool WebContentsDelegateEfl::AddMessageToConsole(WebContents* source,
562 const string16& message,
564 const string16& source_id) {
565 scoped_ptr<_Ewk_Console_Message> console_message(new _Ewk_Console_Message(level,
566 UTF16ToUTF8(message).c_str(),
568 UTF16ToUTF8(source_id).c_str()));
569 web_view_->SmartCallback<EWebViewCallbacks::ConsoleMessage>().call(console_message.get());
573 void WebContentsDelegateEfl::RunFileChooser(WebContents* web_contents, const FileChooserParams& params) {
574 web_view_->ShowFileChooser(params);
577 content::ColorChooser* WebContentsDelegateEfl::OpenColorChooser(
578 WebContents* web_contents,
580 const std::vector<ColorSuggestion>& suggestions) {
581 ColorChooserEfl* color_chooser_efl = new ColorChooserEfl(*web_contents);
582 web_view_->RequestColorPicker(SkColorGetR(color), SkColorGetG(color), SkColorGetB(color), SkColorGetA(color));
584 return color_chooser_efl;
587 void WebContentsDelegateEfl::OpenDateTimeDialog(
588 ui::TextInputType dialog_type,
593 const std::vector<DateTimeSuggestion>& suggestions) {
594 web_view_->InputPickerShow(dialog_type, dialog_value);
597 bool WebContentsDelegateEfl::PreHandleGestureEvent(
599 const blink::WebGestureEvent& event) {
600 switch (event.type) {
601 case blink::WebInputEvent::GestureDoubleTap:
605 case blink::WebInputEvent::GesturePinchBegin:
606 case blink::WebInputEvent::GesturePinchUpdate:
607 case blink::WebInputEvent::GesturePinchEnd:
608 if (!IsPinchToZoomEnabled() ||
609 IsFullscreenForTabOrPending(&web_contents()))
618 void WebContentsDelegateEfl::TitleWasSet(NavigationEntry* entry,
619 bool /*explicit_set*/) {
621 web_view_->GetBackForwardList()->UpdateItemWithEntry(entry);
624 } //namespace content