Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / guest_view / web_view / web_view_guest.cc
1 // Copyright 2014 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.
4
5 #include "chrome/browser/guest_view/web_view/web_view_guest.h"
6
7 #include "base/message_loop/message_loop.h"
8 #include "base/strings/stringprintf.h"
9 #include "chrome/browser/chrome_notification_types.h"
10 #include "chrome/browser/extensions/api/web_request/web_request_api.h"
11 #include "chrome/browser/extensions/api/webview/webview_api.h"
12 #include "chrome/browser/extensions/chrome_extension_web_contents_observer.h"
13 #include "chrome/browser/extensions/extension_renderer_state.h"
14 #include "chrome/browser/extensions/menu_manager.h"
15 #include "chrome/browser/extensions/script_executor.h"
16 #include "chrome/browser/favicon/favicon_tab_helper.h"
17 #include "chrome/browser/guest_view/guest_view_constants.h"
18 #include "chrome/browser/guest_view/web_view/web_view_constants.h"
19 #include "chrome/browser/guest_view/web_view/web_view_permission_types.h"
20 #include "chrome/browser/renderer_context_menu/context_menu_delegate.h"
21 #include "chrome/browser/renderer_context_menu/render_view_context_menu.h"
22 #include "chrome/common/chrome_version_info.h"
23 #include "content/public/browser/browser_thread.h"
24 #include "content/public/browser/geolocation_permission_context.h"
25 #include "content/public/browser/native_web_keyboard_event.h"
26 #include "content/public/browser/navigation_entry.h"
27 #include "content/public/browser/notification_details.h"
28 #include "content/public/browser/notification_service.h"
29 #include "content/public/browser/notification_source.h"
30 #include "content/public/browser/notification_types.h"
31 #include "content/public/browser/render_process_host.h"
32 #include "content/public/browser/resource_request_details.h"
33 #include "content/public/browser/site_instance.h"
34 #include "content/public/browser/storage_partition.h"
35 #include "content/public/browser/user_metrics.h"
36 #include "content/public/browser/web_contents.h"
37 #include "content/public/browser/web_contents_delegate.h"
38 #include "content/public/common/media_stream_request.h"
39 #include "content/public/common/page_zoom.h"
40 #include "content/public/common/result_codes.h"
41 #include "content/public/common/stop_find_action.h"
42 #include "extensions/common/constants.h"
43 #include "net/base/net_errors.h"
44 #include "third_party/WebKit/public/web/WebFindOptions.h"
45 #include "ui/base/models/simple_menu_model.h"
46
47 #if defined(ENABLE_PLUGINS)
48 #include "chrome/browser/guest_view/web_view/plugin_permission_helper.h"
49 #endif
50
51 #if defined(OS_CHROMEOS)
52 #include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
53 #endif
54
55 using base::UserMetricsAction;
56 using content::WebContents;
57
58 namespace {
59
60 static std::string TerminationStatusToString(base::TerminationStatus status) {
61   switch (status) {
62     case base::TERMINATION_STATUS_NORMAL_TERMINATION:
63       return "normal";
64     case base::TERMINATION_STATUS_ABNORMAL_TERMINATION:
65     case base::TERMINATION_STATUS_STILL_RUNNING:
66       return "abnormal";
67     case base::TERMINATION_STATUS_PROCESS_WAS_KILLED:
68       return "killed";
69     case base::TERMINATION_STATUS_PROCESS_CRASHED:
70 #if defined(OS_ANDROID)
71     case base::TERMINATION_STATUS_OOM_PROTECTED:
72 #endif
73       return "crashed";
74     case base::TERMINATION_STATUS_MAX_ENUM:
75       break;
76   }
77   NOTREACHED() << "Unknown Termination Status.";
78   return "unknown";
79 }
80
81 static std::string PermissionTypeToString(BrowserPluginPermissionType type) {
82   switch (type) {
83     case BROWSER_PLUGIN_PERMISSION_TYPE_NEW_WINDOW:
84       return webview::kPermissionTypeNewWindow;
85     case BROWSER_PLUGIN_PERMISSION_TYPE_UNKNOWN:
86       NOTREACHED();
87       break;
88     default: {
89       WebViewPermissionType webview = static_cast<WebViewPermissionType>(type);
90       switch (webview) {
91         case WEB_VIEW_PERMISSION_TYPE_DOWNLOAD:
92           return webview::kPermissionTypeDownload;
93         case WEB_VIEW_PERMISSION_TYPE_GEOLOCATION:
94           return webview::kPermissionTypeGeolocation;
95         case WEB_VIEW_PERMISSION_TYPE_JAVASCRIPT_DIALOG:
96           return webview::kPermissionTypeDialog;
97         case WEB_VIEW_PERMISSION_TYPE_LOAD_PLUGIN:
98           return webview::kPermissionTypeLoadPlugin;
99         case WEB_VIEW_PERMISSION_TYPE_MEDIA:
100           return webview::kPermissionTypeMedia;
101         case WEB_VIEW_PERMISSION_TYPE_POINTER_LOCK:
102           return webview::kPermissionTypePointerLock;
103       }
104       NOTREACHED();
105     }
106   }
107   return std::string();
108 }
109
110 void RemoveWebViewEventListenersOnIOThread(
111     void* profile,
112     const std::string& extension_id,
113     int embedder_process_id,
114     int view_instance_id) {
115   DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
116   ExtensionWebRequestEventRouter::GetInstance()->RemoveWebViewEventListeners(
117       profile,
118       extension_id,
119       embedder_process_id,
120       view_instance_id);
121 }
122
123 void AttachWebViewHelpers(WebContents* contents) {
124   FaviconTabHelper::CreateForWebContents(contents);
125   extensions::ChromeExtensionWebContentsObserver::CreateForWebContents(
126       contents);
127 #if defined(ENABLE_PLUGINS)
128   PluginPermissionHelper::CreateForWebContents(contents);
129 #endif
130 }
131
132 }  // namespace
133
134 WebViewGuest::WebViewGuest(WebContents* guest_web_contents,
135                            const std::string& embedder_extension_id,
136                            const base::WeakPtr<GuestViewBase>& opener)
137    :  GuestView<WebViewGuest>(guest_web_contents,
138                               embedder_extension_id,
139                               opener),
140       WebContentsObserver(guest_web_contents),
141       script_executor_(new extensions::ScriptExecutor(guest_web_contents,
142                                                       &script_observers_)),
143       pending_context_menu_request_id_(0),
144       next_permission_request_id_(0),
145       is_overriding_user_agent_(false),
146       pending_reload_on_attachment_(false),
147       main_frame_id_(0),
148       chromevox_injected_(false),
149       find_helper_(this),
150       javascript_dialog_helper_(this) {
151   notification_registrar_.Add(
152       this, content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
153       content::Source<WebContents>(guest_web_contents));
154
155   notification_registrar_.Add(
156       this, content::NOTIFICATION_RESOURCE_RECEIVED_REDIRECT,
157       content::Source<WebContents>(guest_web_contents));
158
159 #if defined(OS_CHROMEOS)
160   chromeos::AccessibilityManager* accessibility_manager =
161       chromeos::AccessibilityManager::Get();
162   CHECK(accessibility_manager);
163   accessibility_subscription_ = accessibility_manager->RegisterCallback(
164       base::Bind(&WebViewGuest::OnAccessibilityStatusChanged,
165                  base::Unretained(this)));
166 #endif
167
168   AttachWebViewHelpers(guest_web_contents);
169 }
170
171 // static
172 const char WebViewGuest::Type[] = "webview";
173
174 // static.
175 int WebViewGuest::GetViewInstanceId(WebContents* contents) {
176   WebViewGuest* guest = FromWebContents(contents);
177   if (!guest)
178     return guestview::kInstanceIDNone;
179
180   return guest->view_instance_id();
181 }
182
183 // static
184 void WebViewGuest::RecordUserInitiatedUMA(const PermissionResponseInfo& info,
185                                           bool allow) {
186   if (allow) {
187     // Note that |allow| == true means the embedder explicitly allowed the
188     // request. For some requests they might still fail. An example of such
189     // scenario would be: an embedder allows geolocation request but doesn't
190     // have geolocation access on its own.
191     switch (info.permission_type) {
192       case BROWSER_PLUGIN_PERMISSION_TYPE_NEW_WINDOW:
193         content::RecordAction(
194             UserMetricsAction("BrowserPlugin.PermissionAllow.NewWindow"));
195         break;
196       case BROWSER_PLUGIN_PERMISSION_TYPE_UNKNOWN:
197         break;
198       default: {
199         WebViewPermissionType webview_permission_type =
200             static_cast<WebViewPermissionType>(info.permission_type);
201         switch (webview_permission_type) {
202           case WEB_VIEW_PERMISSION_TYPE_DOWNLOAD:
203             content::RecordAction(
204                 UserMetricsAction("WebView.PermissionAllow.Download"));
205             break;
206           case WEB_VIEW_PERMISSION_TYPE_GEOLOCATION:
207             content::RecordAction(
208                 UserMetricsAction("WebView.PermissionAllow.Geolocation"));
209             break;
210           case WEB_VIEW_PERMISSION_TYPE_JAVASCRIPT_DIALOG:
211             content::RecordAction(
212                 UserMetricsAction("WebView.PermissionAllow.JSDialog"));
213             break;
214           case WEB_VIEW_PERMISSION_TYPE_LOAD_PLUGIN:
215             content::RecordAction(
216                 UserMetricsAction("WebView.Guest.PermissionAllow.PluginLoad"));
217           case WEB_VIEW_PERMISSION_TYPE_MEDIA:
218             content::RecordAction(
219                 UserMetricsAction("WebView.PermissionAllow.Media"));
220             break;
221           case WEB_VIEW_PERMISSION_TYPE_POINTER_LOCK:
222             content::RecordAction(
223                 UserMetricsAction("WebView.PermissionAllow.PointerLock"));
224             break;
225           default:
226             break;
227         }
228       }
229     }
230   } else {
231     switch (info.permission_type) {
232       case BROWSER_PLUGIN_PERMISSION_TYPE_NEW_WINDOW:
233         content::RecordAction(
234             UserMetricsAction("BrowserPlugin.PermissionDeny.NewWindow"));
235         break;
236       case BROWSER_PLUGIN_PERMISSION_TYPE_UNKNOWN:
237         break;
238       default: {
239         WebViewPermissionType webview_permission_type =
240             static_cast<WebViewPermissionType>(info.permission_type);
241         switch (webview_permission_type) {
242           case WEB_VIEW_PERMISSION_TYPE_DOWNLOAD:
243             content::RecordAction(
244                 UserMetricsAction("WebView.PermissionDeny.Download"));
245             break;
246           case WEB_VIEW_PERMISSION_TYPE_GEOLOCATION:
247             content::RecordAction(
248                 UserMetricsAction("WebView.PermissionDeny.Geolocation"));
249             break;
250           case WEB_VIEW_PERMISSION_TYPE_JAVASCRIPT_DIALOG:
251             content::RecordAction(
252                 UserMetricsAction("WebView.PermissionDeny.JSDialog"));
253             break;
254           case WEB_VIEW_PERMISSION_TYPE_LOAD_PLUGIN:
255             content::RecordAction(
256                 UserMetricsAction("WebView.Guest.PermissionDeny.PluginLoad"));
257           case WEB_VIEW_PERMISSION_TYPE_MEDIA:
258             content::RecordAction(
259                 UserMetricsAction("WebView.PermissionDeny.Media"));
260             break;
261           case WEB_VIEW_PERMISSION_TYPE_POINTER_LOCK:
262             content::RecordAction(
263                 UserMetricsAction("WebView.PermissionDeny.PointerLock"));
264             break;
265           default:
266             break;
267         }
268       }
269     }
270   }
271 }
272
273 // static
274 scoped_ptr<base::ListValue> WebViewGuest::MenuModelToValue(
275     const ui::SimpleMenuModel& menu_model) {
276   scoped_ptr<base::ListValue> items(new base::ListValue());
277   for (int i = 0; i < menu_model.GetItemCount(); ++i) {
278     base::DictionaryValue* item_value = new base::DictionaryValue();
279     // TODO(lazyboy): We need to expose some kind of enum equivalent of
280     // |command_id| instead of plain integers.
281     item_value->SetInteger(webview::kMenuItemCommandId,
282                            menu_model.GetCommandIdAt(i));
283     item_value->SetString(webview::kMenuItemLabel, menu_model.GetLabelAt(i));
284     items->Append(item_value);
285   }
286   return items.Pass();
287 }
288
289 void WebViewGuest::Attach(WebContents* embedder_web_contents,
290                           const base::DictionaryValue& args) {
291   std::string user_agent_override;
292   if (args.GetString(webview::kParameterUserAgentOverride,
293                      &user_agent_override)) {
294     SetUserAgentOverride(user_agent_override);
295   } else {
296     SetUserAgentOverride("");
297   }
298
299   GuestViewBase::Attach(embedder_web_contents, args);
300
301   AddWebViewToExtensionRendererState();
302 }
303
304 bool WebViewGuest::HandleContextMenu(
305     const content::ContextMenuParams& params) {
306   ContextMenuDelegate* menu_delegate =
307       ContextMenuDelegate::FromWebContents(guest_web_contents());
308   DCHECK(menu_delegate);
309
310   pending_menu_ = menu_delegate->BuildMenu(guest_web_contents(), params);
311
312   // Pass it to embedder.
313   int request_id = ++pending_context_menu_request_id_;
314   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
315   scoped_ptr<base::ListValue> items =
316       MenuModelToValue(pending_menu_->menu_model());
317   args->Set(webview::kContextMenuItems, items.release());
318   args->SetInteger(webview::kRequestId, request_id);
319   DispatchEvent(new GuestViewBase::Event(webview::kEventContextMenu,
320                                          args.Pass()));
321   return true;
322 }
323
324 void WebViewGuest::AddMessageToConsole(int32 level,
325                                        const base::string16& message,
326                                        int32 line_no,
327                                        const base::string16& source_id) {
328   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
329   // Log levels are from base/logging.h: LogSeverity.
330   args->SetInteger(webview::kLevel, level);
331   args->SetString(webview::kMessage, message);
332   args->SetInteger(webview::kLine, line_no);
333   args->SetString(webview::kSourceId, source_id);
334   DispatchEvent(
335       new GuestViewBase::Event(webview::kEventConsoleMessage, args.Pass()));
336 }
337
338 void WebViewGuest::Close() {
339   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
340   DispatchEvent(new GuestViewBase::Event(webview::kEventClose, args.Pass()));
341 }
342
343 void WebViewGuest::DidAttach() {
344   if (pending_reload_on_attachment_) {
345     pending_reload_on_attachment_ = false;
346     guest_web_contents()->GetController().Reload(false);
347   }
348 }
349
350 void WebViewGuest::EmbedderDestroyed() {
351   // TODO(fsamuel): WebRequest event listeners for <webview> should survive
352   // reparenting of a <webview> within a single embedder. Right now, we keep
353   // around the browser state for the listener for the lifetime of the embedder.
354   // Ideally, the lifetime of the listeners should match the lifetime of the
355   // <webview> DOM node. Once http://crbug.com/156219 is resolved we can move
356   // the call to RemoveWebViewEventListenersOnIOThread back to
357   // WebViewGuest::WebContentsDestroyed.
358   content::BrowserThread::PostTask(
359       content::BrowserThread::IO,
360       FROM_HERE,
361       base::Bind(
362           &RemoveWebViewEventListenersOnIOThread,
363           browser_context(), embedder_extension_id(),
364           embedder_render_process_id(),
365           view_instance_id()));
366 }
367
368 void WebViewGuest::FindReply(int request_id,
369                              int number_of_matches,
370                              const gfx::Rect& selection_rect,
371                              int active_match_ordinal,
372                              bool final_update) {
373   find_helper_.FindReply(request_id, number_of_matches, selection_rect,
374                          active_match_ordinal, final_update);
375 }
376
377 void WebViewGuest::GuestProcessGone(base::TerminationStatus status) {
378   // Cancel all find sessions in progress.
379   find_helper_.CancelAllFindSessions();
380
381   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
382   args->SetInteger(webview::kProcessId,
383                    guest_web_contents()->GetRenderProcessHost()->GetID());
384   args->SetString(webview::kReason, TerminationStatusToString(status));
385   DispatchEvent(new GuestViewBase::Event(webview::kEventExit, args.Pass()));
386 }
387
388 bool WebViewGuest::HandleKeyboardEvent(
389     const content::NativeWebKeyboardEvent& event) {
390   if (event.type != blink::WebInputEvent::RawKeyDown)
391     return false;
392
393 #if defined(OS_MACOSX)
394   if (event.modifiers != blink::WebInputEvent::MetaKey)
395     return false;
396
397   if (event.windowsKeyCode == ui::VKEY_OEM_4) {
398     Go(-1);
399     return true;
400   }
401
402   if (event.windowsKeyCode == ui::VKEY_OEM_6) {
403     Go(1);
404     return true;
405   }
406 #else
407   if (event.windowsKeyCode == ui::VKEY_BROWSER_BACK) {
408     Go(-1);
409     return true;
410   }
411
412   if (event.windowsKeyCode == ui::VKEY_BROWSER_FORWARD) {
413     Go(1);
414     return true;
415   }
416 #endif
417   return false;
418 }
419
420 bool WebViewGuest::IsDragAndDropEnabled() {
421   return true;
422 }
423
424 bool WebViewGuest::IsOverridingUserAgent() const {
425   return is_overriding_user_agent_;
426 }
427
428 void WebViewGuest::LoadProgressed(double progress) {
429   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
430   args->SetString(guestview::kUrl, guest_web_contents()->GetURL().spec());
431   args->SetDouble(webview::kProgress, progress);
432   DispatchEvent(
433       new GuestViewBase::Event(webview::kEventLoadProgress, args.Pass()));
434 }
435
436 void WebViewGuest::LoadAbort(bool is_top_level,
437                              const GURL& url,
438                              const std::string& error_type) {
439   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
440   args->SetBoolean(guestview::kIsTopLevel, is_top_level);
441   args->SetString(guestview::kUrl, url.possibly_invalid_spec());
442   args->SetString(guestview::kReason, error_type);
443   DispatchEvent(
444       new GuestViewBase::Event(webview::kEventLoadAbort, args.Pass()));
445 }
446
447 // TODO(fsamuel): Find a reliable way to test the 'responsive' and
448 // 'unresponsive' events.
449 void WebViewGuest::RendererResponsive() {
450   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
451   args->SetInteger(webview::kProcessId,
452       guest_web_contents()->GetRenderProcessHost()->GetID());
453   DispatchEvent(
454       new GuestViewBase::Event(webview::kEventResponsive, args.Pass()));
455 }
456
457 void WebViewGuest::RendererUnresponsive() {
458   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
459   args->SetInteger(webview::kProcessId,
460       guest_web_contents()->GetRenderProcessHost()->GetID());
461   DispatchEvent(
462       new GuestViewBase::Event(webview::kEventUnresponsive, args.Pass()));
463 }
464
465 void WebViewGuest::RequestPermission(
466     BrowserPluginPermissionType permission_type,
467     const base::DictionaryValue& request_info,
468     const PermissionResponseCallback& callback,
469     bool allowed_by_default) {
470   RequestPermissionInternal(permission_type,
471                             request_info,
472                             callback,
473                             allowed_by_default);
474 }
475
476 void WebViewGuest::Observe(int type,
477                            const content::NotificationSource& source,
478                            const content::NotificationDetails& details) {
479   switch (type) {
480     case content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME: {
481       DCHECK_EQ(content::Source<WebContents>(source).ptr(),
482                 guest_web_contents());
483       if (content::Source<WebContents>(source).ptr() == guest_web_contents())
484         LoadHandlerCalled();
485       break;
486     }
487     case content::NOTIFICATION_RESOURCE_RECEIVED_REDIRECT: {
488       DCHECK_EQ(content::Source<WebContents>(source).ptr(),
489                 guest_web_contents());
490       content::ResourceRedirectDetails* resource_redirect_details =
491           content::Details<content::ResourceRedirectDetails>(details).ptr();
492       bool is_top_level =
493           resource_redirect_details->resource_type == ResourceType::MAIN_FRAME;
494       LoadRedirect(resource_redirect_details->url,
495                    resource_redirect_details->new_url,
496                    is_top_level);
497       break;
498     }
499     default:
500       NOTREACHED() << "Unexpected notification sent.";
501       break;
502   }
503 }
504
505 void WebViewGuest::SetZoom(double zoom_factor) {
506   double zoom_level = content::ZoomFactorToZoomLevel(zoom_factor);
507   guest_web_contents()->SetZoomLevel(zoom_level);
508
509   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
510   args->SetDouble(webview::kOldZoomFactor, current_zoom_factor_);
511   args->SetDouble(webview::kNewZoomFactor, zoom_factor);
512   DispatchEvent(
513       new GuestViewBase::Event(webview::kEventZoomChange, args.Pass()));
514
515   current_zoom_factor_ = zoom_factor;
516 }
517
518 double WebViewGuest::GetZoom() {
519   return current_zoom_factor_;
520 }
521
522 void WebViewGuest::Find(
523     const base::string16& search_text,
524     const blink::WebFindOptions& options,
525     scoped_refptr<extensions::WebviewFindFunction> find_function) {
526   find_helper_.Find(guest_web_contents(), search_text, options, find_function);
527 }
528
529 void WebViewGuest::StopFinding(content::StopFindAction action) {
530   find_helper_.CancelAllFindSessions();
531   guest_web_contents()->StopFinding(action);
532 }
533
534 void WebViewGuest::Go(int relative_index) {
535   guest_web_contents()->GetController().GoToOffset(relative_index);
536 }
537
538 void WebViewGuest::Reload() {
539   // TODO(fsamuel): Don't check for repost because we don't want to show
540   // Chromium's repost warning. We might want to implement a separate API
541   // for registering a callback if a repost is about to happen.
542   guest_web_contents()->GetController().Reload(false);
543 }
544
545
546 void WebViewGuest::RequestGeolocationPermission(
547     int bridge_id,
548     const GURL& requesting_frame,
549     bool user_gesture,
550     const base::Callback<void(bool)>& callback) {
551   base::DictionaryValue request_info;
552   request_info.Set(guestview::kUrl,
553                    base::Value::CreateStringValue(requesting_frame.spec()));
554   request_info.Set(guestview::kUserGesture,
555                    base::Value::CreateBooleanValue(user_gesture));
556
557   // It is safe to hold an unretained pointer to WebViewGuest because this
558   // callback is called from WebViewGuest::SetPermission.
559   const PermissionResponseCallback permission_callback =
560       base::Bind(&WebViewGuest::OnWebViewGeolocationPermissionResponse,
561                  base::Unretained(this),
562                  bridge_id,
563                  user_gesture,
564                  callback);
565   int request_id = RequestPermissionInternal(
566       static_cast<BrowserPluginPermissionType>(
567           WEB_VIEW_PERMISSION_TYPE_GEOLOCATION),
568       request_info,
569       permission_callback,
570       false /* allowed_by_default */);
571   bridge_id_to_request_id_map_[bridge_id] = request_id;
572 }
573
574 void WebViewGuest::OnWebViewGeolocationPermissionResponse(
575     int bridge_id,
576     bool user_gesture,
577     const base::Callback<void(bool)>& callback,
578     bool allow,
579     const std::string& user_input) {
580   // The <webview> embedder has allowed the permission. We now need to make sure
581   // that the embedder has geolocation permission.
582   RemoveBridgeID(bridge_id);
583
584   if (!allow || !attached()) {
585     callback.Run(false);
586     return;
587   }
588
589   content::GeolocationPermissionContext* geolocation_context =
590       browser_context()->GetGeolocationPermissionContext();
591
592   DCHECK(geolocation_context);
593   geolocation_context->RequestGeolocationPermission(
594       embedder_web_contents()->GetRenderProcessHost()->GetID(),
595       embedder_web_contents()->GetRoutingID(),
596       // The geolocation permission request here is not initiated
597       // through WebGeolocationPermissionRequest. We are only interested
598       // in the fact whether the embedder/app has geolocation
599       // permission. Therefore we use an invalid |bridge_id|.
600       -1 /* bridge_id */,
601       embedder_web_contents()->GetLastCommittedURL(),
602       user_gesture,
603       callback);
604 }
605
606 void WebViewGuest::CancelGeolocationPermissionRequest(int bridge_id) {
607   int request_id = RemoveBridgeID(bridge_id);
608   RequestMap::iterator request_itr =
609       pending_permission_requests_.find(request_id);
610
611   if (request_itr == pending_permission_requests_.end())
612     return;
613
614   pending_permission_requests_.erase(request_itr);
615 }
616
617 void WebViewGuest::OnWebViewMediaPermissionResponse(
618     const content::MediaStreamRequest& request,
619     const content::MediaResponseCallback& callback,
620     bool allow,
621     const std::string& user_input) {
622   if (!allow || !attached()) {
623     // Deny the request.
624     callback.Run(content::MediaStreamDevices(),
625                  content::MEDIA_DEVICE_INVALID_STATE,
626                  scoped_ptr<content::MediaStreamUI>());
627     return;
628   }
629   if (!embedder_web_contents()->GetDelegate())
630     return;
631
632   embedder_web_contents()->GetDelegate()->
633       RequestMediaAccessPermission(embedder_web_contents(), request, callback);
634 }
635
636 void WebViewGuest::OnWebViewDownloadPermissionResponse(
637     const base::Callback<void(bool)>& callback,
638     bool allow,
639     const std::string& user_input) {
640   callback.Run(allow && attached());
641 }
642
643 void WebViewGuest::OnWebViewPointerLockPermissionResponse(
644     const base::Callback<void(bool)>& callback,
645     bool allow,
646     const std::string& user_input) {
647   callback.Run(allow && attached());
648 }
649
650 WebViewGuest::SetPermissionResult WebViewGuest::SetPermission(
651     int request_id,
652     PermissionResponseAction action,
653     const std::string& user_input) {
654   RequestMap::iterator request_itr =
655       pending_permission_requests_.find(request_id);
656
657   if (request_itr == pending_permission_requests_.end())
658     return SET_PERMISSION_INVALID;
659
660   const PermissionResponseInfo& info = request_itr->second;
661   bool allow = (action == ALLOW) ||
662       ((action == DEFAULT) && info.allowed_by_default);
663
664   info.callback.Run(allow, user_input);
665
666   // Only record user initiated (i.e. non-default) actions.
667   if (action != DEFAULT)
668     RecordUserInitiatedUMA(info, allow);
669
670   pending_permission_requests_.erase(request_itr);
671
672   return allow ? SET_PERMISSION_ALLOWED : SET_PERMISSION_DENIED;
673 }
674
675 void WebViewGuest::SetUserAgentOverride(
676     const std::string& user_agent_override) {
677   is_overriding_user_agent_ = !user_agent_override.empty();
678   if (is_overriding_user_agent_) {
679     content::RecordAction(UserMetricsAction("WebView.Guest.OverrideUA"));
680   }
681   guest_web_contents()->SetUserAgentOverride(user_agent_override);
682 }
683
684 void WebViewGuest::Stop() {
685   guest_web_contents()->Stop();
686 }
687
688 void WebViewGuest::Terminate() {
689   content::RecordAction(UserMetricsAction("WebView.Guest.Terminate"));
690   base::ProcessHandle process_handle =
691       guest_web_contents()->GetRenderProcessHost()->GetHandle();
692   if (process_handle)
693     base::KillProcess(process_handle, content::RESULT_CODE_KILLED, false);
694 }
695
696 bool WebViewGuest::ClearData(const base::Time remove_since,
697                              uint32 removal_mask,
698                              const base::Closure& callback) {
699   content::RecordAction(UserMetricsAction("WebView.Guest.ClearData"));
700   content::StoragePartition* partition =
701       content::BrowserContext::GetStoragePartition(
702           guest_web_contents()->GetBrowserContext(),
703           guest_web_contents()->GetSiteInstance());
704
705   if (!partition)
706     return false;
707
708   partition->ClearData(
709       removal_mask,
710       content::StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL,
711       GURL(),
712       content::StoragePartition::OriginMatcherFunction(),
713       remove_since,
714       base::Time::Now(),
715       callback);
716   return true;
717 }
718
719 WebViewGuest::~WebViewGuest() {
720 }
721
722 void WebViewGuest::DidCommitProvisionalLoadForFrame(
723     int64 frame_id,
724     const base::string16& frame_unique_name,
725     bool is_main_frame,
726     const GURL& url,
727     content::PageTransition transition_type,
728     content::RenderViewHost* render_view_host) {
729   find_helper_.CancelAllFindSessions();
730
731   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
732   args->SetString(guestview::kUrl, url.spec());
733   args->SetBoolean(guestview::kIsTopLevel, is_main_frame);
734   args->SetInteger(webview::kInternalCurrentEntryIndex,
735       guest_web_contents()->GetController().GetCurrentEntryIndex());
736   args->SetInteger(webview::kInternalEntryCount,
737       guest_web_contents()->GetController().GetEntryCount());
738   args->SetInteger(webview::kInternalProcessId,
739       guest_web_contents()->GetRenderProcessHost()->GetID());
740   DispatchEvent(
741       new GuestViewBase::Event(webview::kEventLoadCommit, args.Pass()));
742
743   // Update the current zoom factor for the new page.
744   current_zoom_factor_ = content::ZoomLevelToZoomFactor(
745       guest_web_contents()->GetZoomLevel());
746
747   if (is_main_frame) {
748     chromevox_injected_ = false;
749     main_frame_id_ = frame_id;
750   }
751 }
752
753 void WebViewGuest::DidFailProvisionalLoad(
754     int64 frame_id,
755     const base::string16& frame_unique_name,
756     bool is_main_frame,
757     const GURL& validated_url,
758     int error_code,
759     const base::string16& error_description,
760     content::RenderViewHost* render_view_host) {
761   // Translate the |error_code| into an error string.
762   std::string error_type;
763   base::RemoveChars(net::ErrorToString(error_code), "net::", &error_type);
764   LoadAbort(is_main_frame, validated_url, error_type);
765 }
766
767 void WebViewGuest::DidStartProvisionalLoadForFrame(
768     int64 frame_id,
769     int64 parent_frame_id,
770     bool is_main_frame,
771     const GURL& validated_url,
772     bool is_error_page,
773     bool is_iframe_srcdoc,
774     content::RenderViewHost* render_view_host) {
775   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
776   args->SetString(guestview::kUrl, validated_url.spec());
777   args->SetBoolean(guestview::kIsTopLevel, is_main_frame);
778   DispatchEvent(
779       new GuestViewBase::Event(webview::kEventLoadStart, args.Pass()));
780 }
781
782 void WebViewGuest::DocumentLoadedInFrame(
783     int64 frame_id,
784     content::RenderViewHost* render_view_host) {
785   if (frame_id == main_frame_id_)
786     InjectChromeVoxIfNeeded(render_view_host);
787 }
788
789 void WebViewGuest::DidStopLoading(content::RenderViewHost* render_view_host) {
790   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
791   DispatchEvent(new GuestViewBase::Event(webview::kEventLoadStop, args.Pass()));
792 }
793
794 void WebViewGuest::WebContentsDestroyed() {
795   // Clean up custom context menu items for this guest.
796   extensions::MenuManager* menu_manager = extensions::MenuManager::Get(
797       Profile::FromBrowserContext(browser_context()));
798   menu_manager->RemoveAllContextItems(extensions::MenuItem::ExtensionKey(
799       embedder_extension_id(), view_instance_id()));
800
801   RemoveWebViewFromExtensionRendererState(web_contents());
802 }
803
804 void WebViewGuest::UserAgentOverrideSet(const std::string& user_agent) {
805   content::NavigationController& controller =
806       guest_web_contents()->GetController();
807   content::NavigationEntry* entry = controller.GetVisibleEntry();
808   if (!entry)
809     return;
810   entry->SetIsOverridingUserAgent(!user_agent.empty());
811   if (!attached()) {
812     // We cannot reload now because all resource loads are suspended until
813     // attachment.
814     pending_reload_on_attachment_ = true;
815     return;
816   }
817   guest_web_contents()->GetController().Reload(false);
818 }
819
820 void WebViewGuest::LoadHandlerCalled() {
821   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
822   DispatchEvent(
823       new GuestViewBase::Event(webview::kEventContentLoad, args.Pass()));
824 }
825
826 void WebViewGuest::LoadRedirect(const GURL& old_url,
827                                 const GURL& new_url,
828                                 bool is_top_level) {
829   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
830   args->SetBoolean(guestview::kIsTopLevel, is_top_level);
831   args->SetString(webview::kNewURL, new_url.spec());
832   args->SetString(webview::kOldURL, old_url.spec());
833   DispatchEvent(
834       new GuestViewBase::Event(webview::kEventLoadRedirect, args.Pass()));
835 }
836
837 void WebViewGuest::AddWebViewToExtensionRendererState() {
838   const GURL& site_url = guest_web_contents()->GetSiteInstance()->GetSiteURL();
839   std::string partition_domain;
840   std::string partition_id;
841   bool in_memory;
842   if (!GetGuestPartitionConfigForSite(
843           site_url, &partition_domain, &partition_id, &in_memory)) {
844     NOTREACHED();
845     return;
846   }
847   DCHECK(embedder_extension_id() == partition_domain);
848
849   ExtensionRendererState::WebViewInfo webview_info;
850   webview_info.embedder_process_id = embedder_render_process_id();
851   webview_info.instance_id = view_instance_id();
852   webview_info.partition_id =  partition_id;
853   webview_info.embedder_extension_id = embedder_extension_id();
854
855   content::BrowserThread::PostTask(
856       content::BrowserThread::IO, FROM_HERE,
857       base::Bind(
858           &ExtensionRendererState::AddWebView,
859           base::Unretained(ExtensionRendererState::GetInstance()),
860           guest_web_contents()->GetRenderProcessHost()->GetID(),
861           guest_web_contents()->GetRoutingID(),
862           webview_info));
863 }
864
865 // static
866 void WebViewGuest::RemoveWebViewFromExtensionRendererState(
867     WebContents* web_contents) {
868   content::BrowserThread::PostTask(
869       content::BrowserThread::IO, FROM_HERE,
870       base::Bind(
871           &ExtensionRendererState::RemoveWebView,
872           base::Unretained(ExtensionRendererState::GetInstance()),
873           web_contents->GetRenderProcessHost()->GetID(),
874           web_contents->GetRoutingID()));
875 }
876
877 GURL WebViewGuest::ResolveURL(const std::string& src) {
878   if (!in_extension()) {
879     NOTREACHED();
880     return GURL(src);
881   }
882
883   GURL default_url(base::StringPrintf("%s://%s/",
884                                       extensions::kExtensionScheme,
885                                       embedder_extension_id().c_str()));
886   return default_url.Resolve(src);
887 }
888
889 void WebViewGuest::SizeChanged(const gfx::Size& old_size,
890                                const gfx::Size& new_size) {
891   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
892   args->SetInteger(webview::kOldHeight, old_size.height());
893   args->SetInteger(webview::kOldWidth, old_size.width());
894   args->SetInteger(webview::kNewHeight, new_size.height());
895   args->SetInteger(webview::kNewWidth, new_size.width());
896   DispatchEvent(
897       new GuestViewBase::Event(webview::kEventSizeChanged, args.Pass()));
898 }
899
900 void WebViewGuest::RequestMediaAccessPermission(
901     const content::MediaStreamRequest& request,
902     const content::MediaResponseCallback& callback) {
903   base::DictionaryValue request_info;
904   request_info.Set(
905       guestview::kUrl,
906       base::Value::CreateStringValue(request.security_origin.spec()));
907   RequestPermission(static_cast<BrowserPluginPermissionType>(
908                         WEB_VIEW_PERMISSION_TYPE_MEDIA),
909                     request_info,
910                     base::Bind(&WebViewGuest::OnWebViewMediaPermissionResponse,
911                                base::Unretained(this),
912                                request,
913                                callback),
914                     false /* allowed_by_default */);
915 }
916
917 void WebViewGuest::CanDownload(
918     const std::string& request_method,
919     const GURL& url,
920     const base::Callback<void(bool)>& callback) {
921   base::DictionaryValue request_info;
922   request_info.Set(
923       guestview::kUrl,
924       base::Value::CreateStringValue(url.spec()));
925   RequestPermission(
926       static_cast<BrowserPluginPermissionType>(
927           WEB_VIEW_PERMISSION_TYPE_DOWNLOAD),
928       request_info,
929       base::Bind(&WebViewGuest::OnWebViewDownloadPermissionResponse,
930                  base::Unretained(this),
931                  callback),
932       false /* allowed_by_default */);
933 }
934
935 void WebViewGuest::RequestPointerLockPermission(
936     bool user_gesture,
937     bool last_unlocked_by_target,
938     const base::Callback<void(bool)>& callback) {
939   base::DictionaryValue request_info;
940   request_info.Set(guestview::kUserGesture,
941                    base::Value::CreateBooleanValue(user_gesture));
942   request_info.Set(webview::kLastUnlockedBySelf,
943                    base::Value::CreateBooleanValue(last_unlocked_by_target));
944   request_info.Set(guestview::kUrl,
945                    base::Value::CreateStringValue(
946                        guest_web_contents()->GetLastCommittedURL().spec()));
947
948   RequestPermission(
949       static_cast<BrowserPluginPermissionType>(
950           WEB_VIEW_PERMISSION_TYPE_POINTER_LOCK),
951       request_info,
952       base::Bind(&WebViewGuest::OnWebViewPointerLockPermissionResponse,
953                  base::Unretained(this),
954                  callback),
955       false /* allowed_by_default */);
956 }
957
958 content::JavaScriptDialogManager*
959     WebViewGuest::GetJavaScriptDialogManager() {
960   return &javascript_dialog_helper_;
961 }
962
963 #if defined(OS_CHROMEOS)
964 void WebViewGuest::OnAccessibilityStatusChanged(
965     const chromeos::AccessibilityStatusEventDetails& details) {
966   if (details.notification_type == chromeos::ACCESSIBILITY_MANAGER_SHUTDOWN) {
967     accessibility_subscription_.reset();
968   } else if (details.notification_type ==
969       chromeos::ACCESSIBILITY_TOGGLE_SPOKEN_FEEDBACK) {
970     if (details.enabled)
971       InjectChromeVoxIfNeeded(guest_web_contents()->GetRenderViewHost());
972     else
973       chromevox_injected_ = false;
974   }
975 }
976 #endif
977
978 void WebViewGuest::InjectChromeVoxIfNeeded(
979     content::RenderViewHost* render_view_host) {
980 #if defined(OS_CHROMEOS)
981   if (!chromevox_injected_) {
982     chromeos::AccessibilityManager* manager =
983         chromeos::AccessibilityManager::Get();
984     if (manager && manager->IsSpokenFeedbackEnabled()) {
985       manager->InjectChromeVox(render_view_host);
986       chromevox_injected_ = true;
987     }
988   }
989 #endif
990 }
991
992 int WebViewGuest::RemoveBridgeID(int bridge_id) {
993   std::map<int, int>::iterator bridge_itr =
994       bridge_id_to_request_id_map_.find(bridge_id);
995   if (bridge_itr == bridge_id_to_request_id_map_.end())
996     return webview::kInvalidPermissionRequestID;
997
998   int request_id = bridge_itr->second;
999   bridge_id_to_request_id_map_.erase(bridge_itr);
1000   return request_id;
1001 }
1002
1003 int WebViewGuest::RequestPermissionInternal(
1004     BrowserPluginPermissionType permission_type,
1005     const base::DictionaryValue& request_info,
1006     const PermissionResponseCallback& callback,
1007     bool allowed_by_default) {
1008   // If there are too many pending permission requests then reject this request.
1009   if (pending_permission_requests_.size() >=
1010       webview::kMaxOutstandingPermissionRequests) {
1011     // Let the stack unwind before we deny the permission request so that
1012     // objects held by the permission request are not destroyed immediately
1013     // after creation. This is to allow those same objects to be accessed again
1014     // in the same scope without fear of use after freeing.
1015     base::MessageLoop::current()->PostTask(
1016         FROM_HERE,
1017         base::Bind(&PermissionResponseCallback::Run,
1018                   base::Owned(new PermissionResponseCallback(callback)),
1019                   allowed_by_default,
1020                   std::string()));
1021     return webview::kInvalidPermissionRequestID;
1022   }
1023
1024   int request_id = next_permission_request_id_++;
1025   pending_permission_requests_[request_id] =
1026       PermissionResponseInfo(callback, permission_type, allowed_by_default);
1027   scoped_ptr<base::DictionaryValue> args(request_info.DeepCopy());
1028   args->SetInteger(webview::kRequestId, request_id);
1029   switch (static_cast<int>(permission_type)) {
1030     case BROWSER_PLUGIN_PERMISSION_TYPE_NEW_WINDOW: {
1031       DispatchEvent(
1032           new GuestViewBase::Event(webview::kEventNewWindow, args.Pass()));
1033       break;
1034     }
1035     case WEB_VIEW_PERMISSION_TYPE_JAVASCRIPT_DIALOG: {
1036       DispatchEvent(
1037           new GuestViewBase::Event(webview::kEventDialog, args.Pass()));
1038       break;
1039     }
1040     default: {
1041       args->SetString(webview::kPermission,
1042                       PermissionTypeToString(permission_type));
1043       DispatchEvent(new GuestViewBase::Event(webview::kEventPermissionRequest,
1044                                              args.Pass()));
1045       break;
1046     }
1047   }
1048   return request_id;
1049 }
1050
1051 WebViewGuest::PermissionResponseInfo::PermissionResponseInfo()
1052     : permission_type(BROWSER_PLUGIN_PERMISSION_TYPE_UNKNOWN),
1053       allowed_by_default(false) {
1054 }
1055
1056 WebViewGuest::PermissionResponseInfo::PermissionResponseInfo(
1057     const PermissionResponseCallback& callback,
1058     BrowserPluginPermissionType permission_type,
1059     bool allowed_by_default)
1060     : callback(callback),
1061       permission_type(permission_type),
1062       allowed_by_default(allowed_by_default) {
1063 }
1064
1065 WebViewGuest::PermissionResponseInfo::~PermissionResponseInfo() {
1066 }
1067
1068 void WebViewGuest::ShowContextMenu(int request_id,
1069                                    const MenuItemVector* items) {
1070   if (!pending_menu_.get())
1071     return;
1072
1073   // Make sure this was the correct request.
1074   if (request_id != pending_context_menu_request_id_)
1075     return;
1076
1077   // TODO(lazyboy): Implement.
1078   DCHECK(!items);
1079
1080   ContextMenuDelegate* menu_delegate =
1081       ContextMenuDelegate::FromWebContents(guest_web_contents());
1082   menu_delegate->ShowMenu(pending_menu_.Pass());
1083 }