Upstream version 10.38.220.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 "base/strings/utf_string_conversions.h"
10 #include "chrome/browser/chrome_notification_types.h"
11 #include "chrome/browser/extensions/api/web_request/web_request_api.h"
12 #include "chrome/browser/extensions/api/web_view/web_view_internal_api.h"
13 #include "chrome/browser/extensions/chrome_extension_web_contents_observer.h"
14 #include "chrome/browser/extensions/menu_manager.h"
15 #include "chrome/browser/favicon/favicon_tab_helper.h"
16 #include "chrome/browser/guest_view/web_view/web_view_constants.h"
17 #include "chrome/browser/guest_view/web_view/web_view_permission_helper.h"
18 #include "chrome/browser/guest_view/web_view/web_view_permission_types.h"
19 #include "chrome/browser/guest_view/web_view/web_view_renderer_state.h"
20 #include "chrome/browser/renderer_context_menu/render_view_context_menu.h"
21 #include "chrome/browser/ui/pdf/pdf_tab_helper.h"
22 #include "chrome/browser/ui/zoom/zoom_controller.h"
23 #include "chrome/common/chrome_version_info.h"
24 #include "chrome/common/extensions/chrome_extension_messages.h"
25 #include "chrome/common/render_messages.h"
26 #include "components/renderer_context_menu/context_menu_delegate.h"
27 #include "content/public/browser/browser_thread.h"
28 #include "content/public/browser/child_process_security_policy.h"
29 #include "content/public/browser/native_web_keyboard_event.h"
30 #include "content/public/browser/navigation_entry.h"
31 #include "content/public/browser/notification_details.h"
32 #include "content/public/browser/notification_service.h"
33 #include "content/public/browser/notification_source.h"
34 #include "content/public/browser/notification_types.h"
35 #include "content/public/browser/render_process_host.h"
36 #include "content/public/browser/render_view_host.h"
37 #include "content/public/browser/resource_request_details.h"
38 #include "content/public/browser/site_instance.h"
39 #include "content/public/browser/storage_partition.h"
40 #include "content/public/browser/user_metrics.h"
41 #include "content/public/browser/web_contents.h"
42 #include "content/public/browser/web_contents_delegate.h"
43 #include "content/public/common/media_stream_request.h"
44 #include "content/public/common/page_zoom.h"
45 #include "content/public/common/result_codes.h"
46 #include "content/public/common/stop_find_action.h"
47 #include "content/public/common/url_constants.h"
48 #include "extensions/browser/extension_system.h"
49 #include "extensions/browser/guest_view/guest_view_constants.h"
50 #include "extensions/browser/guest_view/guest_view_manager.h"
51 #include "extensions/common/constants.h"
52 #include "ipc/ipc_message_macros.h"
53 #include "net/base/escape.h"
54 #include "net/base/net_errors.h"
55 #include "third_party/WebKit/public/web/WebFindOptions.h"
56 #include "ui/base/models/simple_menu_model.h"
57
58 #if defined(ENABLE_PRINTING)
59 #if defined(ENABLE_FULL_PRINTING)
60 #include "chrome/browser/printing/print_preview_message_handler.h"
61 #include "chrome/browser/printing/print_view_manager.h"
62 #else
63 #include "chrome/browser/printing/print_view_manager_basic.h"
64 #endif  // defined(ENABLE_FULL_PRINTING)
65 #endif  // defined(ENABLE_PRINTING)
66
67 #if defined(OS_CHROMEOS)
68 #include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
69 #endif
70
71 using base::UserMetricsAction;
72 using content::RenderFrameHost;
73 using content::ResourceType;
74 using content::WebContents;
75
76 namespace extensions {
77
78 namespace {
79
80 std::string WindowOpenDispositionToString(
81   WindowOpenDisposition window_open_disposition) {
82   switch (window_open_disposition) {
83     case IGNORE_ACTION:
84       return "ignore";
85     case SAVE_TO_DISK:
86       return "save_to_disk";
87     case CURRENT_TAB:
88       return "current_tab";
89     case NEW_BACKGROUND_TAB:
90       return "new_background_tab";
91     case NEW_FOREGROUND_TAB:
92       return "new_foreground_tab";
93     case NEW_WINDOW:
94       return "new_window";
95     case NEW_POPUP:
96       return "new_popup";
97     default:
98       NOTREACHED() << "Unknown Window Open Disposition";
99       return "ignore";
100   }
101 }
102
103 static std::string TerminationStatusToString(base::TerminationStatus status) {
104   switch (status) {
105     case base::TERMINATION_STATUS_NORMAL_TERMINATION:
106       return "normal";
107     case base::TERMINATION_STATUS_ABNORMAL_TERMINATION:
108     case base::TERMINATION_STATUS_STILL_RUNNING:
109       return "abnormal";
110     case base::TERMINATION_STATUS_PROCESS_WAS_KILLED:
111       return "killed";
112     case base::TERMINATION_STATUS_PROCESS_CRASHED:
113       return "crashed";
114     case base::TERMINATION_STATUS_MAX_ENUM:
115       break;
116   }
117   NOTREACHED() << "Unknown Termination Status.";
118   return "unknown";
119 }
120
121 std::string GetStoragePartitionIdFromSiteURL(const GURL& site_url) {
122   const std::string& partition_id = site_url.query();
123   bool persist_storage = site_url.path().find("persist") != std::string::npos;
124   return (persist_storage ? webview::kPersistPrefix : "") + partition_id;
125 }
126
127 void RemoveWebViewEventListenersOnIOThread(
128     void* profile,
129     const std::string& extension_id,
130     int embedder_process_id,
131     int view_instance_id) {
132   DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
133   ExtensionWebRequestEventRouter::GetInstance()->RemoveWebViewEventListeners(
134       profile,
135       extension_id,
136       embedder_process_id,
137       view_instance_id);
138 }
139
140 void ParsePartitionParam(const base::DictionaryValue& create_params,
141                          std::string* storage_partition_id,
142                          bool* persist_storage) {
143   std::string partition_str;
144   if (!create_params.GetString(webview::kStoragePartitionId, &partition_str)) {
145     return;
146   }
147
148   // Since the "persist:" prefix is in ASCII, StartsWith will work fine on
149   // UTF-8 encoded |partition_id|. If the prefix is a match, we can safely
150   // remove the prefix without splicing in the middle of a multi-byte codepoint.
151   // We can use the rest of the string as UTF-8 encoded one.
152   if (StartsWithASCII(partition_str, "persist:", true)) {
153     size_t index = partition_str.find(":");
154     CHECK(index != std::string::npos);
155     // It is safe to do index + 1, since we tested for the full prefix above.
156     *storage_partition_id = partition_str.substr(index + 1);
157
158     if (storage_partition_id->empty()) {
159       // TODO(lazyboy): Better way to deal with this error.
160       return;
161     }
162     *persist_storage = true;
163   } else {
164     *storage_partition_id = partition_str;
165     *persist_storage = false;
166   }
167 }
168
169 }  // namespace
170
171 // static
172 GuestViewBase* WebViewGuest::Create(content::BrowserContext* browser_context,
173                                     int guest_instance_id) {
174   return new WebViewGuest(browser_context, guest_instance_id);
175 }
176
177 // static
178 bool WebViewGuest::GetGuestPartitionConfigForSite(
179     const GURL& site,
180     std::string* partition_domain,
181     std::string* partition_name,
182     bool* in_memory) {
183   if (!site.SchemeIs(content::kGuestScheme))
184     return false;
185
186   // Since guest URLs are only used for packaged apps, there must be an app
187   // id in the URL.
188   CHECK(site.has_host());
189   *partition_domain = site.host();
190   // Since persistence is optional, the path must either be empty or the
191   // literal string.
192   *in_memory = (site.path() != "/persist");
193   // The partition name is user supplied value, which we have encoded when the
194   // URL was created, so it needs to be decoded.
195   *partition_name =
196       net::UnescapeURLComponent(site.query(), net::UnescapeRule::NORMAL);
197   return true;
198 }
199
200 // static
201 const char WebViewGuest::Type[] = "webview";
202
203 // static
204 int WebViewGuest::GetViewInstanceId(WebContents* contents) {
205   WebViewGuest* guest = FromWebContents(contents);
206   if (!guest)
207     return guestview::kInstanceIDNone;
208
209   return guest->view_instance_id();
210 }
211
212 // static
213 scoped_ptr<base::ListValue> WebViewGuest::MenuModelToValue(
214     const ui::SimpleMenuModel& menu_model) {
215   scoped_ptr<base::ListValue> items(new base::ListValue());
216   for (int i = 0; i < menu_model.GetItemCount(); ++i) {
217     base::DictionaryValue* item_value = new base::DictionaryValue();
218     // TODO(lazyboy): We need to expose some kind of enum equivalent of
219     // |command_id| instead of plain integers.
220     item_value->SetInteger(webview::kMenuItemCommandId,
221                            menu_model.GetCommandIdAt(i));
222     item_value->SetString(webview::kMenuItemLabel, menu_model.GetLabelAt(i));
223     items->Append(item_value);
224   }
225   return items.Pass();
226 }
227
228 const char* WebViewGuest::GetAPINamespace() {
229   return webview::kAPINamespace;
230 }
231
232 void WebViewGuest::CreateWebContents(
233     const std::string& embedder_extension_id,
234     int embedder_render_process_id,
235     const base::DictionaryValue& create_params,
236     const WebContentsCreatedCallback& callback) {
237   content::RenderProcessHost* embedder_render_process_host =
238       content::RenderProcessHost::FromID(embedder_render_process_id);
239   std::string storage_partition_id;
240   bool persist_storage = false;
241   std::string storage_partition_string;
242   ParsePartitionParam(create_params, &storage_partition_id, &persist_storage);
243   // Validate that the partition id coming from the renderer is valid UTF-8,
244   // since we depend on this in other parts of the code, such as FilePath
245   // creation. If the validation fails, treat it as a bad message and kill the
246   // renderer process.
247   if (!base::IsStringUTF8(storage_partition_id)) {
248     content::RecordAction(
249         base::UserMetricsAction("BadMessageTerminate_BPGM"));
250     base::KillProcess(
251         embedder_render_process_host->GetHandle(),
252         content::RESULT_CODE_KILLED_BAD_MESSAGE, false);
253     callback.Run(NULL);
254     return;
255   }
256   std::string url_encoded_partition = net::EscapeQueryParamValue(
257       storage_partition_id, false);
258   // The SiteInstance of a given webview tag is based on the fact that it's
259   // a guest process in addition to which platform application the tag
260   // belongs to and what storage partition is in use, rather than the URL
261   // that the tag is being navigated to.
262   GURL guest_site(base::StringPrintf("%s://%s/%s?%s",
263                                      content::kGuestScheme,
264                                      embedder_extension_id.c_str(),
265                                      persist_storage ? "persist" : "",
266                                      url_encoded_partition.c_str()));
267
268   // If we already have a webview tag in the same app using the same storage
269   // partition, we should use the same SiteInstance so the existing tag and
270   // the new tag can script each other.
271   GuestViewManager* guest_view_manager =
272       GuestViewManager::FromBrowserContext(
273           embedder_render_process_host->GetBrowserContext());
274   content::SiteInstance* guest_site_instance =
275       guest_view_manager->GetGuestSiteInstance(guest_site);
276   if (!guest_site_instance) {
277     // Create the SiteInstance in a new BrowsingInstance, which will ensure
278     // that webview tags are also not allowed to send messages across
279     // different partitions.
280     guest_site_instance = content::SiteInstance::CreateForURL(
281         embedder_render_process_host->GetBrowserContext(), guest_site);
282   }
283   WebContents::CreateParams params(
284       embedder_render_process_host->GetBrowserContext(),
285       guest_site_instance);
286   params.guest_delegate = this;
287   callback.Run(WebContents::Create(params));
288 }
289
290 void WebViewGuest::DidAttachToEmbedder() {
291   SetUpAutoSize();
292
293   std::string name;
294   if (extra_params()->GetString(webview::kName, &name)) {
295     // If the guest window's name is empty, then the WebView tag's name is
296     // assigned. Otherwise, the guest window's name takes precedence over the
297     // WebView tag's name.
298     if (name_.empty())
299       name_ = name;
300   }
301   ReportFrameNameChange(name_);
302
303   std::string user_agent_override;
304   if (extra_params()->GetString(webview::kParameterUserAgentOverride,
305                                 &user_agent_override)) {
306     SetUserAgentOverride(user_agent_override);
307   } else {
308     SetUserAgentOverride("");
309   }
310
311   std::string src;
312   if (extra_params()->GetString("src", &src) && !src.empty())
313     NavigateGuest(src);
314
315   if (GetOpener()) {
316     // We need to do a navigation here if the target URL has changed between
317     // the time the WebContents was created and the time it was attached.
318     // We also need to do an initial navigation if a RenderView was never
319     // created for the new window in cases where there is no referrer.
320     PendingWindowMap::iterator it =
321         GetOpener()->pending_new_windows_.find(this);
322     if (it != GetOpener()->pending_new_windows_.end()) {
323       const NewWindowInfo& new_window_info = it->second;
324       if (new_window_info.changed || !guest_web_contents()->HasOpener())
325         NavigateGuest(new_window_info.url.spec());
326     } else {
327       NOTREACHED();
328     }
329
330     // Once a new guest is attached to the DOM of the embedder page, then the
331     // lifetime of the new guest is no longer managed by the opener guest.
332     GetOpener()->pending_new_windows_.erase(this);
333   }
334
335   ZoomController* zoom_controller = ZoomController::FromWebContents(
336       embedder_web_contents());
337   if (!zoom_controller)
338     return;
339   // Listen to the embedder's zoom changes.
340   zoom_controller->AddObserver(this);
341   // Set the guest's initial zoom level to be equal to the embedder's.
342   ZoomController::FromWebContents(guest_web_contents())->
343       SetZoomLevel(zoom_controller->GetZoomLevel());
344 }
345
346 void WebViewGuest::DidInitialize() {
347   script_executor_.reset(
348       new ScriptExecutor(guest_web_contents(), &script_observers_));
349
350   notification_registrar_.Add(
351       this, content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
352       content::Source<WebContents>(guest_web_contents()));
353
354   notification_registrar_.Add(
355       this, content::NOTIFICATION_RESOURCE_RECEIVED_REDIRECT,
356       content::Source<WebContents>(guest_web_contents()));
357
358 #if defined(OS_CHROMEOS)
359   chromeos::AccessibilityManager* accessibility_manager =
360       chromeos::AccessibilityManager::Get();
361   CHECK(accessibility_manager);
362   accessibility_subscription_ = accessibility_manager->RegisterCallback(
363       base::Bind(&WebViewGuest::OnAccessibilityStatusChanged,
364                  base::Unretained(this)));
365 #endif
366
367   AttachWebViewHelpers(guest_web_contents());
368 }
369
370 void WebViewGuest::AttachWebViewHelpers(WebContents* contents) {
371   // Create a zoom controller for the guest contents give it access to
372   // GetZoomLevel() and and SetZoomLevel() in WebViewGuest.
373   // TODO(wjmaclean) This currently uses the same HostZoomMap as the browser
374   // context, but we eventually want to isolate the guest contents from zoom
375   // changes outside the guest (e.g. in the main browser), so we should
376   // create a separate HostZoomMap for the guest.
377   ZoomController::CreateForWebContents(contents);
378
379   FaviconTabHelper::CreateForWebContents(contents);
380   ChromeExtensionWebContentsObserver::CreateForWebContents(contents);
381 #if defined(ENABLE_PRINTING)
382 #if defined(ENABLE_FULL_PRINTING)
383   printing::PrintViewManager::CreateForWebContents(contents);
384   printing::PrintPreviewMessageHandler::CreateForWebContents(contents);
385 #else
386   printing::PrintViewManagerBasic::CreateForWebContents(contents);
387 #endif  // defined(ENABLE_FULL_PRINTING)
388 #endif  // defined(ENABLE_PRINTING)
389   PDFTabHelper::CreateForWebContents(contents);
390   web_view_permission_helper_.reset(new WebViewPermissionHelper(this));
391 }
392
393 void WebViewGuest::DidStopLoading() {
394   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
395   DispatchEventToEmbedder(
396       new GuestViewBase::Event(webview::kEventLoadStop, args.Pass()));
397 }
398
399 void WebViewGuest::EmbedderDestroyed() {
400   // TODO(fsamuel): WebRequest event listeners for <webview> should survive
401   // reparenting of a <webview> within a single embedder. Right now, we keep
402   // around the browser state for the listener for the lifetime of the embedder.
403   // Ideally, the lifetime of the listeners should match the lifetime of the
404   // <webview> DOM node. Once http://crbug.com/156219 is resolved we can move
405   // the call to RemoveWebViewEventListenersOnIOThread back to
406   // WebViewGuest::WebContentsDestroyed.
407   content::BrowserThread::PostTask(
408       content::BrowserThread::IO,
409       FROM_HERE,
410       base::Bind(
411           &RemoveWebViewEventListenersOnIOThread,
412           browser_context(), embedder_extension_id(),
413           embedder_render_process_id(),
414           view_instance_id()));
415 }
416
417 void WebViewGuest::GuestDestroyed() {
418   // Clean up custom context menu items for this guest.
419   MenuManager* menu_manager = MenuManager::Get(
420       Profile::FromBrowserContext(browser_context()));
421   menu_manager->RemoveAllContextItems(MenuItem::ExtensionKey(
422       embedder_extension_id(), view_instance_id()));
423
424   RemoveWebViewStateFromIOThread(web_contents());
425 }
426
427 void WebViewGuest::GuestReady() {
428   // The guest RenderView should always live in an isolated guest process.
429   CHECK(guest_web_contents()->GetRenderProcessHost()->IsIsolatedGuest());
430   Send(new ChromeViewMsg_SetName(guest_web_contents()->GetRoutingID(), name_));
431 }
432
433 void WebViewGuest::GuestSizeChangedDueToAutoSize(const gfx::Size& old_size,
434                                                  const gfx::Size& new_size) {
435   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
436   args->SetInteger(webview::kOldHeight, old_size.height());
437   args->SetInteger(webview::kOldWidth, old_size.width());
438   args->SetInteger(webview::kNewHeight, new_size.height());
439   args->SetInteger(webview::kNewWidth, new_size.width());
440   DispatchEventToEmbedder(
441       new GuestViewBase::Event(webview::kEventSizeChanged, args.Pass()));
442 }
443
444 bool WebViewGuest::IsAutoSizeSupported() const {
445   return true;
446 }
447
448 bool WebViewGuest::IsDragAndDropEnabled() const {
449   return true;
450 }
451
452 void WebViewGuest::WillDestroy() {
453   if (!attached() && GetOpener())
454     GetOpener()->pending_new_windows_.erase(this);
455   DestroyUnattachedWindows();
456 }
457
458 bool WebViewGuest::AddMessageToConsole(WebContents* source,
459                                        int32 level,
460                                        const base::string16& message,
461                                        int32 line_no,
462                                        const base::string16& source_id) {
463   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
464   // Log levels are from base/logging.h: LogSeverity.
465   args->SetInteger(webview::kLevel, level);
466   args->SetString(webview::kMessage, message);
467   args->SetInteger(webview::kLine, line_no);
468   args->SetString(webview::kSourceId, source_id);
469   DispatchEventToEmbedder(
470       new GuestViewBase::Event(webview::kEventConsoleMessage, args.Pass()));
471   return true;
472 }
473
474 void WebViewGuest::CloseContents(WebContents* source) {
475   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
476   DispatchEventToEmbedder(
477       new GuestViewBase::Event(webview::kEventClose, args.Pass()));
478 }
479
480 void WebViewGuest::FindReply(WebContents* source,
481                              int request_id,
482                              int number_of_matches,
483                              const gfx::Rect& selection_rect,
484                              int active_match_ordinal,
485                              bool final_update) {
486   find_helper_.FindReply(request_id, number_of_matches, selection_rect,
487                          active_match_ordinal, final_update);
488 }
489
490 bool WebViewGuest::HandleContextMenu(
491     const content::ContextMenuParams& params) {
492   ContextMenuDelegate* menu_delegate =
493       ContextMenuDelegate::FromWebContents(guest_web_contents());
494   DCHECK(menu_delegate);
495
496   pending_menu_ = menu_delegate->BuildMenu(guest_web_contents(), params);
497
498   // Pass it to embedder.
499   int request_id = ++pending_context_menu_request_id_;
500   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
501   scoped_ptr<base::ListValue> items =
502       MenuModelToValue(pending_menu_->menu_model());
503   args->Set(webview::kContextMenuItems, items.release());
504   args->SetInteger(webview::kRequestId, request_id);
505   DispatchEventToEmbedder(
506       new GuestViewBase::Event(webview::kEventContextMenu, args.Pass()));
507   return true;
508 }
509
510 void WebViewGuest::HandleKeyboardEvent(
511     WebContents* source,
512     const content::NativeWebKeyboardEvent& event) {
513   if (!attached())
514     return;
515
516   if (HandleKeyboardShortcuts(event))
517     return;
518
519   // Send the unhandled keyboard events back to the embedder to reprocess them.
520   // TODO(fsamuel): This introduces the possibility of out-of-order keyboard
521   // events because the guest may be arbitrarily delayed when responding to
522   // keyboard events. In that time, the embedder may have received and processed
523   // additional key events. This needs to be fixed as soon as possible.
524   // See http://crbug.com/229882.
525   embedder_web_contents()->GetDelegate()->HandleKeyboardEvent(
526       web_contents(), event);
527 }
528
529 void WebViewGuest::LoadProgressChanged(content::WebContents* source,
530                                        double progress) {
531   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
532   args->SetString(guestview::kUrl, guest_web_contents()->GetURL().spec());
533   args->SetDouble(webview::kProgress, progress);
534   DispatchEventToEmbedder(
535       new GuestViewBase::Event(webview::kEventLoadProgress, args.Pass()));
536 }
537
538 void WebViewGuest::LoadAbort(bool is_top_level,
539                              const GURL& url,
540                              const std::string& error_type) {
541   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
542   args->SetBoolean(guestview::kIsTopLevel, is_top_level);
543   args->SetString(guestview::kUrl, url.possibly_invalid_spec());
544   args->SetString(guestview::kReason, error_type);
545   DispatchEventToEmbedder(
546       new GuestViewBase::Event(webview::kEventLoadAbort, args.Pass()));
547 }
548
549 void WebViewGuest::OnUpdateFrameName(bool is_top_level,
550                                      const std::string& name) {
551   if (!is_top_level)
552     return;
553
554   if (name_ == name)
555     return;
556
557   ReportFrameNameChange(name);
558 }
559
560 void WebViewGuest::CreateNewGuestWebViewWindow(
561     const content::OpenURLParams& params) {
562   GuestViewManager* guest_manager =
563       GuestViewManager::FromBrowserContext(browser_context());
564   // Set the attach params to use the same partition as the opener.
565   // We pull the partition information from the site's URL, which is of the
566   // form guest://site/{persist}?{partition_name}.
567   const GURL& site_url = guest_web_contents()->GetSiteInstance()->GetSiteURL();
568   const std::string storage_partition_id =
569       GetStoragePartitionIdFromSiteURL(site_url);
570   base::DictionaryValue create_params;
571   create_params.SetString(webview::kStoragePartitionId, storage_partition_id);
572
573   guest_manager->CreateGuest(WebViewGuest::Type,
574                              embedder_extension_id(),
575                              embedder_web_contents(),
576                              create_params,
577                              base::Bind(&WebViewGuest::NewGuestWebViewCallback,
578                                         base::Unretained(this),
579                                         params));
580 }
581
582 void WebViewGuest::NewGuestWebViewCallback(
583     const content::OpenURLParams& params,
584     content::WebContents* guest_web_contents) {
585   WebViewGuest* new_guest = WebViewGuest::FromWebContents(guest_web_contents);
586   new_guest->SetOpener(this);
587
588   // Take ownership of |new_guest|.
589   pending_new_windows_.insert(
590       std::make_pair(new_guest, NewWindowInfo(params.url, std::string())));
591
592   // Request permission to show the new window.
593   RequestNewWindowPermission(params.disposition, gfx::Rect(),
594                              params.user_gesture,
595                              new_guest->guest_web_contents());
596 }
597
598 // TODO(fsamuel): Find a reliable way to test the 'responsive' and
599 // 'unresponsive' events.
600 void WebViewGuest::RendererResponsive(content::WebContents* source) {
601   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
602   args->SetInteger(webview::kProcessId,
603       guest_web_contents()->GetRenderProcessHost()->GetID());
604   DispatchEventToEmbedder(
605       new GuestViewBase::Event(webview::kEventResponsive, args.Pass()));
606 }
607
608 void WebViewGuest::RendererUnresponsive(content::WebContents* source) {
609   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
610   args->SetInteger(webview::kProcessId,
611       guest_web_contents()->GetRenderProcessHost()->GetID());
612   DispatchEventToEmbedder(
613       new GuestViewBase::Event(webview::kEventUnresponsive, args.Pass()));
614 }
615
616 void WebViewGuest::Observe(int type,
617                            const content::NotificationSource& source,
618                            const content::NotificationDetails& details) {
619   switch (type) {
620     case content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME: {
621       DCHECK_EQ(content::Source<WebContents>(source).ptr(),
622                 guest_web_contents());
623       if (content::Source<WebContents>(source).ptr() == guest_web_contents())
624         LoadHandlerCalled();
625       break;
626     }
627     case content::NOTIFICATION_RESOURCE_RECEIVED_REDIRECT: {
628       DCHECK_EQ(content::Source<WebContents>(source).ptr(),
629                 guest_web_contents());
630       content::ResourceRedirectDetails* resource_redirect_details =
631           content::Details<content::ResourceRedirectDetails>(details).ptr();
632       bool is_top_level = resource_redirect_details->resource_type ==
633                           content::RESOURCE_TYPE_MAIN_FRAME;
634       LoadRedirect(resource_redirect_details->url,
635                    resource_redirect_details->new_url,
636                    is_top_level);
637       break;
638     }
639     default:
640       NOTREACHED() << "Unexpected notification sent.";
641       break;
642   }
643 }
644
645 double WebViewGuest::GetZoom() {
646   return current_zoom_factor_;
647 }
648
649 void WebViewGuest::Find(
650     const base::string16& search_text,
651     const blink::WebFindOptions& options,
652     scoped_refptr<WebViewInternalFindFunction> find_function) {
653   find_helper_.Find(guest_web_contents(), search_text, options, find_function);
654 }
655
656 void WebViewGuest::StopFinding(content::StopFindAction action) {
657   find_helper_.CancelAllFindSessions();
658   guest_web_contents()->StopFinding(action);
659 }
660
661 void WebViewGuest::Go(int relative_index) {
662   guest_web_contents()->GetController().GoToOffset(relative_index);
663 }
664
665 void WebViewGuest::Reload() {
666   // TODO(fsamuel): Don't check for repost because we don't want to show
667   // Chromium's repost warning. We might want to implement a separate API
668   // for registering a callback if a repost is about to happen.
669   guest_web_contents()->GetController().Reload(false);
670 }
671
672 void WebViewGuest::SetUserAgentOverride(
673     const std::string& user_agent_override) {
674   if (!attached())
675     return;
676   is_overriding_user_agent_ = !user_agent_override.empty();
677   if (is_overriding_user_agent_) {
678     content::RecordAction(UserMetricsAction("WebView.Guest.OverrideUA"));
679   }
680   guest_web_contents()->SetUserAgentOverride(user_agent_override);
681 }
682
683 void WebViewGuest::Stop() {
684   guest_web_contents()->Stop();
685 }
686
687 void WebViewGuest::Terminate() {
688   content::RecordAction(UserMetricsAction("WebView.Guest.Terminate"));
689   base::ProcessHandle process_handle =
690       guest_web_contents()->GetRenderProcessHost()->GetHandle();
691   if (process_handle)
692     base::KillProcess(process_handle, content::RESULT_CODE_KILLED, false);
693 }
694
695 bool WebViewGuest::ClearData(const base::Time remove_since,
696                              uint32 removal_mask,
697                              const base::Closure& callback) {
698   content::RecordAction(UserMetricsAction("WebView.Guest.ClearData"));
699   content::StoragePartition* partition =
700       content::BrowserContext::GetStoragePartition(
701           guest_web_contents()->GetBrowserContext(),
702           guest_web_contents()->GetSiteInstance());
703
704   if (!partition)
705     return false;
706
707   partition->ClearData(
708       removal_mask,
709       content::StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL,
710       GURL(),
711       content::StoragePartition::OriginMatcherFunction(),
712       remove_since,
713       base::Time::Now(),
714       callback);
715   return true;
716 }
717
718 WebViewGuest::WebViewGuest(content::BrowserContext* browser_context,
719                            int guest_instance_id)
720     : GuestView<WebViewGuest>(browser_context, guest_instance_id),
721       pending_context_menu_request_id_(0),
722       is_overriding_user_agent_(false),
723       chromevox_injected_(false),
724       current_zoom_factor_(1.0),
725       find_helper_(this),
726       javascript_dialog_helper_(this) {
727 }
728
729 WebViewGuest::~WebViewGuest() {
730 }
731
732 void WebViewGuest::DidCommitProvisionalLoadForFrame(
733     content::RenderFrameHost* render_frame_host,
734     const GURL& url,
735     content::PageTransition transition_type) {
736   find_helper_.CancelAllFindSessions();
737
738   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
739   args->SetString(guestview::kUrl, url.spec());
740   args->SetBoolean(guestview::kIsTopLevel, !render_frame_host->GetParent());
741   args->SetInteger(webview::kInternalCurrentEntryIndex,
742       guest_web_contents()->GetController().GetCurrentEntryIndex());
743   args->SetInteger(webview::kInternalEntryCount,
744       guest_web_contents()->GetController().GetEntryCount());
745   args->SetInteger(webview::kInternalProcessId,
746       guest_web_contents()->GetRenderProcessHost()->GetID());
747   DispatchEventToEmbedder(
748       new GuestViewBase::Event(webview::kEventLoadCommit, args.Pass()));
749
750   // Update the current zoom factor for the new page.
751   ZoomController* zoom_controller =
752       ZoomController::FromWebContents(guest_web_contents());
753   DCHECK(zoom_controller);
754   current_zoom_factor_ = zoom_controller->GetZoomLevel();
755
756   if (!render_frame_host->GetParent())
757     chromevox_injected_ = false;
758 }
759
760 void WebViewGuest::DidFailProvisionalLoad(
761     content::RenderFrameHost* render_frame_host,
762     const GURL& validated_url,
763     int error_code,
764     const base::string16& error_description) {
765   LoadAbort(!render_frame_host->GetParent(), validated_url,
766             net::ErrorToShortString(error_code));
767 }
768
769 void WebViewGuest::DidStartProvisionalLoadForFrame(
770     content::RenderFrameHost* render_frame_host,
771     const GURL& validated_url,
772     bool is_error_page,
773     bool is_iframe_srcdoc) {
774   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
775   args->SetString(guestview::kUrl, validated_url.spec());
776   args->SetBoolean(guestview::kIsTopLevel, !render_frame_host->GetParent());
777   DispatchEventToEmbedder(
778       new GuestViewBase::Event(webview::kEventLoadStart, args.Pass()));
779 }
780
781 void WebViewGuest::DocumentLoadedInFrame(
782     content::RenderFrameHost* render_frame_host) {
783   if (!render_frame_host->GetParent())
784     InjectChromeVoxIfNeeded(render_frame_host->GetRenderViewHost());
785 }
786
787 bool WebViewGuest::OnMessageReceived(const IPC::Message& message,
788                                      RenderFrameHost* render_frame_host) {
789   bool handled = true;
790   IPC_BEGIN_MESSAGE_MAP(WebViewGuest, message)
791     IPC_MESSAGE_HANDLER(ChromeViewHostMsg_UpdateFrameName, OnUpdateFrameName)
792     IPC_MESSAGE_UNHANDLED(handled = false)
793   IPC_END_MESSAGE_MAP()
794   return handled;
795 }
796
797 void WebViewGuest::RenderProcessGone(base::TerminationStatus status) {
798   // Cancel all find sessions in progress.
799   find_helper_.CancelAllFindSessions();
800
801   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
802   args->SetInteger(webview::kProcessId,
803                    guest_web_contents()->GetRenderProcessHost()->GetID());
804   args->SetString(webview::kReason, TerminationStatusToString(status));
805   DispatchEventToEmbedder(
806       new GuestViewBase::Event(webview::kEventExit, args.Pass()));
807 }
808
809 void WebViewGuest::UserAgentOverrideSet(const std::string& user_agent) {
810   if (!attached())
811     return;
812   content::NavigationController& controller =
813       guest_web_contents()->GetController();
814   content::NavigationEntry* entry = controller.GetVisibleEntry();
815   if (!entry)
816     return;
817   entry->SetIsOverridingUserAgent(!user_agent.empty());
818   guest_web_contents()->GetController().Reload(false);
819 }
820
821 void WebViewGuest::ReportFrameNameChange(const std::string& name) {
822   name_ = name;
823   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
824   args->SetString(webview::kName, name);
825   DispatchEventToEmbedder(
826       new GuestViewBase::Event(webview::kEventFrameNameChanged, args.Pass()));
827 }
828
829 void WebViewGuest::LoadHandlerCalled() {
830   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
831   DispatchEventToEmbedder(
832       new GuestViewBase::Event(webview::kEventContentLoad, args.Pass()));
833 }
834
835 void WebViewGuest::LoadRedirect(const GURL& old_url,
836                                 const GURL& new_url,
837                                 bool is_top_level) {
838   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
839   args->SetBoolean(guestview::kIsTopLevel, is_top_level);
840   args->SetString(webview::kNewURL, new_url.spec());
841   args->SetString(webview::kOldURL, old_url.spec());
842   DispatchEventToEmbedder(
843       new GuestViewBase::Event(webview::kEventLoadRedirect, args.Pass()));
844 }
845
846 void WebViewGuest::PushWebViewStateToIOThread() {
847   const GURL& site_url = guest_web_contents()->GetSiteInstance()->GetSiteURL();
848   std::string partition_domain;
849   std::string partition_id;
850   bool in_memory;
851   if (!GetGuestPartitionConfigForSite(
852           site_url, &partition_domain, &partition_id, &in_memory)) {
853     NOTREACHED();
854     return;
855   }
856   DCHECK(embedder_extension_id() == partition_domain);
857
858   WebViewRendererState::WebViewInfo web_view_info;
859   web_view_info.embedder_process_id = embedder_render_process_id();
860   web_view_info.instance_id = view_instance_id();
861   web_view_info.partition_id = partition_id;
862   web_view_info.embedder_extension_id = embedder_extension_id();
863
864   content::BrowserThread::PostTask(
865       content::BrowserThread::IO,
866       FROM_HERE,
867       base::Bind(&WebViewRendererState::AddGuest,
868                  base::Unretained(WebViewRendererState::GetInstance()),
869                  guest_web_contents()->GetRenderProcessHost()->GetID(),
870                  guest_web_contents()->GetRoutingID(),
871                  web_view_info));
872 }
873
874 // static
875 void WebViewGuest::RemoveWebViewStateFromIOThread(
876     WebContents* web_contents) {
877   content::BrowserThread::PostTask(
878       content::BrowserThread::IO, FROM_HERE,
879       base::Bind(
880           &WebViewRendererState::RemoveGuest,
881           base::Unretained(WebViewRendererState::GetInstance()),
882           web_contents->GetRenderProcessHost()->GetID(),
883           web_contents->GetRoutingID()));
884 }
885
886 content::WebContents* WebViewGuest::CreateNewGuestWindow(
887     const content::WebContents::CreateParams& create_params) {
888   GuestViewManager* guest_manager =
889       GuestViewManager::FromBrowserContext(browser_context());
890   return guest_manager->CreateGuestWithWebContentsParams(
891       WebViewGuest::Type,
892       embedder_extension_id(),
893       embedder_web_contents()->GetRenderProcessHost()->GetID(),
894       create_params);
895 }
896
897 void WebViewGuest::RequestMediaAccessPermission(
898     content::WebContents* source,
899     const content::MediaStreamRequest& request,
900     const content::MediaResponseCallback& callback) {
901   web_view_permission_helper_->RequestMediaAccessPermission(source,
902                                                             request,
903                                                             callback);
904 }
905
906 void WebViewGuest::CanDownload(
907     content::RenderViewHost* render_view_host,
908     const GURL& url,
909     const std::string& request_method,
910     const base::Callback<void(bool)>& callback) {
911   web_view_permission_helper_->CanDownload(render_view_host,
912                                            url,
913                                            request_method,
914                                            callback);
915 }
916
917 void WebViewGuest::RequestPointerLockPermission(
918     bool user_gesture,
919     bool last_unlocked_by_target,
920     const base::Callback<void(bool)>& callback) {
921   web_view_permission_helper_->RequestPointerLockPermission(
922       user_gesture,
923       last_unlocked_by_target,
924       callback);
925 }
926
927 void WebViewGuest::WillAttachToEmbedder() {
928   // We must install the mapping from guests to WebViews prior to resuming
929   // suspended resource loads so that the WebRequest API will catch resource
930   // requests.
931   PushWebViewStateToIOThread();
932 }
933
934 content::JavaScriptDialogManager*
935     WebViewGuest::GetJavaScriptDialogManager() {
936   return &javascript_dialog_helper_;
937 }
938
939 content::ColorChooser* WebViewGuest::OpenColorChooser(
940     WebContents* web_contents,
941     SkColor color,
942     const std::vector<content::ColorSuggestion>& suggestions) {
943   if (!attached() || !embedder_web_contents()->GetDelegate())
944     return NULL;
945   return embedder_web_contents()->GetDelegate()->OpenColorChooser(
946       web_contents, color, suggestions);
947 }
948
949 void WebViewGuest::RunFileChooser(WebContents* web_contents,
950                                   const content::FileChooserParams& params) {
951   if (!attached() || !embedder_web_contents()->GetDelegate())
952     return;
953
954   embedder_web_contents()->GetDelegate()->RunFileChooser(web_contents, params);
955 }
956
957 void WebViewGuest::NavigateGuest(const std::string& src) {
958   GURL url = ResolveURL(src);
959
960   // Do not allow navigating a guest to schemes other than known safe schemes.
961   // This will block the embedder trying to load unwanted schemes, e.g.
962   // chrome://settings.
963   bool scheme_is_blocked =
964       (!content::ChildProcessSecurityPolicy::GetInstance()->IsWebSafeScheme(
965            url.scheme()) &&
966        !url.SchemeIs(url::kAboutScheme)) ||
967       url.SchemeIs(url::kJavaScriptScheme);
968   if (scheme_is_blocked || !url.is_valid()) {
969     LoadAbort(true /* is_top_level */, url,
970               net::ErrorToShortString(net::ERR_ABORTED));
971     return;
972   }
973
974   GURL validated_url(url);
975   guest_web_contents()->GetRenderProcessHost()->
976       FilterURL(false, &validated_url);
977   // As guests do not swap processes on navigation, only navigations to
978   // normal web URLs are supported.  No protocol handlers are installed for
979   // other schemes (e.g., WebUI or extensions), and no permissions or bindings
980   // can be granted to the guest process.
981   LoadURLWithParams(validated_url,
982                     content::Referrer(),
983                     content::PAGE_TRANSITION_AUTO_TOPLEVEL,
984                     guest_web_contents());
985 }
986
987 #if defined(OS_CHROMEOS)
988 void WebViewGuest::OnAccessibilityStatusChanged(
989     const chromeos::AccessibilityStatusEventDetails& details) {
990   if (details.notification_type == chromeos::ACCESSIBILITY_MANAGER_SHUTDOWN) {
991     accessibility_subscription_.reset();
992   } else if (details.notification_type ==
993       chromeos::ACCESSIBILITY_TOGGLE_SPOKEN_FEEDBACK) {
994     if (details.enabled)
995       InjectChromeVoxIfNeeded(guest_web_contents()->GetRenderViewHost());
996     else
997       chromevox_injected_ = false;
998   }
999 }
1000 #endif
1001
1002 void WebViewGuest::InjectChromeVoxIfNeeded(
1003     content::RenderViewHost* render_view_host) {
1004 #if defined(OS_CHROMEOS)
1005   if (!chromevox_injected_) {
1006     chromeos::AccessibilityManager* manager =
1007         chromeos::AccessibilityManager::Get();
1008     if (manager && manager->IsSpokenFeedbackEnabled()) {
1009       manager->InjectChromeVox(render_view_host);
1010       chromevox_injected_ = true;
1011     }
1012   }
1013 #endif
1014 }
1015
1016 bool WebViewGuest::HandleKeyboardShortcuts(
1017     const content::NativeWebKeyboardEvent& event) {
1018   if (event.type != blink::WebInputEvent::RawKeyDown)
1019     return false;
1020
1021   // If the user hits the escape key without any modifiers then unlock the
1022   // mouse if necessary.
1023   if ((event.windowsKeyCode == ui::VKEY_ESCAPE) &&
1024       !(event.modifiers & blink::WebInputEvent::InputModifiers)) {
1025     return guest_web_contents()->GotResponseToLockMouseRequest(false);
1026   }
1027
1028 #if defined(OS_MACOSX)
1029   if (event.modifiers != blink::WebInputEvent::MetaKey)
1030     return false;
1031
1032   if (event.windowsKeyCode == ui::VKEY_OEM_4) {
1033     Go(-1);
1034     return true;
1035   }
1036
1037   if (event.windowsKeyCode == ui::VKEY_OEM_6) {
1038     Go(1);
1039     return true;
1040   }
1041 #else
1042   if (event.windowsKeyCode == ui::VKEY_BROWSER_BACK) {
1043     Go(-1);
1044     return true;
1045   }
1046
1047   if (event.windowsKeyCode == ui::VKEY_BROWSER_FORWARD) {
1048     Go(1);
1049     return true;
1050   }
1051 #endif
1052
1053   return false;
1054 }
1055
1056 void WebViewGuest::SetUpAutoSize() {
1057   // Read the autosize parameters passed in from the embedder.
1058   bool auto_size_enabled = false;
1059   extra_params()->GetBoolean(webview::kAttributeAutoSize, &auto_size_enabled);
1060
1061   int max_height = 0;
1062   int max_width = 0;
1063   extra_params()->GetInteger(webview::kAttributeMaxHeight, &max_height);
1064   extra_params()->GetInteger(webview::kAttributeMaxWidth, &max_width);
1065
1066   int min_height = 0;
1067   int min_width = 0;
1068   extra_params()->GetInteger(webview::kAttributeMinHeight, &min_height);
1069   extra_params()->GetInteger(webview::kAttributeMinWidth, &min_width);
1070
1071   // Call SetAutoSize to apply all the appropriate validation and clipping of
1072   // values.
1073   SetAutoSize(auto_size_enabled,
1074               gfx::Size(min_width, min_height),
1075               gfx::Size(max_width, max_height));
1076 }
1077
1078 void WebViewGuest::ShowContextMenu(int request_id,
1079                                    const MenuItemVector* items) {
1080   if (!pending_menu_.get())
1081     return;
1082
1083   // Make sure this was the correct request.
1084   if (request_id != pending_context_menu_request_id_)
1085     return;
1086
1087   // TODO(lazyboy): Implement.
1088   DCHECK(!items);
1089
1090   ContextMenuDelegate* menu_delegate =
1091       ContextMenuDelegate::FromWebContents(guest_web_contents());
1092   menu_delegate->ShowMenu(pending_menu_.Pass());
1093 }
1094
1095 void WebViewGuest::SetName(const std::string& name) {
1096   if (name_ == name)
1097     return;
1098   name_ = name;
1099
1100   Send(new ChromeViewMsg_SetName(routing_id(), name_));
1101 }
1102
1103 void WebViewGuest::SetZoom(double zoom_factor) {
1104   ZoomController* zoom_controller =
1105       ZoomController::FromWebContents(guest_web_contents());
1106   DCHECK(zoom_controller);
1107   double zoom_level = content::ZoomFactorToZoomLevel(zoom_factor);
1108   zoom_controller->SetZoomLevel(zoom_level);
1109
1110   scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
1111   args->SetDouble(webview::kOldZoomFactor, current_zoom_factor_);
1112   args->SetDouble(webview::kNewZoomFactor, zoom_factor);
1113   DispatchEventToEmbedder(
1114       new GuestViewBase::Event(webview::kEventZoomChange, args.Pass()));
1115
1116   current_zoom_factor_ = zoom_factor;
1117 }
1118
1119 void WebViewGuest::AddNewContents(content::WebContents* source,
1120                                   content::WebContents* new_contents,
1121                                   WindowOpenDisposition disposition,
1122                                   const gfx::Rect& initial_pos,
1123                                   bool user_gesture,
1124                                   bool* was_blocked) {
1125   if (was_blocked)
1126     *was_blocked = false;
1127   RequestNewWindowPermission(disposition,
1128                              initial_pos,
1129                              user_gesture,
1130                              new_contents);
1131 }
1132
1133 content::WebContents* WebViewGuest::OpenURLFromTab(
1134     content::WebContents* source,
1135     const content::OpenURLParams& params) {
1136   // If the guest wishes to navigate away prior to attachment then we save the
1137   // navigation to perform upon attachment. Navigation initializes a lot of
1138   // state that assumes an embedder exists, such as RenderWidgetHostViewGuest.
1139   // Navigation also resumes resource loading which we don't want to allow
1140   // until attachment.
1141   if (!attached()) {
1142     WebViewGuest* opener = GetOpener();
1143     PendingWindowMap::iterator it =
1144         opener->pending_new_windows_.find(this);
1145     if (it == opener->pending_new_windows_.end())
1146       return NULL;
1147     const NewWindowInfo& info = it->second;
1148     NewWindowInfo new_window_info(params.url, info.name);
1149     new_window_info.changed = new_window_info.url != info.url;
1150     it->second = new_window_info;
1151     return NULL;
1152   }
1153   if (params.disposition == CURRENT_TAB) {
1154     // This can happen for cross-site redirects.
1155     LoadURLWithParams(params.url, params.referrer, params.transition, source);
1156     return source;
1157   }
1158
1159   CreateNewGuestWebViewWindow(params);
1160   return NULL;
1161 }
1162
1163 void WebViewGuest::WebContentsCreated(WebContents* source_contents,
1164                                       int opener_render_frame_id,
1165                                       const base::string16& frame_name,
1166                                       const GURL& target_url,
1167                                       content::WebContents* new_contents) {
1168   WebViewGuest* guest = WebViewGuest::FromWebContents(new_contents);
1169   CHECK(guest);
1170   guest->SetOpener(this);
1171   std::string guest_name = base::UTF16ToUTF8(frame_name);
1172   guest->name_ = guest_name;
1173   pending_new_windows_.insert(
1174       std::make_pair(guest, NewWindowInfo(target_url, guest_name)));
1175 }
1176
1177 void WebViewGuest::LoadURLWithParams(const GURL& url,
1178                                      const content::Referrer& referrer,
1179                                      content::PageTransition transition_type,
1180                                      content::WebContents* web_contents) {
1181   content::NavigationController::LoadURLParams load_url_params(url);
1182   load_url_params.referrer = referrer;
1183   load_url_params.transition_type = transition_type;
1184   load_url_params.extra_headers = std::string();
1185   if (is_overriding_user_agent_) {
1186     load_url_params.override_user_agent =
1187         content::NavigationController::UA_OVERRIDE_TRUE;
1188   }
1189   web_contents->GetController().LoadURLWithParams(load_url_params);
1190 }
1191
1192 void WebViewGuest::RequestNewWindowPermission(
1193     WindowOpenDisposition disposition,
1194     const gfx::Rect& initial_bounds,
1195     bool user_gesture,
1196     content::WebContents* new_contents) {
1197   WebViewGuest* guest = WebViewGuest::FromWebContents(new_contents);
1198   if (!guest)
1199     return;
1200   PendingWindowMap::iterator it = pending_new_windows_.find(guest);
1201   if (it == pending_new_windows_.end())
1202     return;
1203   const NewWindowInfo& new_window_info = it->second;
1204
1205   // Retrieve the opener partition info if we have it.
1206   const GURL& site_url = new_contents->GetSiteInstance()->GetSiteURL();
1207   std::string storage_partition_id = GetStoragePartitionIdFromSiteURL(site_url);
1208
1209   base::DictionaryValue request_info;
1210   request_info.SetInteger(webview::kInitialHeight, initial_bounds.height());
1211   request_info.SetInteger(webview::kInitialWidth, initial_bounds.width());
1212   request_info.Set(webview::kTargetURL,
1213                    new base::StringValue(new_window_info.url.spec()));
1214   request_info.Set(webview::kName, new base::StringValue(new_window_info.name));
1215   request_info.SetInteger(webview::kWindowID, guest->GetGuestInstanceID());
1216   // We pass in partition info so that window-s created through newwindow
1217   // API can use it to set their partition attribute.
1218   request_info.Set(webview::kStoragePartitionId,
1219                    new base::StringValue(storage_partition_id));
1220   request_info.Set(
1221       webview::kWindowOpenDisposition,
1222       new base::StringValue(WindowOpenDispositionToString(disposition)));
1223
1224   web_view_permission_helper_->
1225       RequestPermission(WEB_VIEW_PERMISSION_TYPE_NEW_WINDOW,
1226                         request_info,
1227                         base::Bind(&WebViewGuest::OnWebViewNewWindowResponse,
1228                                    base::Unretained(this),
1229                                    guest->GetGuestInstanceID()),
1230                                    false /* allowed_by_default */);
1231 }
1232
1233 void WebViewGuest::DestroyUnattachedWindows() {
1234   // Destroy() reaches in and removes the WebViewGuest from its opener's
1235   // pending_new_windows_ set. To avoid mutating the set while iterating, we
1236   // create a copy of the pending new windows set and iterate over the copy.
1237   PendingWindowMap pending_new_windows(pending_new_windows_);
1238   // Clean up unattached new windows opened by this guest.
1239   for (PendingWindowMap::const_iterator it = pending_new_windows.begin();
1240        it != pending_new_windows.end(); ++it) {
1241     it->first->Destroy();
1242   }
1243   // All pending windows should be removed from the set after Destroy() is
1244   // called on all of them.
1245   DCHECK(pending_new_windows_.empty());
1246 }
1247
1248 GURL WebViewGuest::ResolveURL(const std::string& src) {
1249   if (!in_extension()) {
1250     NOTREACHED();
1251     return GURL(src);
1252   }
1253
1254   GURL default_url(base::StringPrintf("%s://%s/",
1255                                       kExtensionScheme,
1256                                       embedder_extension_id().c_str()));
1257   return default_url.Resolve(src);
1258 }
1259
1260 void WebViewGuest::OnWebViewNewWindowResponse(
1261     int new_window_instance_id,
1262     bool allow,
1263     const std::string& user_input) {
1264   WebViewGuest* guest =
1265       WebViewGuest::From(embedder_render_process_id(), new_window_instance_id);
1266   if (!guest)
1267     return;
1268
1269   if (!allow)
1270     guest->Destroy();
1271 }
1272
1273 void WebViewGuest::OnZoomChanged(
1274     const ZoomController::ZoomChangedEventData& data) {
1275   ZoomController::FromWebContents(guest_web_contents())->
1276       SetZoomLevel(data.new_zoom_level);
1277 }
1278
1279 }  // namespace extensions