web_contents_impl.cc revision 2385ea399aae016c0806a4f9ef3c9cfe3d2a39df
1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "content/browser/web_contents/web_contents_impl.h"
6
7#include <utility>
8
9#include "base/command_line.h"
10#include "base/debug/trace_event.h"
11#include "base/lazy_instance.h"
12#include "base/logging.h"
13#include "base/metrics/histogram.h"
14#include "base/metrics/stats_counters.h"
15#include "base/strings/string16.h"
16#include "base/strings/string_number_conversions.h"
17#include "base/strings/string_util.h"
18#include "base/strings/utf_string_conversions.h"
19#include "base/sys_info.h"
20#include "base/time/time.h"
21#include "cc/base/switches.h"
22#include "content/browser/browser_plugin/browser_plugin_embedder.h"
23#include "content/browser/browser_plugin/browser_plugin_guest.h"
24#include "content/browser/browser_plugin/browser_plugin_guest_manager.h"
25#include "content/browser/child_process_security_policy_impl.h"
26#include "content/browser/devtools/devtools_manager_impl.h"
27#include "content/browser/dom_storage/dom_storage_context_impl.h"
28#include "content/browser/dom_storage/session_storage_namespace_impl.h"
29#include "content/browser/download/download_stats.h"
30#include "content/browser/download/mhtml_generation_manager.h"
31#include "content/browser/download/save_package.h"
32#include "content/browser/gpu/gpu_data_manager_impl.h"
33#include "content/browser/gpu/gpu_process_host.h"
34#include "content/browser/host_zoom_map_impl.h"
35#include "content/browser/loader/resource_dispatcher_host_impl.h"
36#include "content/browser/power_save_blocker_impl.h"
37#include "content/browser/renderer_host/render_process_host_impl.h"
38#include "content/browser/renderer_host/render_view_host_impl.h"
39#include "content/browser/renderer_host/render_widget_host_impl.h"
40#include "content/browser/site_instance_impl.h"
41#include "content/browser/web_contents/interstitial_page_impl.h"
42#include "content/browser/web_contents/navigation_entry_impl.h"
43#include "content/browser/web_contents/web_contents_view_guest.h"
44#include "content/browser/webui/generic_handler.h"
45#include "content/browser/webui/web_ui_controller_factory_registry.h"
46#include "content/browser/webui/web_ui_impl.h"
47#include "content/common/browser_plugin/browser_plugin_constants.h"
48#include "content/common/browser_plugin/browser_plugin_messages.h"
49#include "content/common/image_messages.h"
50#include "content/common/ssl_status_serialization.h"
51#include "content/common/view_messages.h"
52#include "content/port/browser/render_view_host_delegate_view.h"
53#include "content/port/browser/render_widget_host_view_port.h"
54#include "content/public/browser/browser_context.h"
55#include "content/public/browser/color_chooser.h"
56#include "content/public/browser/compositor_util.h"
57#include "content/public/browser/content_browser_client.h"
58#include "content/public/browser/devtools_agent_host.h"
59#include "content/public/browser/download_manager.h"
60#include "content/public/browser/download_url_parameters.h"
61#include "content/public/browser/invalidate_type.h"
62#include "content/public/browser/javascript_dialog_manager.h"
63#include "content/public/browser/load_from_memory_cache_details.h"
64#include "content/public/browser/load_notification_details.h"
65#include "content/public/browser/navigation_details.h"
66#include "content/public/browser/notification_details.h"
67#include "content/public/browser/notification_service.h"
68#include "content/public/browser/resource_request_details.h"
69#include "content/public/browser/storage_partition.h"
70#include "content/public/browser/user_metrics.h"
71#include "content/public/browser/web_contents_delegate.h"
72#include "content/public/browser/web_contents_observer.h"
73#include "content/public/browser/web_contents_view.h"
74#include "content/public/common/bindings_policy.h"
75#include "content/public/common/content_constants.h"
76#include "content/public/common/content_switches.h"
77#include "content/public/common/page_zoom.h"
78#include "content/public/common/url_constants.h"
79#include "net/base/mime_util.h"
80#include "net/base/net_util.h"
81#include "net/base/network_change_notifier.h"
82#include "net/url_request/url_request_context_getter.h"
83#include "ui/base/layout.h"
84#include "ui/base/touch/touch_device.h"
85#include "ui/base/touch/touch_enabled.h"
86#include "ui/base/ui_base_switches.h"
87#include "ui/gfx/display.h"
88#include "ui/gfx/screen.h"
89#include "ui/gl/gl_switches.h"
90#include "webkit/common/webpreferences.h"
91
92#if defined(OS_ANDROID)
93#include "content/browser/android/date_time_chooser_android.h"
94#include "content/public/browser/android/content_view_core.h"
95#endif
96
97#if defined(OS_MACOSX)
98#include "base/mac/foundation_util.h"
99#include "ui/gl/io_surface_support_mac.h"
100#endif
101
102#if defined(OS_ANDROID)
103#include "content/browser/renderer_host/java/java_bridge_dispatcher_host_manager.h"
104#endif
105
106// Cross-Site Navigations
107//
108// If a WebContentsImpl is told to navigate to a different web site (as
109// determined by SiteInstance), it will replace its current RenderViewHost with
110// a new RenderViewHost dedicated to the new SiteInstance.  This works as
111// follows:
112//
113// - Navigate determines whether the destination is cross-site, and if so,
114//   it creates a pending_render_view_host_.
115// - The pending RVH is "suspended," so that no navigation messages are sent to
116//   its renderer until the onbeforeunload JavaScript handler has a chance to
117//   run in the current RVH.
118// - The pending RVH tells CrossSiteRequestManager (a thread-safe singleton)
119//   that it has a pending cross-site request.  ResourceDispatcherHost will
120//   check for this when the response arrives.
121// - The current RVH runs its onbeforeunload handler.  If it returns false, we
122//   cancel all the pending logic.  Otherwise we allow the pending RVH to send
123//   the navigation request to its renderer.
124// - ResourceDispatcherHost receives a ResourceRequest on the IO thread for the
125//   main resource load on the pending RVH. It checks CrossSiteRequestManager
126//   to see that it is a cross-site request, and installs a
127//   CrossSiteResourceHandler.
128// - When RDH receives a response, the BufferedResourceHandler determines
129//   whether it is a download.  If so, it sends a message to the new renderer
130//   causing it to cancel the request, and the download proceeds. For now, the
131//   pending RVH remains until the next DidNavigate event for this
132//   WebContentsImpl. This isn't ideal, but it doesn't affect any functionality.
133// - After RDH receives a response and determines that it is safe and not a
134//   download, it pauses the response to first run the old page's onunload
135//   handler.  It does this by asynchronously calling the OnCrossSiteResponse
136//   method of WebContentsImpl on the UI thread, which sends a SwapOut message
137//   to the current RVH.
138// - Once the onunload handler is finished, a SwapOut_ACK message is sent to
139//   the ResourceDispatcherHost, who unpauses the response.  Data is then sent
140//   to the pending RVH.
141// - The pending renderer sends a FrameNavigate message that invokes the
142//   DidNavigate method.  This replaces the current RVH with the
143//   pending RVH.
144// - The previous renderer is kept swapped out in RenderViewHostManager in case
145//   the user goes back.  The process only stays live if another tab is using
146//   it, but if so, the existing frame relationships will be maintained.
147
148namespace content {
149namespace {
150
151// Amount of time we wait between when a key event is received and the renderer
152// is queried for its state and pushed to the NavigationEntry.
153const int kQueryStateDelay = 5000;
154
155const int kSyncWaitDelay = 40;
156
157const char kDotGoogleDotCom[] = ".google.com";
158
159base::LazyInstance<std::vector<WebContents::CreatedCallback> >
160g_created_callbacks = LAZY_INSTANCE_INITIALIZER;
161
162static int StartDownload(content::RenderViewHost* rvh,
163                         const GURL& url,
164                         bool is_favicon,
165                         uint32_t preferred_image_size,
166                         uint32_t max_image_size) {
167  static int g_next_image_download_id = 0;
168  rvh->Send(new ImageMsg_DownloadImage(rvh->GetRoutingID(),
169                                       ++g_next_image_download_id,
170                                       url,
171                                       is_favicon,
172                                       preferred_image_size,
173                                       max_image_size));
174  return g_next_image_download_id;
175}
176
177ViewMsg_Navigate_Type::Value GetNavigationType(
178    BrowserContext* browser_context, const NavigationEntryImpl& entry,
179    NavigationController::ReloadType reload_type) {
180  switch (reload_type) {
181    case NavigationControllerImpl::RELOAD:
182      return ViewMsg_Navigate_Type::RELOAD;
183    case NavigationControllerImpl::RELOAD_IGNORING_CACHE:
184      return ViewMsg_Navigate_Type::RELOAD_IGNORING_CACHE;
185    case NavigationControllerImpl::RELOAD_ORIGINAL_REQUEST_URL:
186      return ViewMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL;
187    case NavigationControllerImpl::NO_RELOAD:
188      break;  // Fall through to rest of function.
189  }
190
191  // |RenderViewImpl::PopulateStateFromPendingNavigationParams| differentiates
192  // between |RESTORE_WITH_POST| and |RESTORE|.
193  if (entry.restore_type() ==
194      NavigationEntryImpl::RESTORE_LAST_SESSION_EXITED_CLEANLY) {
195    if (entry.GetHasPostData())
196      return ViewMsg_Navigate_Type::RESTORE_WITH_POST;
197    return ViewMsg_Navigate_Type::RESTORE;
198  }
199
200  return ViewMsg_Navigate_Type::NORMAL;
201}
202
203void MakeNavigateParams(const NavigationEntryImpl& entry,
204                        const NavigationControllerImpl& controller,
205                        WebContentsDelegate* delegate,
206                        NavigationController::ReloadType reload_type,
207                        ViewMsg_Navigate_Params* params) {
208  params->page_id = entry.GetPageID();
209  params->should_clear_history_list = entry.should_clear_history_list();
210  if (entry.should_clear_history_list()) {
211    // Set the history list related parameters to the same values a
212    // NavigationController would return before its first navigation. This will
213    // fully clear the RenderView's view of the session history.
214    params->pending_history_list_offset = -1;
215    params->current_history_list_offset = -1;
216    params->current_history_list_length = 0;
217  } else {
218    params->pending_history_list_offset = controller.GetIndexOfEntry(&entry);
219    params->current_history_list_offset =
220        controller.GetLastCommittedEntryIndex();
221    params->current_history_list_length = controller.GetEntryCount();
222  }
223  if (!entry.GetBaseURLForDataURL().is_empty()) {
224    params->base_url_for_data_url = entry.GetBaseURLForDataURL();
225    params->history_url_for_data_url = entry.GetVirtualURL();
226  }
227  params->referrer = entry.GetReferrer();
228  params->transition = entry.GetTransitionType();
229  params->page_state = entry.GetPageState();
230  params->navigation_type =
231      GetNavigationType(controller.GetBrowserContext(), entry, reload_type);
232  params->request_time = base::Time::Now();
233  params->extra_headers = entry.extra_headers();
234  params->transferred_request_child_id =
235      entry.transferred_global_request_id().child_id;
236  params->transferred_request_request_id =
237      entry.transferred_global_request_id().request_id;
238  params->is_overriding_user_agent = entry.GetIsOverridingUserAgent();
239  // Avoid downloading when in view-source mode.
240  params->allow_download = !entry.IsViewSourceMode();
241  params->is_post = entry.GetHasPostData();
242  if(entry.GetBrowserInitiatedPostData()) {
243      params->browser_initiated_post_data.assign(
244          entry.GetBrowserInitiatedPostData()->front(),
245          entry.GetBrowserInitiatedPostData()->front() +
246              entry.GetBrowserInitiatedPostData()->size());
247
248  }
249
250  if (reload_type == NavigationControllerImpl::RELOAD_ORIGINAL_REQUEST_URL &&
251      entry.GetOriginalRequestURL().is_valid() && !entry.GetHasPostData()) {
252    // We may have been redirected when navigating to the current URL.
253    // Use the URL the user originally intended to visit, if it's valid and if a
254    // POST wasn't involved; the latter case avoids issues with sending data to
255    // the wrong page.
256    params->url = entry.GetOriginalRequestURL();
257  } else {
258    params->url = entry.GetURL();
259  }
260
261  params->can_load_local_resources = entry.GetCanLoadLocalResources();
262  params->frame_to_navigate = entry.GetFrameToNavigate();
263
264  if (delegate)
265    delegate->AddNavigationHeaders(params->url, &params->extra_headers);
266}
267
268}  // namespace
269
270WebContents* WebContents::Create(const WebContents::CreateParams& params) {
271  return WebContentsImpl::CreateWithOpener(
272      params, static_cast<WebContentsImpl*>(params.opener));
273}
274
275WebContents* WebContents::CreateWithSessionStorage(
276    const WebContents::CreateParams& params,
277    const SessionStorageNamespaceMap& session_storage_namespace_map) {
278  WebContentsImpl* new_contents = new WebContentsImpl(
279      params.browser_context, NULL);
280
281  for (SessionStorageNamespaceMap::const_iterator it =
282           session_storage_namespace_map.begin();
283       it != session_storage_namespace_map.end();
284       ++it) {
285    new_contents->GetController()
286        .SetSessionStorageNamespace(it->first, it->second.get());
287  }
288
289  new_contents->Init(params);
290  return new_contents;
291}
292
293void WebContents::AddCreatedCallback(const CreatedCallback& callback) {
294  g_created_callbacks.Get().push_back(callback);
295}
296
297void WebContents::RemoveCreatedCallback(const CreatedCallback& callback) {
298  for (size_t i = 0; i < g_created_callbacks.Get().size(); ++i) {
299    if (g_created_callbacks.Get().at(i).Equals(callback)) {
300      g_created_callbacks.Get().erase(g_created_callbacks.Get().begin() + i);
301      return;
302    }
303  }
304}
305
306WebContents* WebContents::FromRenderViewHost(const RenderViewHost* rvh) {
307  return rvh->GetDelegate()->GetAsWebContents();
308}
309
310// WebContentsImpl::DestructionObserver ----------------------------------------
311
312class WebContentsImpl::DestructionObserver : public WebContentsObserver {
313 public:
314  DestructionObserver(WebContentsImpl* owner, WebContents* watched_contents)
315      : WebContentsObserver(watched_contents),
316        owner_(owner) {
317  }
318
319  // WebContentsObserver:
320  virtual void WebContentsDestroyed(WebContents* web_contents) OVERRIDE {
321    owner_->OnWebContentsDestroyed(static_cast<WebContentsImpl*>(web_contents));
322  }
323
324 private:
325  WebContentsImpl* owner_;
326
327  DISALLOW_COPY_AND_ASSIGN(DestructionObserver);
328};
329
330// WebContentsImpl -------------------------------------------------------------
331
332WebContentsImpl::WebContentsImpl(
333    BrowserContext* browser_context,
334    WebContentsImpl* opener)
335    : delegate_(NULL),
336      controller_(this, browser_context),
337      render_view_host_delegate_view_(NULL),
338      opener_(opener),
339#if defined(OS_WIN) && defined(USE_AURA)
340      accessible_parent_(NULL),
341#endif
342      render_manager_(this, this, this),
343      is_loading_(false),
344      crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING),
345      crashed_error_code_(0),
346      waiting_for_response_(false),
347      load_state_(net::LOAD_STATE_IDLE, string16()),
348      upload_size_(0),
349      upload_position_(0),
350      displayed_insecure_content_(false),
351      capturer_count_(0),
352      should_normally_be_visible_(true),
353      is_being_destroyed_(false),
354      notify_disconnection_(false),
355      dialog_manager_(NULL),
356      is_showing_before_unload_dialog_(false),
357      closed_by_user_gesture_(false),
358      minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor * 100)),
359      maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor * 100)),
360      temporary_zoom_settings_(false),
361      color_chooser_identifier_(0),
362      message_source_(NULL),
363      fullscreen_widget_routing_id_(MSG_ROUTING_NONE) {
364  for (size_t i = 0; i < g_created_callbacks.Get().size(); i++)
365    g_created_callbacks.Get().at(i).Run(this);
366}
367
368WebContentsImpl::~WebContentsImpl() {
369  is_being_destroyed_ = true;
370
371  ClearAllPowerSaveBlockers();
372
373  for (std::set<RenderWidgetHostImpl*>::iterator iter =
374           created_widgets_.begin(); iter != created_widgets_.end(); ++iter) {
375    (*iter)->DetachDelegate();
376  }
377  created_widgets_.clear();
378
379  // Clear out any JavaScript state.
380  if (dialog_manager_)
381    dialog_manager_->WebContentsDestroyed(this);
382
383  if (color_chooser_)
384    color_chooser_->End();
385
386  NotifyDisconnected();
387
388  // Notify any observer that have a reference on this WebContents.
389  NotificationService::current()->Notify(
390      NOTIFICATION_WEB_CONTENTS_DESTROYED,
391      Source<WebContents>(this),
392      NotificationService::NoDetails());
393
394  // TODO(brettw) this should be moved to the view.
395#if defined(OS_WIN) && !defined(USE_AURA)
396  // If we still have a window handle, destroy it. GetNativeView can return
397  // NULL if this contents was part of a window that closed.
398  if (view_->GetNativeView()) {
399    RenderViewHost* host = GetRenderViewHost();
400    if (host && host->GetView())
401      RenderWidgetHostViewPort::FromRWHV(host->GetView())->WillWmDestroy();
402  }
403#endif
404
405  FOR_EACH_OBSERVER(WebContentsObserver,
406                    observers_,
407                    WebContentsImplDestroyed());
408
409  SetDelegate(NULL);
410
411  STLDeleteContainerPairSecondPointers(destruction_observers_.begin(),
412                                       destruction_observers_.end());
413}
414
415WebContentsImpl* WebContentsImpl::CreateWithOpener(
416    const WebContents::CreateParams& params,
417    WebContentsImpl* opener) {
418  TRACE_EVENT0("browser", "WebContentsImpl::CreateWithOpener");
419  WebContentsImpl* new_contents = new WebContentsImpl(
420      params.browser_context, opener);
421
422  new_contents->Init(params);
423  return new_contents;
424}
425
426// static
427BrowserPluginGuest* WebContentsImpl::CreateGuest(
428    BrowserContext* browser_context,
429    SiteInstance* site_instance,
430    int guest_instance_id,
431    scoped_ptr<base::DictionaryValue> extra_params) {
432  WebContentsImpl* new_contents = new WebContentsImpl(browser_context, NULL);
433
434  // This makes |new_contents| act as a guest.
435  // For more info, see comment above class BrowserPluginGuest.
436  BrowserPluginGuest::Create(
437      guest_instance_id, new_contents, extra_params.Pass());
438
439  WebContents::CreateParams create_params(browser_context, site_instance);
440  new_contents->Init(create_params);
441
442  // We are instantiating a WebContents for browser plugin. Set its subframe bit
443  // to true.
444  static_cast<RenderViewHostImpl*>(
445      new_contents->GetRenderViewHost())->set_is_subframe(true);
446
447  return new_contents->browser_plugin_guest_.get();
448}
449
450WebPreferences WebContentsImpl::GetWebkitPrefs(RenderViewHost* rvh,
451                                               const GURL& url) {
452  TRACE_EVENT0("browser", "WebContentsImpl::GetWebkitPrefs");
453  WebPreferences prefs;
454
455  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
456
457  prefs.javascript_enabled =
458      !command_line.HasSwitch(switches::kDisableJavaScript);
459  prefs.web_security_enabled =
460      !command_line.HasSwitch(switches::kDisableWebSecurity);
461  prefs.plugins_enabled =
462      !command_line.HasSwitch(switches::kDisablePlugins);
463  prefs.java_enabled =
464      !command_line.HasSwitch(switches::kDisableJava);
465
466  prefs.remote_fonts_enabled =
467      !command_line.HasSwitch(switches::kDisableRemoteFonts);
468  prefs.xss_auditor_enabled =
469      !command_line.HasSwitch(switches::kDisableXSSAuditor);
470  prefs.application_cache_enabled =
471      !command_line.HasSwitch(switches::kDisableApplicationCache);
472
473  prefs.local_storage_enabled =
474      !command_line.HasSwitch(switches::kDisableLocalStorage);
475  prefs.databases_enabled =
476      !command_line.HasSwitch(switches::kDisableDatabases);
477  prefs.webaudio_enabled =
478      !command_line.HasSwitch(switches::kDisableWebAudio);
479
480  prefs.experimental_webgl_enabled =
481      GpuProcessHost::gpu_enabled() &&
482      !command_line.HasSwitch(switches::kDisable3DAPIs) &&
483      !command_line.HasSwitch(switches::kDisableExperimentalWebGL);
484
485  prefs.flash_3d_enabled =
486      GpuProcessHost::gpu_enabled() &&
487      !command_line.HasSwitch(switches::kDisableFlash3d);
488  prefs.flash_stage3d_enabled =
489      GpuProcessHost::gpu_enabled() &&
490      !command_line.HasSwitch(switches::kDisableFlashStage3d);
491  prefs.flash_stage3d_baseline_enabled =
492      GpuProcessHost::gpu_enabled() &&
493      !command_line.HasSwitch(switches::kDisableFlashStage3d);
494
495  prefs.gl_multisampling_enabled =
496      !command_line.HasSwitch(switches::kDisableGLMultisampling);
497  prefs.privileged_webgl_extensions_enabled =
498      command_line.HasSwitch(switches::kEnablePrivilegedWebGLExtensions);
499  prefs.site_specific_quirks_enabled =
500      !command_line.HasSwitch(switches::kDisableSiteSpecificQuirks);
501  prefs.allow_file_access_from_file_urls =
502      command_line.HasSwitch(switches::kAllowFileAccessFromFiles);
503
504  prefs.accelerated_compositing_for_overflow_scroll_enabled = false;
505  if (command_line.HasSwitch(switches::kEnableAcceleratedOverflowScroll))
506    prefs.accelerated_compositing_for_overflow_scroll_enabled = true;
507  if (command_line.HasSwitch(switches::kDisableAcceleratedOverflowScroll))
508    prefs.accelerated_compositing_for_overflow_scroll_enabled = false;
509
510  prefs.accelerated_compositing_for_scrollable_frames_enabled =
511      command_line.HasSwitch(switches::kEnableAcceleratedScrollableFrames);
512  prefs.composited_scrolling_for_frames_enabled =
513      command_line.HasSwitch(switches::kEnableCompositedScrollingForFrames);
514  prefs.show_paint_rects =
515      command_line.HasSwitch(switches::kShowPaintRects);
516  prefs.accelerated_compositing_enabled =
517      GpuProcessHost::gpu_enabled() &&
518      !command_line.HasSwitch(switches::kDisableAcceleratedCompositing);
519  prefs.force_compositing_mode =
520      content::IsForceCompositingModeEnabled() &&
521      !command_line.HasSwitch(switches::kDisableForceCompositingMode);
522  prefs.accelerated_2d_canvas_enabled =
523      GpuProcessHost::gpu_enabled() &&
524      !command_line.HasSwitch(switches::kDisableAccelerated2dCanvas);
525  prefs.antialiased_2d_canvas_disabled =
526      command_line.HasSwitch(switches::kDisable2dCanvasAntialiasing);
527  prefs.accelerated_filters_enabled =
528      GpuProcessHost::gpu_enabled() &&
529      command_line.HasSwitch(switches::kEnableAcceleratedFilters);
530  prefs.accelerated_compositing_for_3d_transforms_enabled =
531      prefs.accelerated_compositing_for_animation_enabled =
532          !command_line.HasSwitch(switches::kDisableAcceleratedLayers);
533  prefs.accelerated_compositing_for_plugins_enabled =
534      !command_line.HasSwitch(switches::kDisableAcceleratedPlugins);
535  prefs.accelerated_compositing_for_video_enabled =
536      !command_line.HasSwitch(switches::kDisableAcceleratedVideo);
537  prefs.fullscreen_enabled =
538      !command_line.HasSwitch(switches::kDisableFullScreen);
539  prefs.css_sticky_position_enabled =
540      command_line.HasSwitch(switches::kEnableExperimentalWebPlatformFeatures);
541  prefs.css_shaders_enabled =
542      command_line.HasSwitch(switches::kEnableCssShaders);
543  prefs.lazy_layout_enabled =
544      command_line.HasSwitch(switches::kEnableExperimentalWebPlatformFeatures);
545  prefs.region_based_columns_enabled =
546      command_line.HasSwitch(switches::kEnableRegionBasedColumns);
547  prefs.threaded_html_parser =
548      !command_line.HasSwitch(switches::kDisableThreadedHTMLParser);
549  prefs.experimental_websocket_enabled =
550      command_line.HasSwitch(switches::kEnableExperimentalWebSocket);
551  if (command_line.HasSwitch(cc::switches::kEnablePinchVirtualViewport)) {
552    prefs.pinch_virtual_viewport_enabled = true;
553    prefs.pinch_overlay_scrollbar_thickness = 10;
554  }
555
556#if defined(OS_ANDROID)
557  prefs.user_gesture_required_for_media_playback = !command_line.HasSwitch(
558      switches::kDisableGestureRequirementForMediaPlayback);
559#endif
560
561  prefs.touch_enabled = ui::AreTouchEventsEnabled();
562  prefs.device_supports_touch = prefs.touch_enabled &&
563      ui::IsTouchDevicePresent();
564#if defined(OS_ANDROID)
565  prefs.device_supports_mouse = false;
566#endif
567
568   prefs.touch_adjustment_enabled =
569       !command_line.HasSwitch(switches::kDisableTouchAdjustment);
570
571#if defined(OS_MACOSX) || defined(OS_CHROMEOS)
572  bool default_enable_scroll_animator = true;
573#else
574  bool default_enable_scroll_animator = false;
575#endif
576  prefs.enable_scroll_animator = default_enable_scroll_animator;
577  if (command_line.HasSwitch(switches::kEnableSmoothScrolling))
578    prefs.enable_scroll_animator = true;
579  if (command_line.HasSwitch(switches::kDisableSmoothScrolling))
580    prefs.enable_scroll_animator = false;
581
582  prefs.visual_word_movement_enabled =
583      command_line.HasSwitch(switches::kEnableVisualWordMovement);
584
585  // Certain GPU features might have been blacklisted.
586  GpuDataManagerImpl::GetInstance()->UpdateRendererWebPrefs(&prefs);
587
588  if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
589          rvh->GetProcess()->GetID())) {
590    prefs.loads_images_automatically = true;
591    prefs.javascript_enabled = true;
592  }
593
594  prefs.is_online = !net::NetworkChangeNotifier::IsOffline();
595
596#if !defined(USE_AURA)
597  // Force accelerated compositing and 2d canvas off for chrome: and about:
598  // pages (unless it's specifically allowed).
599  if ((url.SchemeIs(chrome::kChromeUIScheme) ||
600      (url.SchemeIs(chrome::kAboutScheme) &&
601       url.spec() != kAboutBlankURL)) &&
602      !command_line.HasSwitch(switches::kAllowWebUICompositing)) {
603    prefs.accelerated_compositing_enabled = false;
604    prefs.accelerated_2d_canvas_enabled = false;
605  }
606#endif
607
608  prefs.fixed_position_creates_stacking_context = !command_line.HasSwitch(
609      switches::kDisableFixedPositionCreatesStackingContext);
610
611#if defined(OS_CHROMEOS)
612  prefs.gesture_tap_highlight_enabled = !command_line.HasSwitch(
613      switches::kDisableGestureTapHighlight);
614#else
615  prefs.gesture_tap_highlight_enabled = command_line.HasSwitch(
616      switches::kEnableGestureTapHighlight);
617#endif
618
619  prefs.number_of_cpu_cores = base::SysInfo::NumberOfProcessors();
620
621  prefs.viewport_enabled = command_line.HasSwitch(switches::kEnableViewport);
622
623  prefs.deferred_image_decoding_enabled =
624      command_line.HasSwitch(switches::kEnableDeferredImageDecoding) ||
625      cc::switches::IsImplSidePaintingEnabled();
626
627  prefs.spatial_navigation_enabled = command_line.HasSwitch(
628      switches::kEnableSpatialNavigation);
629
630  GetContentClient()->browser()->OverrideWebkitPrefs(rvh, url, &prefs);
631
632  // Disable compositing in guests until we have compositing path implemented
633  // for guests.
634  bool guest_compositing_enabled = !command_line.HasSwitch(
635      switches::kDisableBrowserPluginCompositing);
636  if (rvh->GetProcess()->IsGuest() && !guest_compositing_enabled) {
637    prefs.force_compositing_mode = false;
638    prefs.accelerated_compositing_enabled = false;
639  }
640
641  return prefs;
642}
643
644RenderViewHostManager* WebContentsImpl::GetRenderManagerForTesting() {
645  return &render_manager_;
646}
647
648bool WebContentsImpl::OnMessageReceived(RenderViewHost* render_view_host,
649                                        const IPC::Message& message) {
650  if (GetWebUI() &&
651      static_cast<WebUIImpl*>(GetWebUI())->OnMessageReceived(message)) {
652    return true;
653  }
654
655  ObserverListBase<WebContentsObserver>::Iterator it(observers_);
656  WebContentsObserver* observer;
657  while ((observer = it.GetNext()) != NULL)
658    if (observer->OnMessageReceived(message))
659      return true;
660
661  // Message handlers should be aware of which RenderViewHost sent the
662  // message, which is temporarily stored in message_source_.
663  message_source_ = render_view_host;
664  bool handled = true;
665  bool message_is_ok = true;
666  IPC_BEGIN_MESSAGE_MAP_EX(WebContentsImpl, message, message_is_ok)
667    IPC_MESSAGE_HANDLER(ViewHostMsg_DidLoadResourceFromMemoryCache,
668                        OnDidLoadResourceFromMemoryCache)
669    IPC_MESSAGE_HANDLER(ViewHostMsg_DidDisplayInsecureContent,
670                        OnDidDisplayInsecureContent)
671    IPC_MESSAGE_HANDLER(ViewHostMsg_DidRunInsecureContent,
672                        OnDidRunInsecureContent)
673    IPC_MESSAGE_HANDLER(ViewHostMsg_DocumentLoadedInFrame,
674                        OnDocumentLoadedInFrame)
675    IPC_MESSAGE_HANDLER(ViewHostMsg_DidFinishLoad, OnDidFinishLoad)
676    IPC_MESSAGE_HANDLER(ViewHostMsg_DidFailLoadWithError,
677                        OnDidFailLoadWithError)
678    IPC_MESSAGE_HANDLER(ViewHostMsg_GoToEntryAtOffset, OnGoToEntryAtOffset)
679    IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateZoomLimits, OnUpdateZoomLimits)
680    IPC_MESSAGE_HANDLER(ViewHostMsg_EnumerateDirectory, OnEnumerateDirectory)
681    IPC_MESSAGE_HANDLER(ViewHostMsg_JSOutOfMemory, OnJSOutOfMemory)
682    IPC_MESSAGE_HANDLER(ViewHostMsg_RegisterProtocolHandler,
683                        OnRegisterProtocolHandler)
684    IPC_MESSAGE_HANDLER(ViewHostMsg_Find_Reply, OnFindReply)
685    IPC_MESSAGE_HANDLER(ViewHostMsg_DidProgrammaticallyScroll,
686                        OnDidProgrammaticallyScroll)
687    IPC_MESSAGE_HANDLER(ViewHostMsg_CrashedPlugin, OnCrashedPlugin)
688    IPC_MESSAGE_HANDLER(ViewHostMsg_AppCacheAccessed, OnAppCacheAccessed)
689    IPC_MESSAGE_HANDLER(ViewHostMsg_OpenColorChooser, OnOpenColorChooser)
690    IPC_MESSAGE_HANDLER(ViewHostMsg_EndColorChooser, OnEndColorChooser)
691    IPC_MESSAGE_HANDLER(ViewHostMsg_SetSelectedColorInColorChooser,
692                        OnSetSelectedColorInColorChooser)
693    IPC_MESSAGE_HANDLER(ViewHostMsg_PepperPluginHung, OnPepperPluginHung)
694    IPC_MESSAGE_HANDLER(ViewHostMsg_WebUISend, OnWebUISend)
695    IPC_MESSAGE_HANDLER(ViewHostMsg_RequestPpapiBrokerPermission,
696                        OnRequestPpapiBrokerPermission)
697    IPC_MESSAGE_HANDLER_GENERIC(BrowserPluginHostMsg_AllocateInstanceID,
698                                OnBrowserPluginMessage(message))
699    IPC_MESSAGE_HANDLER_GENERIC(BrowserPluginHostMsg_Attach,
700                                OnBrowserPluginMessage(message))
701    IPC_MESSAGE_HANDLER(ImageHostMsg_DidDownloadImage, OnDidDownloadImage)
702    IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateFaviconURL, OnUpdateFaviconURL)
703#if defined(OS_ANDROID)
704    IPC_MESSAGE_HANDLER(ViewHostMsg_FindMatchRects_Reply,
705                        OnFindMatchRectsReply)
706    IPC_MESSAGE_HANDLER(ViewHostMsg_OpenDateTimeDialog,
707                        OnOpenDateTimeDialog)
708#endif
709    IPC_MESSAGE_HANDLER(ViewHostMsg_FrameAttached, OnFrameAttached)
710    IPC_MESSAGE_HANDLER(ViewHostMsg_FrameDetached, OnFrameDetached)
711    IPC_MESSAGE_HANDLER(ViewHostMsg_MediaNotification, OnMediaNotification)
712    IPC_MESSAGE_UNHANDLED(handled = false)
713  IPC_END_MESSAGE_MAP_EX()
714  message_source_ = NULL;
715
716  if (!message_is_ok) {
717    RecordAction(UserMetricsAction("BadMessageTerminate_RVD"));
718    GetRenderProcessHost()->ReceivedBadMessage();
719  }
720
721  return handled;
722}
723
724void WebContentsImpl::RunFileChooser(
725    RenderViewHost* render_view_host,
726    const FileChooserParams& params) {
727  if (delegate_)
728    delegate_->RunFileChooser(this, params);
729}
730
731NavigationControllerImpl& WebContentsImpl::GetController() {
732  return controller_;
733}
734
735const NavigationControllerImpl& WebContentsImpl::GetController() const {
736  return controller_;
737}
738
739BrowserContext* WebContentsImpl::GetBrowserContext() const {
740  return controller_.GetBrowserContext();
741}
742
743const GURL& WebContentsImpl::GetURL() const {
744  // We may not have a navigation entry yet.
745  NavigationEntry* entry = controller_.GetVisibleEntry();
746  return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
747}
748
749const GURL& WebContentsImpl::GetVisibleURL() const {
750  // We may not have a navigation entry yet.
751  NavigationEntry* entry = controller_.GetVisibleEntry();
752  return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
753}
754
755const GURL& WebContentsImpl::GetLastCommittedURL() const {
756  // We may not have a navigation entry yet.
757  NavigationEntry* entry = controller_.GetLastCommittedEntry();
758  return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
759}
760
761WebContentsDelegate* WebContentsImpl::GetDelegate() {
762  return delegate_;
763}
764
765void WebContentsImpl::SetDelegate(WebContentsDelegate* delegate) {
766  // TODO(cbentzel): remove this debugging code?
767  if (delegate == delegate_)
768    return;
769  if (delegate_)
770    delegate_->Detach(this);
771  delegate_ = delegate;
772  if (delegate_) {
773    delegate_->Attach(this);
774    // Ensure the visible RVH reflects the new delegate's preferences.
775    if (view_)
776      view_->SetOverscrollControllerEnabled(delegate->CanOverscrollContent());
777  }
778}
779
780RenderProcessHost* WebContentsImpl::GetRenderProcessHost() const {
781  RenderViewHostImpl* host = render_manager_.current_host();
782  return host ? host->GetProcess() : NULL;
783}
784
785RenderViewHost* WebContentsImpl::GetRenderViewHost() const {
786  return render_manager_.current_host();
787}
788
789void WebContentsImpl::GetRenderViewHostAtPosition(
790    int x,
791    int y,
792    const base::Callback<void(RenderViewHost*, int, int)>& callback) {
793  BrowserPluginEmbedder* embedder = GetBrowserPluginEmbedder();
794  if (embedder)
795    embedder->GetRenderViewHostAtPosition(x, y, callback);
796  else
797    callback.Run(GetRenderViewHost(), x, y);
798}
799
800WebContents* WebContentsImpl::GetEmbedderWebContents() const {
801  BrowserPluginGuest* guest = GetBrowserPluginGuest();
802  if (guest)
803    return guest->embedder_web_contents();
804  return NULL;
805}
806
807int WebContentsImpl::GetEmbeddedInstanceID() const {
808  BrowserPluginGuest* guest = GetBrowserPluginGuest();
809  if (guest)
810    return guest->instance_id();
811  return 0;
812}
813
814int WebContentsImpl::GetRoutingID() const {
815  if (!GetRenderViewHost())
816    return MSG_ROUTING_NONE;
817
818  return GetRenderViewHost()->GetRoutingID();
819}
820
821int WebContentsImpl::GetFullscreenWidgetRoutingID() const {
822  return fullscreen_widget_routing_id_;
823}
824
825RenderWidgetHostView* WebContentsImpl::GetRenderWidgetHostView() const {
826  return render_manager_.GetRenderWidgetHostView();
827}
828
829RenderWidgetHostViewPort* WebContentsImpl::GetRenderWidgetHostViewPort() const {
830  BrowserPluginGuest* guest = GetBrowserPluginGuest();
831  if (guest && guest->embedder_web_contents()) {
832    return guest->embedder_web_contents()->GetRenderWidgetHostViewPort();
833  }
834  return RenderWidgetHostViewPort::FromRWHV(GetRenderWidgetHostView());
835}
836
837WebContentsView* WebContentsImpl::GetView() const {
838  return view_.get();
839}
840
841WebUI* WebContentsImpl::CreateWebUI(const GURL& url) {
842  WebUIImpl* web_ui = new WebUIImpl(this);
843  WebUIController* controller = WebUIControllerFactoryRegistry::GetInstance()->
844      CreateWebUIControllerForURL(web_ui, url);
845  if (controller) {
846    web_ui->AddMessageHandler(new GenericHandler());
847    web_ui->SetController(controller);
848    return web_ui;
849  }
850
851  delete web_ui;
852  return NULL;
853}
854
855WebUI* WebContentsImpl::GetWebUI() const {
856  return render_manager_.web_ui() ? render_manager_.web_ui()
857      : render_manager_.pending_web_ui();
858}
859
860WebUI* WebContentsImpl::GetCommittedWebUI() const {
861  return render_manager_.web_ui();
862}
863
864void WebContentsImpl::SetUserAgentOverride(const std::string& override) {
865  if (GetUserAgentOverride() == override)
866    return;
867
868  renderer_preferences_.user_agent_override = override;
869
870  // Send the new override string to the renderer.
871  RenderViewHost* host = GetRenderViewHost();
872  if (host)
873    host->SyncRendererPrefs();
874
875  // Reload the page if a load is currently in progress to avoid having
876  // different parts of the page loaded using different user agents.
877  NavigationEntry* entry = controller_.GetActiveEntry();
878  if (is_loading_ && entry != NULL && entry->GetIsOverridingUserAgent())
879    controller_.ReloadIgnoringCache(true);
880
881  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
882                    UserAgentOverrideSet(override));
883}
884
885const std::string& WebContentsImpl::GetUserAgentOverride() const {
886  return renderer_preferences_.user_agent_override;
887}
888
889#if defined(OS_WIN) && defined(USE_AURA)
890void WebContentsImpl::SetParentNativeViewAccessible(
891gfx::NativeViewAccessible accessible_parent) {
892  accessible_parent_ = accessible_parent;
893  if (GetRenderViewHost())
894    GetRenderViewHostImpl()->SetParentNativeViewAccessible(accessible_parent);
895}
896#endif
897
898const string16& WebContentsImpl::GetTitle() const {
899  // Transient entries take precedence. They are used for interstitial pages
900  // that are shown on top of existing pages.
901  NavigationEntry* entry = controller_.GetTransientEntry();
902  std::string accept_languages =
903      GetContentClient()->browser()->GetAcceptLangs(
904          GetBrowserContext());
905  if (entry) {
906    return entry->GetTitleForDisplay(accept_languages);
907  }
908  WebUI* our_web_ui = render_manager_.pending_web_ui() ?
909      render_manager_.pending_web_ui() : render_manager_.web_ui();
910  if (our_web_ui) {
911    // Don't override the title in view source mode.
912    entry = controller_.GetVisibleEntry();
913    if (!(entry && entry->IsViewSourceMode())) {
914      // Give the Web UI the chance to override our title.
915      const string16& title = our_web_ui->GetOverriddenTitle();
916      if (!title.empty())
917        return title;
918    }
919  }
920
921  // We use the title for the last committed entry rather than a pending
922  // navigation entry. For example, when the user types in a URL, we want to
923  // keep the old page's title until the new load has committed and we get a new
924  // title.
925  entry = controller_.GetLastCommittedEntry();
926
927  // We make an exception for initial navigations, because we can have a
928  // committed entry for an initial navigation when doing a history navigation
929  // in a new tab, such as Ctrl+Back.
930  if (entry && controller_.IsInitialNavigation())
931    entry = controller_.GetVisibleEntry();
932
933  if (entry) {
934    return entry->GetTitleForDisplay(accept_languages);
935  }
936
937  // |page_title_when_no_navigation_entry_| is finally used
938  // if no title cannot be retrieved.
939  return page_title_when_no_navigation_entry_;
940}
941
942int32 WebContentsImpl::GetMaxPageID() {
943  return GetMaxPageIDForSiteInstance(GetSiteInstance());
944}
945
946int32 WebContentsImpl::GetMaxPageIDForSiteInstance(
947    SiteInstance* site_instance) {
948  if (max_page_ids_.find(site_instance->GetId()) == max_page_ids_.end())
949    max_page_ids_[site_instance->GetId()] = -1;
950
951  return max_page_ids_[site_instance->GetId()];
952}
953
954void WebContentsImpl::UpdateMaxPageID(int32 page_id) {
955  UpdateMaxPageIDForSiteInstance(GetSiteInstance(), page_id);
956}
957
958void WebContentsImpl::UpdateMaxPageIDForSiteInstance(
959    SiteInstance* site_instance, int32 page_id) {
960  if (GetMaxPageIDForSiteInstance(site_instance) < page_id)
961    max_page_ids_[site_instance->GetId()] = page_id;
962}
963
964void WebContentsImpl::CopyMaxPageIDsFrom(WebContentsImpl* web_contents) {
965  max_page_ids_ = web_contents->max_page_ids_;
966}
967
968SiteInstance* WebContentsImpl::GetSiteInstance() const {
969  return render_manager_.current_host()->GetSiteInstance();
970}
971
972SiteInstance* WebContentsImpl::GetPendingSiteInstance() const {
973  RenderViewHost* dest_rvh = render_manager_.pending_render_view_host() ?
974      render_manager_.pending_render_view_host() :
975      render_manager_.current_host();
976  return dest_rvh->GetSiteInstance();
977}
978
979bool WebContentsImpl::IsLoading() const {
980  return is_loading_;
981}
982
983bool WebContentsImpl::IsWaitingForResponse() const {
984  return waiting_for_response_;
985}
986
987const net::LoadStateWithParam& WebContentsImpl::GetLoadState() const {
988  return load_state_;
989}
990
991const string16& WebContentsImpl::GetLoadStateHost() const {
992  return load_state_host_;
993}
994
995uint64 WebContentsImpl::GetUploadSize() const {
996  return upload_size_;
997}
998
999uint64 WebContentsImpl::GetUploadPosition() const {
1000  return upload_position_;
1001}
1002
1003std::set<GURL> WebContentsImpl::GetSitesInTab() const {
1004  BrowserContext* browser_context = GetBrowserContext();
1005  std::set<GURL> sites;
1006  if (!frame_tree_root_.get())
1007    return sites;
1008
1009  // Iterates over the FrameTreeNodes to find each unique site URL that is
1010  // currently committed.
1011  FrameTreeNode* node = NULL;
1012  std::queue<FrameTreeNode*> queue;
1013  queue.push(frame_tree_root_.get());
1014
1015  while (!queue.empty()) {
1016    node = queue.front();
1017    queue.pop();
1018    sites.insert(SiteInstance::GetSiteForURL(browser_context,
1019                                             node->current_url()));
1020
1021    for (size_t i = 0; i < node->child_count(); ++i)
1022      queue.push(node->child_at(i));
1023  }
1024
1025  return sites;
1026}
1027
1028const std::string& WebContentsImpl::GetEncoding() const {
1029  return encoding_;
1030}
1031
1032bool WebContentsImpl::DisplayedInsecureContent() const {
1033  return displayed_insecure_content_;
1034}
1035
1036void WebContentsImpl::IncrementCapturerCount() {
1037  DCHECK(!is_being_destroyed_);
1038  ++capturer_count_;
1039  DVLOG(1) << "There are now " << capturer_count_
1040           << " capturing(s) of WebContentsImpl@" << this;
1041}
1042
1043void WebContentsImpl::DecrementCapturerCount() {
1044  --capturer_count_;
1045  DVLOG(1) << "There are now " << capturer_count_
1046           << " capturing(s) of WebContentsImpl@" << this;
1047  DCHECK_LE(0, capturer_count_);
1048
1049  if (is_being_destroyed_)
1050    return;
1051
1052  // While capturer_count_ was greater than zero, the WasHidden() calls to RWHV
1053  // were being prevented.  If there are no more capturers, make the call now.
1054  if (capturer_count_ == 0 && !should_normally_be_visible_) {
1055    DVLOG(1) << "Executing delayed WasHidden().";
1056    WasHidden();
1057  }
1058}
1059
1060int WebContentsImpl::GetCapturerCount() const {
1061  return capturer_count_;
1062}
1063
1064bool WebContentsImpl::IsCrashed() const {
1065  return (crashed_status_ == base::TERMINATION_STATUS_PROCESS_CRASHED ||
1066          crashed_status_ == base::TERMINATION_STATUS_ABNORMAL_TERMINATION ||
1067          crashed_status_ == base::TERMINATION_STATUS_PROCESS_WAS_KILLED);
1068}
1069
1070void WebContentsImpl::SetIsCrashed(base::TerminationStatus status,
1071                                   int error_code) {
1072  if (status == crashed_status_)
1073    return;
1074
1075  crashed_status_ = status;
1076  crashed_error_code_ = error_code;
1077  NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
1078}
1079
1080base::TerminationStatus WebContentsImpl::GetCrashedStatus() const {
1081  return crashed_status_;
1082}
1083
1084bool WebContentsImpl::IsBeingDestroyed() const {
1085  return is_being_destroyed_;
1086}
1087
1088void WebContentsImpl::NotifyNavigationStateChanged(unsigned changed_flags) {
1089  if (delegate_)
1090    delegate_->NavigationStateChanged(this, changed_flags);
1091}
1092
1093base::TimeTicks WebContentsImpl::GetLastSelectedTime() const {
1094  return last_selected_time_;
1095}
1096
1097void WebContentsImpl::WasShown() {
1098  controller_.SetActive(true);
1099  RenderWidgetHostViewPort* rwhv =
1100      RenderWidgetHostViewPort::FromRWHV(GetRenderWidgetHostView());
1101  if (rwhv) {
1102    rwhv->WasShown();
1103#if defined(OS_MACOSX)
1104    rwhv->SetActive(true);
1105#endif
1106  }
1107
1108  last_selected_time_ = base::TimeTicks::Now();
1109
1110  FOR_EACH_OBSERVER(WebContentsObserver, observers_, WasShown());
1111
1112  // The resize rect might have changed while this was inactive -- send the new
1113  // one to make sure it's up to date.
1114  RenderViewHostImpl* rvh =
1115      static_cast<RenderViewHostImpl*>(GetRenderViewHost());
1116  if (rvh) {
1117    rvh->ResizeRectChanged(GetRootWindowResizerRect());
1118  }
1119
1120  should_normally_be_visible_ = true;
1121  NotificationService::current()->Notify(
1122      NOTIFICATION_WEB_CONTENTS_VISIBILITY_CHANGED,
1123      Source<WebContents>(this),
1124      Details<const bool>(&should_normally_be_visible_));
1125}
1126
1127void WebContentsImpl::WasHidden() {
1128  // If there are entities capturing screenshots or video (e.g., mirroring),
1129  // don't activate the "disable rendering" optimization.
1130  if (capturer_count_ == 0) {
1131    // |GetRenderViewHost()| can be NULL if the user middle clicks a link to
1132    // open a tab in the background, then closes the tab before selecting it.
1133    // This is because closing the tab calls WebContentsImpl::Destroy(), which
1134    // removes the |GetRenderViewHost()|; then when we actually destroy the
1135    // window, OnWindowPosChanged() notices and calls WasHidden() (which
1136    // calls us).
1137    RenderWidgetHostViewPort* rwhv =
1138        RenderWidgetHostViewPort::FromRWHV(GetRenderWidgetHostView());
1139    if (rwhv)
1140      rwhv->WasHidden();
1141  }
1142
1143  should_normally_be_visible_ = false;
1144  NotificationService::current()->Notify(
1145      NOTIFICATION_WEB_CONTENTS_VISIBILITY_CHANGED,
1146      Source<WebContents>(this),
1147      Details<const bool>(&should_normally_be_visible_));
1148}
1149
1150bool WebContentsImpl::NeedToFireBeforeUnload() {
1151  // TODO(creis): Should we fire even for interstitial pages?
1152  return WillNotifyDisconnection() &&
1153      !ShowingInterstitialPage() &&
1154      !static_cast<RenderViewHostImpl*>(
1155          GetRenderViewHost())->SuddenTerminationAllowed();
1156}
1157
1158void WebContentsImpl::Stop() {
1159  render_manager_.Stop();
1160  FOR_EACH_OBSERVER(WebContentsObserver, observers_, StopNavigation());
1161}
1162
1163WebContents* WebContentsImpl::Clone() {
1164  // We use our current SiteInstance since the cloned entry will use it anyway.
1165  // We pass our own opener so that the cloned page can access it if it was
1166  // before.
1167  CreateParams create_params(GetBrowserContext(), GetSiteInstance());
1168  create_params.initial_size = view_->GetContainerSize();
1169  WebContentsImpl* tc = CreateWithOpener(create_params, opener_);
1170  tc->GetController().CopyStateFrom(controller_);
1171  FOR_EACH_OBSERVER(WebContentsObserver,
1172                    observers_,
1173                    DidCloneToNewWebContents(this, tc));
1174  return tc;
1175}
1176
1177void WebContentsImpl::Observe(int type,
1178                              const NotificationSource& source,
1179                              const NotificationDetails& details) {
1180  switch (type) {
1181    case NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED: {
1182      RenderWidgetHost* host = Source<RenderWidgetHost>(source).ptr();
1183      for (PendingWidgetViews::iterator i = pending_widget_views_.begin();
1184           i != pending_widget_views_.end(); ++i) {
1185        if (host->GetView() == i->second) {
1186          pending_widget_views_.erase(i);
1187          break;
1188        }
1189      }
1190      break;
1191    }
1192    default:
1193      NOTREACHED();
1194  }
1195}
1196
1197void WebContentsImpl::Init(const WebContents::CreateParams& params) {
1198  render_manager_.Init(
1199      params.browser_context, params.site_instance, params.routing_id,
1200      params.main_frame_routing_id);
1201
1202  view_.reset(GetContentClient()->browser()->
1203      OverrideCreateWebContentsView(this, &render_view_host_delegate_view_));
1204  if (view_) {
1205    CHECK(render_view_host_delegate_view_);
1206  } else {
1207    WebContentsViewDelegate* delegate =
1208        GetContentClient()->browser()->GetWebContentsViewDelegate(this);
1209
1210    if (browser_plugin_guest_) {
1211      scoped_ptr<WebContentsViewPort> platform_view(CreateWebContentsView(
1212          this, delegate, &render_view_host_delegate_view_));
1213
1214      WebContentsViewGuest* rv = new WebContentsViewGuest(
1215          this, browser_plugin_guest_.get(), platform_view.Pass(),
1216          render_view_host_delegate_view_);
1217      render_view_host_delegate_view_ = rv;
1218      view_.reset(rv);
1219    } else {
1220      // Regular WebContentsView.
1221      view_.reset(CreateWebContentsView(
1222          this, delegate, &render_view_host_delegate_view_));
1223    }
1224    CHECK(render_view_host_delegate_view_);
1225  }
1226  CHECK(view_.get());
1227
1228  gfx::Size initial_size = params.initial_size;
1229  view_->CreateView(initial_size, params.context);
1230
1231  // Listen for whether our opener gets destroyed.
1232  if (opener_)
1233    AddDestructionObserver(opener_);
1234
1235  registrar_.Add(this,
1236                 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1237                 NotificationService::AllBrowserContextsAndSources());
1238#if defined(OS_ANDROID)
1239  java_bridge_dispatcher_host_manager_.reset(
1240      new JavaBridgeDispatcherHostManager(this));
1241#endif
1242
1243#if defined(OS_ANDROID)
1244  date_time_chooser_.reset(new DateTimeChooserAndroid());
1245#endif
1246}
1247
1248void WebContentsImpl::OnWebContentsDestroyed(WebContentsImpl* web_contents) {
1249  RemoveDestructionObserver(web_contents);
1250
1251  // Clear the opener if it has been closed.
1252  if (web_contents == opener_) {
1253    opener_ = NULL;
1254    return;
1255  }
1256  // Clear a pending contents that has been closed before being shown.
1257  for (PendingContents::iterator iter = pending_contents_.begin();
1258       iter != pending_contents_.end();
1259       ++iter) {
1260    if (iter->second != web_contents)
1261      continue;
1262    pending_contents_.erase(iter);
1263    return;
1264  }
1265  NOTREACHED();
1266}
1267
1268void WebContentsImpl::AddDestructionObserver(WebContentsImpl* web_contents) {
1269  if (!ContainsKey(destruction_observers_, web_contents)) {
1270    destruction_observers_[web_contents] =
1271        new DestructionObserver(this, web_contents);
1272  }
1273}
1274
1275void WebContentsImpl::RemoveDestructionObserver(WebContentsImpl* web_contents) {
1276  DestructionObservers::iterator iter =
1277      destruction_observers_.find(web_contents);
1278  if (iter != destruction_observers_.end()) {
1279    delete destruction_observers_[web_contents];
1280    destruction_observers_.erase(iter);
1281  }
1282}
1283
1284void WebContentsImpl::AddObserver(WebContentsObserver* observer) {
1285  observers_.AddObserver(observer);
1286}
1287
1288void WebContentsImpl::RemoveObserver(WebContentsObserver* observer) {
1289  observers_.RemoveObserver(observer);
1290}
1291
1292void WebContentsImpl::Activate() {
1293  if (delegate_)
1294    delegate_->ActivateContents(this);
1295}
1296
1297void WebContentsImpl::Deactivate() {
1298  if (delegate_)
1299    delegate_->DeactivateContents(this);
1300}
1301
1302void WebContentsImpl::LostCapture() {
1303  if (delegate_)
1304    delegate_->LostCapture();
1305}
1306
1307void WebContentsImpl::RenderWidgetDeleted(
1308    RenderWidgetHostImpl* render_widget_host) {
1309  if (is_being_destroyed_) {
1310    // |created_widgets_| might have been destroyed.
1311    return;
1312  }
1313
1314  std::set<RenderWidgetHostImpl*>::iterator iter =
1315      created_widgets_.find(render_widget_host);
1316  if (iter != created_widgets_.end())
1317    created_widgets_.erase(iter);
1318
1319  if (render_widget_host &&
1320      render_widget_host->GetRoutingID() == fullscreen_widget_routing_id_) {
1321    FOR_EACH_OBSERVER(WebContentsObserver,
1322                      observers_,
1323                      DidDestroyFullscreenWidget(
1324                          fullscreen_widget_routing_id_));
1325    fullscreen_widget_routing_id_ = MSG_ROUTING_NONE;
1326  }
1327}
1328
1329bool WebContentsImpl::PreHandleKeyboardEvent(
1330    const NativeWebKeyboardEvent& event,
1331    bool* is_keyboard_shortcut) {
1332  return delegate_ &&
1333      delegate_->PreHandleKeyboardEvent(this, event, is_keyboard_shortcut);
1334}
1335
1336void WebContentsImpl::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
1337  if (browser_plugin_embedder_ &&
1338      browser_plugin_embedder_->HandleKeyboardEvent(event)) {
1339    return;
1340  }
1341
1342  if (delegate_)
1343    delegate_->HandleKeyboardEvent(this, event);
1344}
1345
1346bool WebContentsImpl::PreHandleWheelEvent(
1347    const WebKit::WebMouseWheelEvent& event) {
1348#if !defined(OS_MACOSX)
1349  // On platforms other than Mac, control+mousewheel changes zoom. On Mac, this
1350  // isn't done for two reasons:
1351  //   -the OS already has a gesture to do this through pinch-zoom
1352  //   -if a user starts an inertial scroll, let's go, and presses control
1353  //      (i.e. control+tab) then the OS's buffered scroll events will come in
1354  //      with control key set which isn't what the user wants
1355  if (delegate_ &&
1356      event.wheelTicksY &&
1357      (event.modifiers & WebKit::WebInputEvent::ControlKey)) {
1358    delegate_->ContentsZoomChange(event.wheelTicksY > 0);
1359    return true;
1360  }
1361#endif
1362
1363  return false;
1364}
1365
1366#if defined(OS_WIN) && defined(USE_AURA)
1367gfx::NativeViewAccessible WebContentsImpl::GetParentNativeViewAccessible() {
1368  return accessible_parent_;
1369}
1370#endif
1371
1372void WebContentsImpl::HandleMouseDown() {
1373  if (delegate_)
1374    delegate_->HandleMouseDown();
1375}
1376
1377void WebContentsImpl::HandleMouseUp() {
1378  if (delegate_)
1379    delegate_->HandleMouseUp();
1380}
1381
1382void WebContentsImpl::HandlePointerActivate() {
1383  if (delegate_)
1384    delegate_->HandlePointerActivate();
1385}
1386
1387void WebContentsImpl::HandleGestureBegin() {
1388  if (delegate_)
1389    delegate_->HandleGestureBegin();
1390}
1391
1392void WebContentsImpl::HandleGestureEnd() {
1393  if (delegate_)
1394    delegate_->HandleGestureEnd();
1395}
1396
1397void WebContentsImpl::ToggleFullscreenMode(bool enter_fullscreen) {
1398  if (delegate_)
1399    delegate_->ToggleFullscreenModeForTab(this, enter_fullscreen);
1400}
1401
1402bool WebContentsImpl::IsFullscreenForCurrentTab() const {
1403  return delegate_ ? delegate_->IsFullscreenForTabOrPending(this) : false;
1404}
1405
1406void WebContentsImpl::RequestToLockMouse(bool user_gesture,
1407                                         bool last_unlocked_by_target) {
1408  if (delegate_) {
1409    delegate_->RequestToLockMouse(this, user_gesture, last_unlocked_by_target);
1410  } else {
1411    GotResponseToLockMouseRequest(false);
1412  }
1413}
1414
1415void WebContentsImpl::LostMouseLock() {
1416  if (delegate_)
1417    delegate_->LostMouseLock();
1418}
1419
1420void WebContentsImpl::CreateNewWindow(
1421    int route_id,
1422    int main_frame_route_id,
1423    const ViewHostMsg_CreateWindow_Params& params,
1424    SessionStorageNamespace* session_storage_namespace) {
1425  if (delegate_ &&
1426      !delegate_->ShouldCreateWebContents(this,
1427                                          route_id,
1428                                          params.window_container_type,
1429                                          params.frame_name,
1430                                          params.target_url,
1431                                          params.referrer,
1432                                          params.disposition,
1433                                          params.features,
1434                                          params.user_gesture,
1435                                          params.opener_suppressed)) {
1436    GetRenderViewHost()->GetProcess()->ResumeRequestsForView(route_id);
1437    GetRenderViewHost()->GetProcess()->ResumeRequestsForView(
1438        main_frame_route_id);
1439    return;
1440  }
1441
1442  // We usually create the new window in the same BrowsingInstance (group of
1443  // script-related windows), by passing in the current SiteInstance.  However,
1444  // if the opener is being suppressed (in a non-guest), we create a new
1445  // SiteInstance in its own BrowsingInstance.
1446  bool is_guest = GetRenderProcessHost()->IsGuest();
1447
1448  scoped_refptr<SiteInstance> site_instance =
1449      params.opener_suppressed && !is_guest ?
1450      SiteInstance::CreateForURL(GetBrowserContext(), params.target_url) :
1451      GetSiteInstance();
1452
1453  // Create the new web contents. This will automatically create the new
1454  // WebContentsView. In the future, we may want to create the view separately.
1455  WebContentsImpl* new_contents =
1456      new WebContentsImpl(GetBrowserContext(),
1457                          params.opener_suppressed ? NULL : this);
1458
1459  // We must assign the SessionStorageNamespace before calling Init().
1460  //
1461  // http://crbug.com/142685
1462  const std::string& partition_id =
1463      GetContentClient()->browser()->
1464          GetStoragePartitionIdForSite(GetBrowserContext(),
1465                                       site_instance->GetSiteURL());
1466  StoragePartition* partition = BrowserContext::GetStoragePartition(
1467      GetBrowserContext(), site_instance.get());
1468  DOMStorageContextImpl* dom_storage_context =
1469      static_cast<DOMStorageContextImpl*>(partition->GetDOMStorageContext());
1470  SessionStorageNamespaceImpl* session_storage_namespace_impl =
1471      static_cast<SessionStorageNamespaceImpl*>(session_storage_namespace);
1472  CHECK(session_storage_namespace_impl->IsFromContext(dom_storage_context));
1473  new_contents->GetController().SetSessionStorageNamespace(
1474      partition_id,
1475      session_storage_namespace);
1476  CreateParams create_params(GetBrowserContext(), site_instance.get());
1477  create_params.routing_id = route_id;
1478  create_params.main_frame_routing_id = main_frame_route_id;
1479  if (!is_guest) {
1480    create_params.context = view_->GetNativeView();
1481    create_params.initial_size = view_->GetContainerSize();
1482  } else {
1483    // This makes |new_contents| act as a guest.
1484    // For more info, see comment above class BrowserPluginGuest.
1485    int instance_id = GetBrowserPluginGuestManager()->get_next_instance_id();
1486    WebContentsImpl* new_contents_impl =
1487        static_cast<WebContentsImpl*>(new_contents);
1488    BrowserPluginGuest::CreateWithOpener(instance_id, new_contents_impl,
1489        GetBrowserPluginGuest(), !!new_contents_impl->opener());
1490  }
1491  new_contents->Init(create_params);
1492
1493  // Save the window for later if we're not suppressing the opener (since it
1494  // will be shown immediately).
1495  if (!params.opener_suppressed) {
1496    if (!is_guest) {
1497      WebContentsViewPort* new_view = new_contents->view_.get();
1498
1499      // TODO(brettw): It seems bogus that we have to call this function on the
1500      // newly created object and give it one of its own member variables.
1501      new_view->CreateViewForWidget(new_contents->GetRenderViewHost());
1502    }
1503    // Save the created window associated with the route so we can show it
1504    // later.
1505    DCHECK_NE(MSG_ROUTING_NONE, route_id);
1506    pending_contents_[route_id] = new_contents;
1507    AddDestructionObserver(new_contents);
1508  }
1509
1510  if (delegate_) {
1511    delegate_->WebContentsCreated(
1512        this, params.opener_frame_id, params.frame_name,
1513        params.target_url, new_contents);
1514  }
1515
1516  if (params.opener_suppressed) {
1517    // When the opener is suppressed, the original renderer cannot access the
1518    // new window.  As a result, we need to show and navigate the window here.
1519    bool was_blocked = false;
1520    if (delegate_) {
1521      gfx::Rect initial_pos;
1522      delegate_->AddNewContents(
1523          this, new_contents, params.disposition, initial_pos,
1524          params.user_gesture, &was_blocked);
1525    }
1526    if (!was_blocked) {
1527      OpenURLParams open_params(params.target_url,
1528                                Referrer(),
1529                                CURRENT_TAB,
1530                                PAGE_TRANSITION_LINK,
1531                                true /* is_renderer_initiated */);
1532      open_params.user_gesture = params.user_gesture;
1533      new_contents->OpenURL(open_params);
1534    }
1535  }
1536}
1537
1538void WebContentsImpl::CreateNewWidget(int route_id,
1539                                      WebKit::WebPopupType popup_type) {
1540  CreateNewWidget(route_id, false, popup_type);
1541}
1542
1543void WebContentsImpl::CreateNewFullscreenWidget(int route_id) {
1544  CreateNewWidget(route_id, true, WebKit::WebPopupTypeNone);
1545}
1546
1547void WebContentsImpl::CreateNewWidget(int route_id,
1548                                      bool is_fullscreen,
1549                                      WebKit::WebPopupType popup_type) {
1550  RenderProcessHost* process = GetRenderProcessHost();
1551  RenderWidgetHostImpl* widget_host =
1552      new RenderWidgetHostImpl(this, process, route_id);
1553  created_widgets_.insert(widget_host);
1554
1555  RenderWidgetHostViewPort* widget_view = RenderWidgetHostViewPort::FromRWHV(
1556      view_->CreateViewForPopupWidget(widget_host));
1557  if (!widget_view)
1558    return;
1559  if (!is_fullscreen) {
1560    // Popups should not get activated.
1561    widget_view->SetPopupType(popup_type);
1562  }
1563  // Save the created widget associated with the route so we can show it later.
1564  pending_widget_views_[route_id] = widget_view;
1565
1566#if defined(OS_MACOSX)
1567  // A RenderWidgetHostViewMac has lifetime scoped to the view. We'll retain it
1568  // to allow it to survive the trip without being hosted.
1569  base::mac::NSObjectRetain(widget_view->GetNativeView());
1570#endif
1571}
1572
1573void WebContentsImpl::ShowCreatedWindow(int route_id,
1574                                        WindowOpenDisposition disposition,
1575                                        const gfx::Rect& initial_pos,
1576                                        bool user_gesture) {
1577  WebContentsImpl* contents = GetCreatedWindow(route_id);
1578  if (contents) {
1579    WebContentsDelegate* delegate = GetDelegate();
1580    if (delegate) {
1581      delegate->AddNewContents(
1582          this, contents, disposition, initial_pos, user_gesture, NULL);
1583    }
1584  }
1585}
1586
1587void WebContentsImpl::ShowCreatedWidget(int route_id,
1588                                        const gfx::Rect& initial_pos) {
1589  ShowCreatedWidget(route_id, false, initial_pos);
1590}
1591
1592void WebContentsImpl::ShowCreatedFullscreenWidget(int route_id) {
1593  ShowCreatedWidget(route_id, true, gfx::Rect());
1594
1595  DCHECK_EQ(MSG_ROUTING_NONE, fullscreen_widget_routing_id_);
1596  fullscreen_widget_routing_id_ = route_id;
1597  FOR_EACH_OBSERVER(WebContentsObserver,
1598                    observers_,
1599                    DidShowFullscreenWidget(route_id));
1600}
1601
1602void WebContentsImpl::ShowCreatedWidget(int route_id,
1603                                        bool is_fullscreen,
1604                                        const gfx::Rect& initial_pos) {
1605  if (delegate_)
1606    delegate_->RenderWidgetShowing();
1607
1608  RenderWidgetHostViewPort* widget_host_view =
1609      RenderWidgetHostViewPort::FromRWHV(GetCreatedWidget(route_id));
1610  if (!widget_host_view)
1611    return;
1612  if (is_fullscreen)
1613    widget_host_view->InitAsFullscreen(GetRenderWidgetHostViewPort());
1614  else
1615    widget_host_view->InitAsPopup(GetRenderWidgetHostViewPort(), initial_pos);
1616
1617  RenderWidgetHostImpl* render_widget_host_impl =
1618      RenderWidgetHostImpl::From(widget_host_view->GetRenderWidgetHost());
1619  render_widget_host_impl->Init();
1620  // Only allow privileged mouse lock for fullscreen render widget, which is
1621  // used to implement Pepper Flash fullscreen.
1622  render_widget_host_impl->set_allow_privileged_mouse_lock(is_fullscreen);
1623
1624#if defined(OS_MACOSX)
1625  // A RenderWidgetHostViewMac has lifetime scoped to the view. Now that it's
1626  // properly embedded (or purposefully ignored) we can release the retain we
1627  // took in CreateNewWidget().
1628  base::mac::NSObjectRelease(widget_host_view->GetNativeView());
1629#endif
1630}
1631
1632WebContentsImpl* WebContentsImpl::GetCreatedWindow(int route_id) {
1633  PendingContents::iterator iter = pending_contents_.find(route_id);
1634
1635  // Certain systems can block the creation of new windows. If we didn't succeed
1636  // in creating one, just return NULL.
1637  if (iter == pending_contents_.end()) {
1638    return NULL;
1639  }
1640
1641  WebContentsImpl* new_contents = iter->second;
1642  pending_contents_.erase(route_id);
1643  RemoveDestructionObserver(new_contents);
1644
1645  // Don't initialize the guest WebContents immediately.
1646  if (new_contents->GetRenderProcessHost()->IsGuest())
1647    return new_contents;
1648
1649  if (!new_contents->GetRenderProcessHost()->HasConnection() ||
1650      !new_contents->GetRenderViewHost()->GetView())
1651    return NULL;
1652
1653  // TODO(brettw): It seems bogus to reach into here and initialize the host.
1654  static_cast<RenderViewHostImpl*>(new_contents->GetRenderViewHost())->Init();
1655  return new_contents;
1656}
1657
1658RenderWidgetHostView* WebContentsImpl::GetCreatedWidget(int route_id) {
1659  PendingWidgetViews::iterator iter = pending_widget_views_.find(route_id);
1660  if (iter == pending_widget_views_.end()) {
1661    DCHECK(false);
1662    return NULL;
1663  }
1664
1665  RenderWidgetHostView* widget_host_view = iter->second;
1666  pending_widget_views_.erase(route_id);
1667
1668  RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();
1669  if (!widget_host->GetProcess()->HasConnection()) {
1670    // The view has gone away or the renderer crashed. Nothing to do.
1671    return NULL;
1672  }
1673
1674  return widget_host_view;
1675}
1676
1677void WebContentsImpl::ShowContextMenu(const ContextMenuParams& params) {
1678  // Allow WebContentsDelegates to handle the context menu operation first.
1679  if (delegate_ && delegate_->HandleContextMenu(params))
1680    return;
1681
1682  render_view_host_delegate_view_->ShowContextMenu(params);
1683}
1684
1685void WebContentsImpl::RequestMediaAccessPermission(
1686    const MediaStreamRequest& request,
1687    const MediaResponseCallback& callback) {
1688  if (delegate_)
1689    delegate_->RequestMediaAccessPermission(this, request, callback);
1690  else
1691    callback.Run(MediaStreamDevices(), scoped_ptr<MediaStreamUI>());
1692}
1693
1694SessionStorageNamespace* WebContentsImpl::GetSessionStorageNamespace(
1695    SiteInstance* instance) {
1696  return controller_.GetSessionStorageNamespace(instance);
1697}
1698
1699void WebContentsImpl::DidSendScreenRects(RenderWidgetHostImpl* rwh) {
1700  if (browser_plugin_embedder_)
1701    browser_plugin_embedder_->DidSendScreenRects();
1702}
1703
1704void WebContentsImpl::UpdatePreferredSize(const gfx::Size& pref_size) {
1705  preferred_size_ = pref_size;
1706  if (delegate_)
1707    delegate_->UpdatePreferredSize(this, pref_size);
1708}
1709
1710void WebContentsImpl::ResizeDueToAutoResize(const gfx::Size& new_size) {
1711  if (delegate_)
1712    delegate_->ResizeDueToAutoResize(this, new_size);
1713}
1714
1715WebContents* WebContentsImpl::OpenURL(const OpenURLParams& params) {
1716  if (!delegate_)
1717    return NULL;
1718
1719  WebContents* new_contents = delegate_->OpenURLFromTab(this, params);
1720  return new_contents;
1721}
1722
1723bool WebContentsImpl::Send(IPC::Message* message) {
1724  if (!GetRenderViewHost()) {
1725    delete message;
1726    return false;
1727  }
1728
1729  return GetRenderViewHost()->Send(message);
1730}
1731
1732bool WebContentsImpl::NavigateToPendingEntry(
1733    NavigationController::ReloadType reload_type) {
1734  return NavigateToEntry(
1735      *NavigationEntryImpl::FromNavigationEntry(controller_.GetPendingEntry()),
1736      reload_type);
1737}
1738
1739void WebContentsImpl::RenderViewForInterstitialPageCreated(
1740    RenderViewHost* render_view_host) {
1741  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1742                    RenderViewForInterstitialPageCreated(render_view_host));
1743}
1744
1745void WebContentsImpl::AttachInterstitialPage(
1746    InterstitialPageImpl* interstitial_page) {
1747  DCHECK(interstitial_page);
1748  render_manager_.set_interstitial_page(interstitial_page);
1749  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1750                    DidAttachInterstitialPage());
1751}
1752
1753void WebContentsImpl::DetachInterstitialPage() {
1754  if (GetInterstitialPage())
1755    render_manager_.remove_interstitial_page();
1756  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1757                    DidDetachInterstitialPage());
1758}
1759
1760bool WebContentsImpl::NavigateToEntry(
1761    const NavigationEntryImpl& entry,
1762    NavigationController::ReloadType reload_type) {
1763  TRACE_EVENT0("browser", "WebContentsImpl::NavigateToEntry");
1764
1765  // The renderer will reject IPC messages with URLs longer than
1766  // this limit, so don't attempt to navigate with a longer URL.
1767  if (entry.GetURL().spec().size() > kMaxURLChars)
1768    return false;
1769
1770  RenderViewHostImpl* dest_render_view_host =
1771      static_cast<RenderViewHostImpl*>(render_manager_.Navigate(entry));
1772  if (!dest_render_view_host)
1773    return false;  // Unable to create the desired render view host.
1774
1775  // For security, we should never send non-Web-UI URLs to a Web UI renderer.
1776  // Double check that here.
1777  int enabled_bindings = dest_render_view_host->GetEnabledBindings();
1778  bool data_urls_allowed = delegate_ && delegate_->CanLoadDataURLsInWebUI();
1779  bool is_allowed_in_web_ui_renderer =
1780      WebUIControllerFactoryRegistry::GetInstance()->IsURLAcceptableForWebUI(
1781          GetBrowserContext(), entry.GetURL(), data_urls_allowed);
1782  if ((enabled_bindings & BINDINGS_POLICY_WEB_UI) &&
1783      !is_allowed_in_web_ui_renderer) {
1784    // Log the URL to help us diagnose any future failures of this CHECK.
1785    GetContentClient()->SetActiveURL(entry.GetURL());
1786    CHECK(0);
1787  }
1788
1789  // Notify observers that we will navigate in this RV.
1790  FOR_EACH_OBSERVER(WebContentsObserver,
1791                    observers_,
1792                    AboutToNavigateRenderView(dest_render_view_host));
1793
1794  // Used for page load time metrics.
1795  current_load_start_ = base::TimeTicks::Now();
1796
1797  // Navigate in the desired RenderViewHost.
1798  ViewMsg_Navigate_Params navigate_params;
1799  MakeNavigateParams(entry, controller_, delegate_, reload_type,
1800                     &navigate_params);
1801  dest_render_view_host->Navigate(navigate_params);
1802
1803  if (entry.GetPageID() == -1) {
1804    // HACK!!  This code suppresses javascript: URLs from being added to
1805    // session history, which is what we want to do for javascript: URLs that
1806    // do not generate content.  What we really need is a message from the
1807    // renderer telling us that a new page was not created.  The same message
1808    // could be used for mailto: URLs and the like.
1809    if (entry.GetURL().SchemeIs(chrome::kJavaScriptScheme))
1810      return false;
1811  }
1812
1813  // Notify observers about navigation.
1814  FOR_EACH_OBSERVER(WebContentsObserver,
1815                    observers_,
1816                    NavigateToPendingEntry(entry.GetURL(), reload_type));
1817
1818  if (delegate_)
1819    delegate_->DidNavigateToPendingEntry(this);
1820
1821  return true;
1822}
1823
1824void WebContentsImpl::SetHistoryLengthAndPrune(
1825    const SiteInstance* site_instance,
1826    int history_length,
1827    int32 minimum_page_id) {
1828  // SetHistoryLengthAndPrune doesn't work when there are pending cross-site
1829  // navigations. Callers should ensure that this is the case.
1830  if (render_manager_.pending_render_view_host()) {
1831    NOTREACHED();
1832    return;
1833  }
1834  RenderViewHostImpl* rvh = GetRenderViewHostImpl();
1835  if (!rvh) {
1836    NOTREACHED();
1837    return;
1838  }
1839  if (site_instance && rvh->GetSiteInstance() != site_instance) {
1840    NOTREACHED();
1841    return;
1842  }
1843  Send(new ViewMsg_SetHistoryLengthAndPrune(GetRoutingID(),
1844                                            history_length,
1845                                            minimum_page_id));
1846}
1847
1848void WebContentsImpl::FocusThroughTabTraversal(bool reverse) {
1849  if (ShowingInterstitialPage()) {
1850    render_manager_.interstitial_page()->FocusThroughTabTraversal(reverse);
1851    return;
1852  }
1853  GetRenderViewHostImpl()->SetInitialFocus(reverse);
1854}
1855
1856bool WebContentsImpl::ShowingInterstitialPage() const {
1857  return render_manager_.interstitial_page() != NULL;
1858}
1859
1860InterstitialPage* WebContentsImpl::GetInterstitialPage() const {
1861  return render_manager_.interstitial_page();
1862}
1863
1864bool WebContentsImpl::IsSavable() {
1865  // WebKit creates Document object when MIME type is application/xhtml+xml,
1866  // so we also support this MIME type.
1867  return contents_mime_type_ == "text/html" ||
1868         contents_mime_type_ == "text/xml" ||
1869         contents_mime_type_ == "application/xhtml+xml" ||
1870         contents_mime_type_ == "text/plain" ||
1871         contents_mime_type_ == "text/css" ||
1872         net::IsSupportedJavascriptMimeType(contents_mime_type_.c_str());
1873}
1874
1875void WebContentsImpl::OnSavePage() {
1876  // If we can not save the page, try to download it.
1877  if (!IsSavable()) {
1878    RecordDownloadSource(INITIATED_BY_SAVE_PACKAGE_ON_NON_HTML);
1879    SaveFrame(GetURL(), Referrer());
1880    return;
1881  }
1882
1883  Stop();
1884
1885  // Create the save package and possibly prompt the user for the name to save
1886  // the page as. The user prompt is an asynchronous operation that runs on
1887  // another thread.
1888  save_package_ = new SavePackage(this);
1889  save_package_->GetSaveInfo();
1890}
1891
1892// Used in automated testing to bypass prompting the user for file names.
1893// Instead, the names and paths are hard coded rather than running them through
1894// file name sanitation and extension / mime checking.
1895bool WebContentsImpl::SavePage(const base::FilePath& main_file,
1896                               const base::FilePath& dir_path,
1897                               SavePageType save_type) {
1898  // Stop the page from navigating.
1899  Stop();
1900
1901  save_package_ = new SavePackage(this, save_type, main_file, dir_path);
1902  return save_package_->Init(SavePackageDownloadCreatedCallback());
1903}
1904
1905void WebContentsImpl::SaveFrame(const GURL& url,
1906                                const Referrer& referrer) {
1907  if (!GetURL().is_valid())
1908    return;
1909  bool is_main_frame = (url == GetURL());
1910
1911  DownloadManager* dlm =
1912      BrowserContext::GetDownloadManager(GetBrowserContext());
1913  if (!dlm)
1914    return;
1915  int64 post_id = -1;
1916  if (is_main_frame) {
1917    const NavigationEntry* entry = controller_.GetActiveEntry();
1918    if (entry)
1919      post_id = entry->GetPostID();
1920  }
1921  scoped_ptr<DownloadUrlParameters> params(
1922      DownloadUrlParameters::FromWebContents(this, url));
1923  params->set_referrer(referrer);
1924  params->set_post_id(post_id);
1925  params->set_prefer_cache(true);
1926  if (post_id >= 0)
1927    params->set_method("POST");
1928  params->set_prompt(true);
1929  dlm->DownloadUrl(params.Pass());
1930}
1931
1932void WebContentsImpl::GenerateMHTML(
1933    const base::FilePath& file,
1934    const base::Callback<void(const base::FilePath&, int64)>& callback) {
1935  MHTMLGenerationManager::GetInstance()->GenerateMHTML(this, file, callback);
1936}
1937
1938bool WebContentsImpl::IsActiveEntry(int32 page_id) {
1939  NavigationEntryImpl* active_entry =
1940      NavigationEntryImpl::FromNavigationEntry(controller_.GetActiveEntry());
1941  return (active_entry != NULL &&
1942          active_entry->site_instance() == GetSiteInstance() &&
1943          active_entry->GetPageID() == page_id);
1944}
1945
1946const std::string& WebContentsImpl::GetContentsMimeType() const {
1947  return contents_mime_type_;
1948}
1949
1950bool WebContentsImpl::WillNotifyDisconnection() const {
1951  return notify_disconnection_;
1952}
1953
1954void WebContentsImpl::SetOverrideEncoding(const std::string& encoding) {
1955  SetEncoding(encoding);
1956  Send(new ViewMsg_SetPageEncoding(GetRoutingID(), encoding));
1957}
1958
1959void WebContentsImpl::ResetOverrideEncoding() {
1960  encoding_.clear();
1961  Send(new ViewMsg_ResetPageEncodingToDefault(GetRoutingID()));
1962}
1963
1964RendererPreferences* WebContentsImpl::GetMutableRendererPrefs() {
1965  return &renderer_preferences_;
1966}
1967
1968void WebContentsImpl::Close() {
1969  Close(GetRenderViewHost());
1970}
1971
1972void WebContentsImpl::DragSourceEndedAt(int client_x, int client_y,
1973    int screen_x, int screen_y, WebKit::WebDragOperation operation) {
1974  if (browser_plugin_embedder_.get())
1975    browser_plugin_embedder_->DragSourceEndedAt(client_x, client_y,
1976        screen_x, screen_y, operation);
1977  if (GetRenderViewHost())
1978    GetRenderViewHostImpl()->DragSourceEndedAt(client_x, client_y,
1979        screen_x, screen_y, operation);
1980}
1981
1982void WebContentsImpl::DragSourceMovedTo(int client_x, int client_y,
1983                                        int screen_x, int screen_y) {
1984  if (browser_plugin_embedder_.get())
1985    browser_plugin_embedder_->DragSourceMovedTo(client_x, client_y,
1986                                                screen_x, screen_y);
1987  if (GetRenderViewHost())
1988    GetRenderViewHostImpl()->DragSourceMovedTo(client_x, client_y,
1989                                               screen_x, screen_y);
1990}
1991
1992void WebContentsImpl::SystemDragEnded() {
1993  if (GetRenderViewHost())
1994    GetRenderViewHostImpl()->DragSourceSystemDragEnded();
1995  if (delegate_)
1996    delegate_->DragEnded();
1997  if (browser_plugin_embedder_.get())
1998    browser_plugin_embedder_->SystemDragEnded();
1999}
2000
2001void WebContentsImpl::UserGestureDone() {
2002  OnUserGesture();
2003}
2004
2005void WebContentsImpl::SetClosedByUserGesture(bool value) {
2006  closed_by_user_gesture_ = value;
2007}
2008
2009bool WebContentsImpl::GetClosedByUserGesture() const {
2010  return closed_by_user_gesture_;
2011}
2012
2013double WebContentsImpl::GetZoomLevel() const {
2014  HostZoomMapImpl* zoom_map = static_cast<HostZoomMapImpl*>(
2015      HostZoomMap::GetForBrowserContext(GetBrowserContext()));
2016  if (!zoom_map)
2017    return 0;
2018
2019  double zoom_level;
2020  if (temporary_zoom_settings_) {
2021    zoom_level = zoom_map->GetTemporaryZoomLevel(
2022        GetRenderProcessHost()->GetID(), GetRenderViewHost()->GetRoutingID());
2023  } else {
2024    GURL url;
2025    NavigationEntry* active_entry = GetController().GetActiveEntry();
2026    // Since zoom map is updated using rewritten URL, use rewritten URL
2027    // to get the zoom level.
2028    url = active_entry ? active_entry->GetURL() : GURL::EmptyGURL();
2029    zoom_level = zoom_map->GetZoomLevelForHostAndScheme(url.scheme(),
2030        net::GetHostOrSpecFromURL(url));
2031  }
2032  return zoom_level;
2033}
2034
2035int WebContentsImpl::GetZoomPercent(bool* enable_increment,
2036                                    bool* enable_decrement) const {
2037  *enable_decrement = *enable_increment = false;
2038  // Calculate the zoom percent from the factor. Round up to the nearest whole
2039  // number.
2040  int percent = static_cast<int>(
2041      ZoomLevelToZoomFactor(GetZoomLevel()) * 100 + 0.5);
2042  *enable_decrement = percent > minimum_zoom_percent_;
2043  *enable_increment = percent < maximum_zoom_percent_;
2044  return percent;
2045}
2046
2047void WebContentsImpl::ViewSource() {
2048  if (!delegate_)
2049    return;
2050
2051  NavigationEntry* active_entry = GetController().GetActiveEntry();
2052  if (!active_entry)
2053    return;
2054
2055  delegate_->ViewSourceForTab(this, active_entry->GetURL());
2056}
2057
2058void WebContentsImpl::ViewFrameSource(const GURL& url,
2059                                      const PageState& page_state) {
2060  if (!delegate_)
2061    return;
2062
2063  delegate_->ViewSourceForFrame(this, url, page_state);
2064}
2065
2066int WebContentsImpl::GetMinimumZoomPercent() const {
2067  return minimum_zoom_percent_;
2068}
2069
2070int WebContentsImpl::GetMaximumZoomPercent() const {
2071  return maximum_zoom_percent_;
2072}
2073
2074gfx::Size WebContentsImpl::GetPreferredSize() const {
2075  return preferred_size_;
2076}
2077
2078bool WebContentsImpl::GotResponseToLockMouseRequest(bool allowed) {
2079  return GetRenderViewHost() ?
2080      GetRenderViewHostImpl()->GotResponseToLockMouseRequest(allowed) : false;
2081}
2082
2083bool WebContentsImpl::HasOpener() const {
2084  return opener_ != NULL;
2085}
2086
2087void WebContentsImpl::DidChooseColorInColorChooser(SkColor color) {
2088  Send(new ViewMsg_DidChooseColorResponse(
2089      GetRoutingID(), color_chooser_identifier_, color));
2090}
2091
2092void WebContentsImpl::DidEndColorChooser() {
2093  Send(new ViewMsg_DidEndColorChooser(GetRoutingID(),
2094                                      color_chooser_identifier_));
2095  color_chooser_.reset();
2096  color_chooser_identifier_ = 0;
2097}
2098
2099int WebContentsImpl::DownloadImage(const GURL& url,
2100                                   bool is_favicon,
2101                                   uint32_t preferred_image_size,
2102                                   uint32_t max_image_size,
2103                                   const ImageDownloadCallback& callback) {
2104  RenderViewHost* host = GetRenderViewHost();
2105  int id = StartDownload(
2106      host, url, is_favicon, preferred_image_size, max_image_size);
2107  image_download_map_[id] = callback;
2108  return id;
2109}
2110
2111bool WebContentsImpl::FocusLocationBarByDefault() {
2112  NavigationEntry* entry = controller_.GetActiveEntry();
2113  if (entry && entry->GetURL() == GURL(kAboutBlankURL))
2114    return true;
2115  return delegate_ && delegate_->ShouldFocusLocationBarByDefault(this);
2116}
2117
2118void WebContentsImpl::SetFocusToLocationBar(bool select_all) {
2119  if (delegate_)
2120    delegate_->SetFocusToLocationBar(select_all);
2121}
2122
2123void WebContentsImpl::DidStartProvisionalLoadForFrame(
2124    RenderViewHost* render_view_host,
2125    int64 frame_id,
2126    int64 parent_frame_id,
2127    bool is_main_frame,
2128    const GURL& url) {
2129  bool is_error_page = (url.spec() == kUnreachableWebDataURL);
2130  bool is_iframe_srcdoc = (url.spec() == kAboutSrcDocURL);
2131  GURL validated_url(url);
2132  RenderProcessHost* render_process_host =
2133      render_view_host->GetProcess();
2134  RenderViewHost::FilterURL(render_process_host, false, &validated_url);
2135
2136  if (is_main_frame) {
2137    DidChangeLoadProgress(0);
2138
2139    // If there is no browser-initiated pending entry for this navigation,
2140    // create one using the current SiteInstance, and ensure the address bar
2141    // updates accordingly.  We don't know the referrer or extra headers at this
2142    // point, but the referrer will be set properly upon commit.
2143    NavigationEntry* pending_entry = controller_.GetPendingEntry();
2144    bool has_browser_initiated_pending_entry = pending_entry &&
2145        !NavigationEntryImpl::FromNavigationEntry(pending_entry)->
2146            is_renderer_initiated();
2147    if (!has_browser_initiated_pending_entry) {
2148      NavigationEntryImpl* entry = NavigationEntryImpl::FromNavigationEntry(
2149          controller_.CreateNavigationEntry(validated_url,
2150                                            content::Referrer(),
2151                                            content::PAGE_TRANSITION_LINK,
2152                                            true /* is_renderer_initiated */,
2153                                            std::string(),
2154                                            GetBrowserContext()));
2155      entry->set_site_instance(
2156          static_cast<SiteInstanceImpl*>(GetSiteInstance()));
2157      controller_.SetPendingEntry(entry);
2158      NotifyNavigationStateChanged(content::INVALIDATE_TYPE_URL);
2159    }
2160  }
2161
2162  // Notify observers about the start of the provisional load.
2163  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2164                    DidStartProvisionalLoadForFrame(frame_id, parent_frame_id,
2165                    is_main_frame, validated_url, is_error_page,
2166                    is_iframe_srcdoc, render_view_host));
2167
2168  if (is_main_frame) {
2169    // Notify observers about the provisional change in the main frame URL.
2170    FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2171                      ProvisionalChangeToMainFrameUrl(validated_url,
2172                                                      render_view_host));
2173  }
2174}
2175
2176void WebContentsImpl::DidRedirectProvisionalLoad(
2177    RenderViewHost* render_view_host,
2178    int32 page_id,
2179    const GURL& source_url,
2180    const GURL& target_url) {
2181  // TODO(creis): Remove this method and have the pre-rendering code listen to
2182  // the ResourceDispatcherHost's RESOURCE_RECEIVED_REDIRECT notification
2183  // instead.  See http://crbug.com/78512.
2184  GURL validated_source_url(source_url);
2185  GURL validated_target_url(target_url);
2186  RenderProcessHost* render_process_host =
2187      render_view_host->GetProcess();
2188  RenderViewHost::FilterURL(render_process_host, false, &validated_source_url);
2189  RenderViewHost::FilterURL(render_process_host, false, &validated_target_url);
2190  NavigationEntry* entry;
2191  if (page_id == -1) {
2192    entry = controller_.GetPendingEntry();
2193  } else {
2194    entry = controller_.GetEntryWithPageID(render_view_host->GetSiteInstance(),
2195                                           page_id);
2196  }
2197  if (!entry || entry->GetURL() != validated_source_url)
2198    return;
2199
2200  // Notify observers about the provisional change in the main frame URL.
2201  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2202                    ProvisionalChangeToMainFrameUrl(validated_target_url,
2203                                                    render_view_host));
2204}
2205
2206void WebContentsImpl::DidFailProvisionalLoadWithError(
2207    RenderViewHost* render_view_host,
2208    const ViewHostMsg_DidFailProvisionalLoadWithError_Params& params) {
2209  VLOG(1) << "Failed Provisional Load: " << params.url.possibly_invalid_spec()
2210          << ", error_code: " << params.error_code
2211          << ", error_description: " << params.error_description
2212          << ", is_main_frame: " << params.is_main_frame
2213          << ", showing_repost_interstitial: " <<
2214            params.showing_repost_interstitial
2215          << ", frame_id: " << params.frame_id;
2216  GURL validated_url(params.url);
2217  RenderProcessHost* render_process_host =
2218      render_view_host->GetProcess();
2219  RenderViewHost::FilterURL(render_process_host, false, &validated_url);
2220
2221  if (net::ERR_ABORTED == params.error_code) {
2222    // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
2223    // This means that the interstitial won't be torn down properly, which is
2224    // bad. But if we have an interstitial, go back to another tab type, and
2225    // then load the same interstitial again, we could end up getting the first
2226    // interstitial's "failed" message (as a result of the cancel) when we're on
2227    // the second one.
2228    //
2229    // We can't tell this apart, so we think we're tearing down the current page
2230    // which will cause a crash later one. There is also some code in
2231    // RenderViewHostManager::RendererAbortedProvisionalLoad that is commented
2232    // out because of this problem.
2233    //
2234    // http://code.google.com/p/chromium/issues/detail?id=2855
2235    // Because this will not tear down the interstitial properly, if "back" is
2236    // back to another tab type, the interstitial will still be somewhat alive
2237    // in the previous tab type. If you navigate somewhere that activates the
2238    // tab with the interstitial again, you'll see a flash before the new load
2239    // commits of the interstitial page.
2240    if (ShowingInterstitialPage()) {
2241      LOG(WARNING) << "Discarding message during interstitial.";
2242      return;
2243    }
2244
2245    // Do not clear the pending entry if one exists, so that the user's typed
2246    // URL is not lost when a navigation fails or is aborted.  We'll allow
2247    // the view to clear the pending entry and typed URL if the user requests.
2248
2249    render_manager_.RendererAbortedProvisionalLoad(render_view_host);
2250  }
2251
2252  FOR_EACH_OBSERVER(WebContentsObserver,
2253                    observers_,
2254                    DidFailProvisionalLoad(params.frame_id,
2255                                           params.is_main_frame,
2256                                           validated_url,
2257                                           params.error_code,
2258                                           params.error_description,
2259                                           render_view_host));
2260}
2261
2262void WebContentsImpl::OnDidLoadResourceFromMemoryCache(
2263    const GURL& url,
2264    const std::string& security_info,
2265    const std::string& http_method,
2266    const std::string& mime_type,
2267    ResourceType::Type resource_type) {
2268  base::StatsCounter cache("WebKit.CacheHit");
2269  cache.Increment();
2270
2271  // Send out a notification that we loaded a resource from our memory cache.
2272  int cert_id = 0;
2273  net::CertStatus cert_status = 0;
2274  int security_bits = -1;
2275  int connection_status = 0;
2276  DeserializeSecurityInfo(security_info, &cert_id, &cert_status,
2277                          &security_bits, &connection_status);
2278  LoadFromMemoryCacheDetails details(
2279      url, GetRenderProcessHost()->GetID(), cert_id, cert_status, http_method,
2280      mime_type, resource_type);
2281
2282  NotificationService::current()->Notify(
2283      NOTIFICATION_LOAD_FROM_MEMORY_CACHE,
2284      Source<NavigationController>(&controller_),
2285      Details<LoadFromMemoryCacheDetails>(&details));
2286}
2287
2288void WebContentsImpl::OnDidDisplayInsecureContent() {
2289  RecordAction(UserMetricsAction("SSL.DisplayedInsecureContent"));
2290  displayed_insecure_content_ = true;
2291  SSLManager::NotifySSLInternalStateChanged(
2292      GetController().GetBrowserContext());
2293}
2294
2295void WebContentsImpl::OnDidRunInsecureContent(
2296    const std::string& security_origin, const GURL& target_url) {
2297  LOG(INFO) << security_origin << " ran insecure content from "
2298            << target_url.possibly_invalid_spec();
2299  RecordAction(UserMetricsAction("SSL.RanInsecureContent"));
2300  if (EndsWith(security_origin, kDotGoogleDotCom, false))
2301    RecordAction(UserMetricsAction("SSL.RanInsecureContentGoogle"));
2302  controller_.ssl_manager()->DidRunInsecureContent(security_origin);
2303  displayed_insecure_content_ = true;
2304  SSLManager::NotifySSLInternalStateChanged(
2305      GetController().GetBrowserContext());
2306}
2307
2308void WebContentsImpl::OnDocumentLoadedInFrame(int64 frame_id) {
2309  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2310                    DocumentLoadedInFrame(frame_id, message_source_));
2311}
2312
2313void WebContentsImpl::OnDidFinishLoad(
2314    int64 frame_id,
2315    const GURL& url,
2316    bool is_main_frame) {
2317  GURL validated_url(url);
2318  RenderProcessHost* render_process_host = message_source_->GetProcess();
2319  RenderViewHost::FilterURL(render_process_host, false, &validated_url);
2320  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2321                    DidFinishLoad(frame_id, validated_url, is_main_frame,
2322                                  message_source_));
2323}
2324
2325void WebContentsImpl::OnDidFailLoadWithError(
2326    int64 frame_id,
2327    const GURL& url,
2328    bool is_main_frame,
2329    int error_code,
2330    const string16& error_description) {
2331  GURL validated_url(url);
2332  RenderProcessHost* render_process_host = message_source_->GetProcess();
2333  RenderViewHost::FilterURL(render_process_host, false, &validated_url);
2334  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2335                    DidFailLoad(frame_id, validated_url, is_main_frame,
2336                                error_code, error_description,
2337                                message_source_));
2338}
2339
2340void WebContentsImpl::OnGoToEntryAtOffset(int offset) {
2341  if (!delegate_ || delegate_->OnGoToEntryOffset(offset)) {
2342    NavigationEntryImpl* entry = NavigationEntryImpl::FromNavigationEntry(
2343        controller_.GetEntryAtOffset(offset));
2344    if (!entry)
2345      return;
2346    // Note that we don't call NavigationController::GotToOffset() as we don't
2347    // want to create a pending navigation entry (it might end up lingering
2348    // http://crbug.com/51680).
2349    entry->SetTransitionType(
2350        PageTransitionFromInt(
2351            entry->GetTransitionType() |
2352            PAGE_TRANSITION_FORWARD_BACK));
2353    NavigateToEntry(*entry, NavigationControllerImpl::NO_RELOAD);
2354
2355    // If the entry is being restored and doesn't have a SiteInstance yet, fill
2356    // it in now that we know. This allows us to find the entry when it commits.
2357    if (!entry->site_instance() &&
2358        entry->restore_type() != NavigationEntryImpl::RESTORE_NONE) {
2359      entry->set_site_instance(
2360          static_cast<SiteInstanceImpl*>(GetPendingSiteInstance()));
2361    }
2362  }
2363}
2364
2365void WebContentsImpl::OnUpdateZoomLimits(int minimum_percent,
2366                                         int maximum_percent,
2367                                         bool remember) {
2368  minimum_zoom_percent_ = minimum_percent;
2369  maximum_zoom_percent_ = maximum_percent;
2370  temporary_zoom_settings_ = !remember;
2371}
2372
2373void WebContentsImpl::OnEnumerateDirectory(int request_id,
2374                                           const base::FilePath& path) {
2375  if (!delegate_)
2376    return;
2377
2378  ChildProcessSecurityPolicyImpl* policy =
2379      ChildProcessSecurityPolicyImpl::GetInstance();
2380  if (policy->CanReadDirectory(GetRenderProcessHost()->GetID(), path))
2381    delegate_->EnumerateDirectory(this, request_id, path);
2382}
2383
2384void WebContentsImpl::OnJSOutOfMemory() {
2385  if (delegate_)
2386    delegate_->JSOutOfMemory(this);
2387}
2388
2389void WebContentsImpl::OnRegisterProtocolHandler(const std::string& protocol,
2390                                                const GURL& url,
2391                                                const string16& title,
2392                                                bool user_gesture) {
2393  if (!delegate_)
2394    return;
2395
2396  ChildProcessSecurityPolicyImpl* policy =
2397      ChildProcessSecurityPolicyImpl::GetInstance();
2398  if (policy->IsPseudoScheme(protocol))
2399    return;
2400
2401  delegate_->RegisterProtocolHandler(this, protocol, url, title, user_gesture);
2402}
2403
2404void WebContentsImpl::OnFindReply(int request_id,
2405                                  int number_of_matches,
2406                                  const gfx::Rect& selection_rect,
2407                                  int active_match_ordinal,
2408                                  bool final_update) {
2409  if (delegate_) {
2410    delegate_->FindReply(this, request_id, number_of_matches, selection_rect,
2411                         active_match_ordinal, final_update);
2412  }
2413}
2414
2415void WebContentsImpl::OnDidProgrammaticallyScroll(
2416    const gfx::Vector2d& scroll_point) {
2417  if (delegate_)
2418    delegate_->DidProgrammaticallyScroll(this, scroll_point);
2419}
2420
2421#if defined(OS_ANDROID)
2422void WebContentsImpl::OnFindMatchRectsReply(
2423    int version,
2424    const std::vector<gfx::RectF>& rects,
2425    const gfx::RectF& active_rect) {
2426  if (delegate_)
2427    delegate_->FindMatchRectsReply(this, version, rects, active_rect);
2428}
2429
2430void WebContentsImpl::OnOpenDateTimeDialog(
2431    const ViewHostMsg_DateTimeDialogValue_Params& value) {
2432  date_time_chooser_->ShowDialog(
2433      ContentViewCore::FromWebContents(this), GetRenderViewHost(),
2434      value.dialog_type, value.year, value.month, value.day, value.hour,
2435      value.minute, value.second, value.week, value.minimum, value.maximum);
2436}
2437
2438#endif
2439
2440void WebContentsImpl::OnCrashedPlugin(const base::FilePath& plugin_path,
2441                                      base::ProcessId plugin_pid) {
2442  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2443                    PluginCrashed(plugin_path, plugin_pid));
2444}
2445
2446void WebContentsImpl::OnAppCacheAccessed(const GURL& manifest_url,
2447                                         bool blocked_by_policy) {
2448  // Notify observers about navigation.
2449  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2450                    AppCacheAccessed(manifest_url, blocked_by_policy));
2451}
2452
2453void WebContentsImpl::OnOpenColorChooser(int color_chooser_id,
2454                                         SkColor color) {
2455  ColorChooser* new_color_chooser = delegate_->OpenColorChooser(this, color);
2456  if (color_chooser_ == new_color_chooser)
2457    return;
2458  color_chooser_.reset(new_color_chooser);
2459  color_chooser_identifier_ = color_chooser_id;
2460}
2461
2462void WebContentsImpl::OnEndColorChooser(int color_chooser_id) {
2463  if (color_chooser_ &&
2464      color_chooser_id == color_chooser_identifier_)
2465    color_chooser_->End();
2466}
2467
2468void WebContentsImpl::OnSetSelectedColorInColorChooser(int color_chooser_id,
2469                                                       SkColor color) {
2470  if (color_chooser_ &&
2471      color_chooser_id == color_chooser_identifier_)
2472    color_chooser_->SetSelectedColor(color);
2473}
2474
2475void WebContentsImpl::OnPepperPluginHung(int plugin_child_id,
2476                                         const base::FilePath& path,
2477                                         bool is_hung) {
2478  UMA_HISTOGRAM_COUNTS("Pepper.PluginHung", 1);
2479
2480  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2481                    PluginHungStatusChanged(plugin_child_id, path, is_hung));
2482}
2483
2484// This exists for render views that don't have a WebUI, but do have WebUI
2485// bindings enabled.
2486void WebContentsImpl::OnWebUISend(const GURL& source_url,
2487                                  const std::string& name,
2488                                  const base::ListValue& args) {
2489  if (delegate_)
2490    delegate_->WebUISend(this, source_url, name, args);
2491}
2492
2493void WebContentsImpl::OnRequestPpapiBrokerPermission(
2494    int request_id,
2495    const GURL& url,
2496    const base::FilePath& plugin_path) {
2497  if (!delegate_) {
2498    OnPpapiBrokerPermissionResult(request_id, false);
2499    return;
2500  }
2501
2502  if (!delegate_->RequestPpapiBrokerPermission(
2503      this, url, plugin_path,
2504      base::Bind(&WebContentsImpl::OnPpapiBrokerPermissionResult,
2505                 base::Unretained(this), request_id))) {
2506    NOTIMPLEMENTED();
2507    OnPpapiBrokerPermissionResult(request_id, false);
2508  }
2509}
2510
2511void WebContentsImpl::OnPpapiBrokerPermissionResult(int request_id,
2512                                                    bool result) {
2513  RenderViewHostImpl* rvh = GetRenderViewHostImpl();
2514  rvh->Send(new ViewMsg_PpapiBrokerPermissionResult(rvh->GetRoutingID(),
2515                                                    request_id,
2516                                                    result));
2517}
2518
2519void WebContentsImpl::OnBrowserPluginMessage(const IPC::Message& message) {
2520  // This creates a BrowserPluginEmbedder, which handles all the BrowserPlugin
2521  // specific messages for this WebContents. This means that any message from
2522  // a BrowserPlugin prior to this will be ignored.
2523  // For more info, see comment above classes BrowserPluginEmbedder and
2524  // BrowserPluginGuest.
2525  CHECK(!browser_plugin_embedder_.get());
2526  browser_plugin_embedder_.reset(BrowserPluginEmbedder::Create(this));
2527  browser_plugin_embedder_->OnMessageReceived(message);
2528}
2529
2530void WebContentsImpl::OnDidDownloadImage(
2531    int id,
2532    int http_status_code,
2533    const GURL& image_url,
2534    int requested_size,
2535    const std::vector<SkBitmap>& bitmaps) {
2536  ImageDownloadMap::iterator iter = image_download_map_.find(id);
2537  if (iter == image_download_map_.end()) {
2538    // Currently WebContents notifies us of ANY downloads so that it is
2539    // possible to get here.
2540    return;
2541  }
2542  if (!iter->second.is_null()) {
2543    iter->second.Run(id, http_status_code, image_url, requested_size, bitmaps);
2544  }
2545  image_download_map_.erase(id);
2546}
2547
2548void WebContentsImpl::OnUpdateFaviconURL(
2549    int32 page_id,
2550    const std::vector<FaviconURL>& candidates) {
2551  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2552                    DidUpdateFaviconURL(page_id, candidates));
2553}
2554
2555FrameTreeNode* WebContentsImpl::FindFrameTreeNodeByID(int64 frame_id) {
2556  // TODO(nasko): Remove this check once we move to creating the root node
2557  // through RenderFrameHost creation.
2558  if (!frame_tree_root_.get())
2559    return NULL;
2560
2561  FrameTreeNode* node = NULL;
2562  std::queue<FrameTreeNode*> queue;
2563  queue.push(frame_tree_root_.get());
2564
2565  while (!queue.empty()) {
2566    node = queue.front();
2567    queue.pop();
2568    if (node->frame_id() == frame_id)
2569      return node;
2570
2571    for (size_t i = 0; i < node->child_count(); ++i)
2572      queue.push(node->child_at(i));
2573  }
2574
2575  return NULL;
2576}
2577
2578void WebContentsImpl::OnFrameAttached(
2579    int64 parent_frame_id,
2580    int64 frame_id,
2581    const std::string& frame_name) {
2582  FrameTreeNode* parent = FindFrameTreeNodeByID(parent_frame_id);
2583  if (!parent)
2584    return;
2585
2586  FrameTreeNode* node = new FrameTreeNode(frame_id, frame_name);
2587  parent->AddChild(node);
2588}
2589
2590void WebContentsImpl::OnFrameDetached(int64 parent_frame_id, int64 frame_id) {
2591  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2592                    FrameDetached(message_source_, frame_id));
2593
2594  FrameTreeNode* parent = FindFrameTreeNodeByID(parent_frame_id);
2595  if (!parent)
2596    return;
2597
2598  parent->RemoveChild(frame_id);
2599}
2600
2601void WebContentsImpl::OnMediaNotification(int64 player_cookie,
2602                                          bool has_video,
2603                                          bool has_audio,
2604                                          bool is_playing) {
2605  // Chrome OS does its own detection of audio and video.
2606#if !defined(OS_CHROMEOS)
2607  if (is_playing) {
2608    scoped_ptr<PowerSaveBlocker> blocker;
2609    if (has_video) {
2610      blocker = PowerSaveBlocker::Create(
2611          PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep,
2612          "Playing video");
2613#if defined(OS_ANDROID)
2614      static_cast<PowerSaveBlockerImpl*>(blocker.get())->
2615          InitDisplaySleepBlocker(GetView()->GetTopLevelNativeWindow());
2616#endif
2617    } else if (has_audio) {
2618      blocker = PowerSaveBlocker::Create(
2619          PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension,
2620          "Playing audio");
2621    }
2622
2623    if (blocker)
2624      power_save_blockers_[message_source_][player_cookie] = blocker.release();
2625  } else {
2626    delete power_save_blockers_[message_source_][player_cookie];
2627    power_save_blockers_[message_source_].erase(player_cookie);
2628  }
2629#endif  // !defined(OS_CHROMEOS)
2630}
2631
2632
2633void WebContentsImpl::DidChangeVisibleSSLState() {
2634  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2635                    DidChangeVisibleSSLState());
2636}
2637
2638void WebContentsImpl::NotifyBeforeFormRepostWarningShow() {
2639  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2640                    BeforeFormRepostWarningShow());
2641}
2642
2643// Notifies the RenderWidgetHost instance about the fact that the page is
2644// loading, or done loading and calls the base implementation.
2645void WebContentsImpl::SetIsLoading(bool is_loading,
2646                                   LoadNotificationDetails* details) {
2647  if (is_loading == is_loading_)
2648    return;
2649
2650  if (!is_loading) {
2651    load_state_ = net::LoadStateWithParam(net::LOAD_STATE_IDLE, string16());
2652    load_state_host_.clear();
2653    upload_size_ = 0;
2654    upload_position_ = 0;
2655  }
2656
2657  render_manager_.SetIsLoading(is_loading);
2658
2659  is_loading_ = is_loading;
2660  waiting_for_response_ = is_loading;
2661
2662  if (delegate_)
2663    delegate_->LoadingStateChanged(this);
2664  NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD);
2665
2666  if (is_loading)
2667    TRACE_EVENT_ASYNC_BEGIN0("browser", "WebContentsImpl Loading", this);
2668  else
2669    TRACE_EVENT_ASYNC_END0("browser", "WebContentsImpl Loading", this);
2670  int type = is_loading ? NOTIFICATION_LOAD_START : NOTIFICATION_LOAD_STOP;
2671  NotificationDetails det = NotificationService::NoDetails();
2672  if (details)
2673      det = Details<LoadNotificationDetails>(details);
2674  NotificationService::current()->Notify(
2675      type, Source<NavigationController>(&controller_), det);
2676}
2677
2678void WebContentsImpl::DidNavigateMainFramePostCommit(
2679    const LoadCommittedDetails& details,
2680    const ViewHostMsg_FrameNavigate_Params& params) {
2681  if (details.is_navigation_to_different_page()) {
2682    // Clear the status bubble. This is a workaround for a bug where WebKit
2683    // doesn't let us know that the cursor left an element during a
2684    // transition (this is also why the mouse cursor remains as a hand after
2685    // clicking on a link); see bugs 1184641 and 980803. We don't want to
2686    // clear the bubble when a user navigates to a named anchor in the same
2687    // page.
2688    UpdateTargetURL(details.entry->GetPageID(), GURL());
2689  }
2690
2691  if (!details.is_in_page) {
2692    // Once the main frame is navigated, we're no longer considered to have
2693    // displayed insecure content.
2694    displayed_insecure_content_ = false;
2695    SSLManager::NotifySSLInternalStateChanged(
2696        GetController().GetBrowserContext());
2697  }
2698
2699  // Notify observers about navigation.
2700  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2701                    DidNavigateMainFrame(details, params));
2702}
2703
2704void WebContentsImpl::DidNavigateAnyFramePostCommit(
2705    RenderViewHost* render_view_host,
2706    const LoadCommittedDetails& details,
2707    const ViewHostMsg_FrameNavigate_Params& params) {
2708  // If we navigate off the page, close all JavaScript dialogs.
2709  if (dialog_manager_ && !details.is_in_page)
2710    dialog_manager_->CancelActiveAndPendingDialogs(this);
2711
2712  // Notify observers about navigation.
2713  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2714                    DidNavigateAnyFrame(details, params));
2715}
2716
2717bool WebContentsImpl::ShouldAssignSiteForURL(const GURL& url) {
2718  // about:blank should not "use up" a new SiteInstance.  The SiteInstance can
2719  // still be used for a normal web site.
2720  if (url == GURL(kAboutBlankURL))
2721    return false;
2722
2723  // The embedder will then have the opportunity to determine if the URL
2724  // should "use up" the SiteInstance.
2725  return GetContentClient()->browser()->ShouldAssignSiteForURL(url);
2726}
2727
2728void WebContentsImpl::UpdateMaxPageIDIfNecessary(RenderViewHost* rvh) {
2729  // If we are creating a RVH for a restored controller, then we need to make
2730  // sure the RenderView starts with a next_page_id_ larger than the number
2731  // of restored entries.  This must be called before the RenderView starts
2732  // navigating (to avoid a race between the browser updating max_page_id and
2733  // the renderer updating next_page_id_).  Because of this, we only call this
2734  // from CreateRenderView and allow that to notify the RenderView for us.
2735  int max_restored_page_id = controller_.GetMaxRestoredPageID();
2736  if (max_restored_page_id >
2737      GetMaxPageIDForSiteInstance(rvh->GetSiteInstance()))
2738    UpdateMaxPageIDForSiteInstance(rvh->GetSiteInstance(),
2739                                   max_restored_page_id);
2740}
2741
2742bool WebContentsImpl::UpdateTitleForEntry(NavigationEntryImpl* entry,
2743                                          const string16& title) {
2744  // For file URLs without a title, use the pathname instead. In the case of a
2745  // synthesized title, we don't want the update to count toward the "one set
2746  // per page of the title to history."
2747  string16 final_title;
2748  bool explicit_set;
2749  if (entry && entry->GetURL().SchemeIsFile() && title.empty()) {
2750    final_title = UTF8ToUTF16(entry->GetURL().ExtractFileName());
2751    explicit_set = false;  // Don't count synthetic titles toward the set limit.
2752  } else {
2753    TrimWhitespace(title, TRIM_ALL, &final_title);
2754    explicit_set = true;
2755  }
2756
2757  // If a page is created via window.open and never navigated,
2758  // there will be no navigation entry. In this situation,
2759  // |page_title_when_no_navigation_entry_| will be used for page title.
2760  if (entry) {
2761    if (final_title == entry->GetTitle())
2762      return false;  // Nothing changed, don't bother.
2763
2764    entry->SetTitle(final_title);
2765  } else {
2766    if (page_title_when_no_navigation_entry_ == final_title)
2767      return false;  // Nothing changed, don't bother.
2768
2769    page_title_when_no_navigation_entry_ = final_title;
2770  }
2771
2772  // Lastly, set the title for the view.
2773  view_->SetPageTitle(final_title);
2774
2775  std::pair<NavigationEntry*, bool> details =
2776      std::make_pair(entry, explicit_set);
2777
2778  NotificationService::current()->Notify(
2779      NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED,
2780      Source<WebContents>(this),
2781      Details<std::pair<NavigationEntry*, bool> >(&details));
2782
2783  return true;
2784}
2785
2786void WebContentsImpl::NotifySwapped(RenderViewHost* old_render_view_host) {
2787  // After sending out a swap notification, we need to send a disconnect
2788  // notification so that clients that pick up a pointer to |this| can NULL the
2789  // pointer.  See Bug 1230284.
2790  notify_disconnection_ = true;
2791  NotificationService::current()->Notify(
2792      NOTIFICATION_WEB_CONTENTS_SWAPPED,
2793      Source<WebContents>(this),
2794      Details<RenderViewHost>(old_render_view_host));
2795
2796  // Ensure that the associated embedder gets cleared after a RenderViewHost
2797  // gets swapped, so we don't reuse the same embedder next time a
2798  // RenderViewHost is attached to this WebContents.
2799  RemoveBrowserPluginEmbedder();
2800}
2801
2802void WebContentsImpl::NotifyConnected() {
2803  notify_disconnection_ = true;
2804  NotificationService::current()->Notify(
2805      NOTIFICATION_WEB_CONTENTS_CONNECTED,
2806      Source<WebContents>(this),
2807      NotificationService::NoDetails());
2808}
2809
2810void WebContentsImpl::NotifyDisconnected() {
2811  if (!notify_disconnection_)
2812    return;
2813
2814  notify_disconnection_ = false;
2815  NotificationService::current()->Notify(
2816      NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
2817      Source<WebContents>(this),
2818      NotificationService::NoDetails());
2819}
2820
2821void WebContentsImpl::NotifyNavigationEntryCommitted(
2822    const LoadCommittedDetails& load_details) {
2823  FOR_EACH_OBSERVER(
2824      WebContentsObserver, observers_, NavigationEntryCommitted(load_details));
2825}
2826
2827RenderViewHostDelegateView* WebContentsImpl::GetDelegateView() {
2828  return render_view_host_delegate_view_;
2829}
2830
2831RenderViewHostDelegate::RendererManagement*
2832WebContentsImpl::GetRendererManagementDelegate() {
2833  return &render_manager_;
2834}
2835
2836RendererPreferences WebContentsImpl::GetRendererPrefs(
2837    BrowserContext* browser_context) const {
2838  return renderer_preferences_;
2839}
2840
2841WebContents* WebContentsImpl::GetAsWebContents() {
2842  return this;
2843}
2844
2845gfx::Rect WebContentsImpl::GetRootWindowResizerRect() const {
2846  if (delegate_)
2847    return delegate_->GetRootWindowResizerRect();
2848  return gfx::Rect();
2849}
2850
2851void WebContentsImpl::RemoveBrowserPluginEmbedder() {
2852  if (browser_plugin_embedder_)
2853    browser_plugin_embedder_.reset();
2854}
2855
2856void WebContentsImpl::RenderViewCreated(RenderViewHost* render_view_host) {
2857  // Don't send notifications if we are just creating a swapped-out RVH for
2858  // the opener chain.  These won't be used for view-source or WebUI, so it's
2859  // ok to return early.
2860  if (static_cast<RenderViewHostImpl*>(render_view_host)->is_swapped_out())
2861    return;
2862
2863  if (delegate_)
2864    view_->SetOverscrollControllerEnabled(delegate_->CanOverscrollContent());
2865
2866  NotificationService::current()->Notify(
2867      NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED,
2868      Source<WebContents>(this),
2869      Details<RenderViewHost>(render_view_host));
2870  NavigationEntry* entry = controller_.GetActiveEntry();
2871  if (!entry)
2872    return;
2873
2874  // When we're creating views, we're still doing initial setup, so we always
2875  // use the pending Web UI rather than any possibly existing committed one.
2876  if (render_manager_.pending_web_ui())
2877    render_manager_.pending_web_ui()->RenderViewCreated(render_view_host);
2878
2879  if (entry->IsViewSourceMode()) {
2880    // Put the renderer in view source mode.
2881    render_view_host->Send(
2882        new ViewMsg_EnableViewSourceMode(render_view_host->GetRoutingID()));
2883  }
2884
2885  view_->RenderViewCreated(render_view_host);
2886
2887  FOR_EACH_OBSERVER(
2888      WebContentsObserver, observers_, RenderViewCreated(render_view_host));
2889}
2890
2891void WebContentsImpl::RenderViewReady(RenderViewHost* rvh) {
2892  if (rvh != GetRenderViewHost()) {
2893    // Don't notify the world, since this came from a renderer in the
2894    // background.
2895    return;
2896  }
2897
2898  NotifyConnected();
2899  bool was_crashed = IsCrashed();
2900  SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING, 0);
2901
2902  // Restore the focus to the tab (otherwise the focus will be on the top
2903  // window).
2904  if (was_crashed && !FocusLocationBarByDefault() &&
2905      (!delegate_ || delegate_->ShouldFocusPageAfterCrash())) {
2906    view_->Focus();
2907  }
2908
2909  FOR_EACH_OBSERVER(WebContentsObserver, observers_, RenderViewReady());
2910}
2911
2912void WebContentsImpl::RenderViewTerminated(RenderViewHost* rvh,
2913                                           base::TerminationStatus status,
2914                                           int error_code) {
2915  if (rvh != GetRenderViewHost()) {
2916    // The pending page's RenderViewHost is gone.
2917    return;
2918  }
2919
2920  ClearPowerSaveBlockers(rvh);
2921  SetIsLoading(false, NULL);
2922  NotifyDisconnected();
2923  SetIsCrashed(status, error_code);
2924  GetView()->OnTabCrashed(GetCrashedStatus(), crashed_error_code_);
2925
2926  FOR_EACH_OBSERVER(WebContentsObserver,
2927                    observers_,
2928                    RenderProcessGone(GetCrashedStatus()));
2929}
2930
2931void WebContentsImpl::RenderViewDeleted(RenderViewHost* rvh) {
2932  ClearPowerSaveBlockers(rvh);
2933  render_manager_.RenderViewDeleted(rvh);
2934  FOR_EACH_OBSERVER(WebContentsObserver, observers_, RenderViewDeleted(rvh));
2935}
2936
2937void WebContentsImpl::DidNavigate(
2938    RenderViewHost* rvh,
2939    const ViewHostMsg_FrameNavigate_Params& params) {
2940  // If we don't have a frame tree root yet, this is the first navigation in
2941  // using the current RenderViewHost, so we need to create it with the proper
2942  // frame id.
2943  if (!frame_tree_root_.get()) {
2944    DCHECK(PageTransitionIsMainFrame(params.transition));
2945    frame_tree_root_.reset(new FrameTreeNode(params.frame_id, std::string()));
2946  }
2947
2948  if (PageTransitionIsMainFrame(params.transition)) {
2949    // When overscroll navigation gesture is enabled, a screenshot of the page
2950    // in its current state is taken so that it can be used during the
2951    // nav-gesture. It is necessary to take the screenshot here, before calling
2952    // RenderViewHostManager::DidNavigateMainFrame, because that can change
2953    // WebContents::GetRenderViewHost to return the new host, instead of the one
2954    // that may have just been swapped out.
2955    if (delegate_ && delegate_->CanOverscrollContent())
2956      controller_.TakeScreenshot();
2957
2958    render_manager_.DidNavigateMainFrame(rvh);
2959  }
2960
2961  // We expect to have a valid frame tree root node at all times when
2962  // navigating.
2963  DCHECK(frame_tree_root_.get());
2964
2965  // Update the site of the SiteInstance if it doesn't have one yet, unless
2966  // assigning a site is not necessary for this URL.  In that case, the
2967  // SiteInstance can still be considered unused until a navigation to a real
2968  // page.
2969  if (!static_cast<SiteInstanceImpl*>(GetSiteInstance())->HasSite() &&
2970      ShouldAssignSiteForURL(params.url)) {
2971    static_cast<SiteInstanceImpl*>(GetSiteInstance())->SetSite(params.url);
2972  }
2973
2974  // Need to update MIME type here because it's referred to in
2975  // UpdateNavigationCommands() called by RendererDidNavigate() to
2976  // determine whether or not to enable the encoding menu.
2977  // It's updated only for the main frame. For a subframe,
2978  // RenderView::UpdateURL does not set params.contents_mime_type.
2979  // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
2980  // TODO(jungshik): Add a test for the encoding menu to avoid
2981  // regressing it again.
2982  if (PageTransitionIsMainFrame(params.transition))
2983    contents_mime_type_ = params.contents_mime_type;
2984
2985  LoadCommittedDetails details;
2986  bool did_navigate = controller_.RendererDidNavigate(params, &details);
2987
2988  // For now, keep track of each frame's URL in its FrameTreeNode.  This lets
2989  // us estimate our process count for implementing OOP iframes.
2990  // TODO(creis): Remove this when we track which pages commit in each frame.
2991  FrameTreeNode* node = FindFrameTreeNodeByID(params.frame_id);
2992  if (node)
2993    node->set_current_url(params.url);
2994
2995  // Send notification about committed provisional loads. This notification is
2996  // different from the NAV_ENTRY_COMMITTED notification which doesn't include
2997  // the actual URL navigated to and isn't sent for AUTO_SUBFRAME navigations.
2998  if (details.type != NAVIGATION_TYPE_NAV_IGNORE) {
2999    // For AUTO_SUBFRAME navigations, an event for the main frame is generated
3000    // that is not recorded in the navigation history. For the purpose of
3001    // tracking navigation events, we treat this event as a sub frame navigation
3002    // event.
3003    bool is_main_frame = did_navigate ? details.is_main_frame : false;
3004    PageTransition transition_type = params.transition;
3005    // Whether or not a page transition was triggered by going backward or
3006    // forward in the history is only stored in the navigation controller's
3007    // entry list.
3008    if (did_navigate &&
3009        (controller_.GetActiveEntry()->GetTransitionType() &
3010            PAGE_TRANSITION_FORWARD_BACK)) {
3011      transition_type = PageTransitionFromInt(
3012          params.transition | PAGE_TRANSITION_FORWARD_BACK);
3013    }
3014    // Notify observers about the commit of the provisional load.
3015    FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3016                      DidCommitProvisionalLoadForFrame(params.frame_id,
3017                      is_main_frame, params.url, transition_type, rvh));
3018  }
3019
3020  if (!did_navigate)
3021    return;  // No navigation happened.
3022
3023  // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
3024  // for the appropriate notification (best) or you can add it to
3025  // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
3026  // necessary, please).
3027
3028  // Run post-commit tasks.
3029  if (details.is_main_frame) {
3030    DidNavigateMainFramePostCommit(details, params);
3031    if (delegate_) {
3032      delegate_->DidNavigateMainFramePostCommit(this);
3033      view_->SetOverscrollControllerEnabled(delegate_->CanOverscrollContent());
3034    }
3035  }
3036  DidNavigateAnyFramePostCommit(rvh, details, params);
3037}
3038
3039void WebContentsImpl::UpdateState(RenderViewHost* rvh,
3040                                  int32 page_id,
3041                                  const PageState& page_state) {
3042  // Ensure that this state update comes from either the active RVH or one of
3043  // the swapped out RVHs.  We don't expect to hear from any other RVHs.
3044  DCHECK(rvh == GetRenderViewHost() || render_manager_.IsOnSwappedOutList(rvh));
3045
3046  // We must be prepared to handle state updates for any page, these occur
3047  // when the user is scrolling and entering form data, as well as when we're
3048  // leaving a page, in which case our state may have already been moved to
3049  // the next page. The navigation controller will look up the appropriate
3050  // NavigationEntry and update it when it is notified via the delegate.
3051
3052  int entry_index = controller_.GetEntryIndexWithPageID(
3053      rvh->GetSiteInstance(), page_id);
3054  if (entry_index < 0)
3055    return;
3056  NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
3057
3058  if (page_state == entry->GetPageState())
3059    return;  // Nothing to update.
3060  entry->SetPageState(page_state);
3061  controller_.NotifyEntryChanged(entry, entry_index);
3062}
3063
3064void WebContentsImpl::UpdateTitle(RenderViewHost* rvh,
3065                                  int32 page_id,
3066                                  const string16& title,
3067                                  base::i18n::TextDirection title_direction) {
3068  // If we have a title, that's a pretty good indication that we've started
3069  // getting useful data.
3070  SetNotWaitingForResponse();
3071
3072  // Try to find the navigation entry, which might not be the current one.
3073  // For example, it might be from a pending RVH for the pending entry.
3074  NavigationEntryImpl* entry = controller_.GetEntryWithPageID(
3075      rvh->GetSiteInstance(), page_id);
3076
3077  // We can handle title updates when we don't have an entry in
3078  // UpdateTitleForEntry, but only if the update is from the current RVH.
3079  if (!entry && rvh != GetRenderViewHost())
3080    return;
3081
3082  // TODO(evan): make use of title_direction.
3083  // http://code.google.com/p/chromium/issues/detail?id=27094
3084  if (!UpdateTitleForEntry(entry, title))
3085    return;
3086
3087  // Broadcast notifications when the UI should be updated.
3088  if (entry == controller_.GetEntryAtOffset(0))
3089    NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE);
3090}
3091
3092void WebContentsImpl::UpdateEncoding(RenderViewHost* render_view_host,
3093                                     const std::string& encoding) {
3094  SetEncoding(encoding);
3095}
3096
3097void WebContentsImpl::UpdateTargetURL(int32 page_id, const GURL& url) {
3098  if (delegate_)
3099    delegate_->UpdateTargetURL(this, page_id, url);
3100}
3101
3102void WebContentsImpl::Close(RenderViewHost* rvh) {
3103#if defined(OS_MACOSX)
3104  // The UI may be in an event-tracking loop, such as between the
3105  // mouse-down and mouse-up in text selection or a button click.
3106  // Defer the close until after tracking is complete, so that we
3107  // don't free objects out from under the UI.
3108  // TODO(shess): This could get more fine-grained.  For instance,
3109  // closing a tab in another window while selecting text in the
3110  // current window's Omnibox should be just fine.
3111  if (view_->IsEventTracking()) {
3112    view_->CloseTabAfterEventTracking();
3113    return;
3114  }
3115#endif
3116
3117  // Ignore this if it comes from a RenderViewHost that we aren't showing.
3118  if (delegate_ && rvh == GetRenderViewHost())
3119    delegate_->CloseContents(this);
3120}
3121
3122void WebContentsImpl::SwappedOut(RenderViewHost* rvh) {
3123  if (delegate_ && rvh == GetRenderViewHost())
3124    delegate_->SwappedOut(this);
3125
3126  // Allow the navigation to proceed.
3127  render_manager_.SwappedOut(rvh);
3128}
3129
3130void WebContentsImpl::RequestMove(const gfx::Rect& new_bounds) {
3131  if (delegate_ && delegate_->IsPopupOrPanel(this))
3132    delegate_->MoveContents(this, new_bounds);
3133}
3134
3135void WebContentsImpl::DidStartLoading(RenderViewHost* render_view_host) {
3136  SetIsLoading(true, NULL);
3137
3138  // Notify observers about navigation.
3139  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3140                    DidStartLoading(render_view_host));
3141}
3142
3143void WebContentsImpl::DidStopLoading(RenderViewHost* render_view_host) {
3144  scoped_ptr<LoadNotificationDetails> details;
3145
3146  // Use the last committed entry rather than the active one, in case a
3147  // pending entry has been created.
3148  NavigationEntry* entry = controller_.GetLastCommittedEntry();
3149
3150  // An entry may not exist for a stop when loading an initial blank page or
3151  // if an iframe injected by script into a blank page finishes loading.
3152  if (entry) {
3153    base::TimeDelta elapsed = base::TimeTicks::Now() - current_load_start_;
3154
3155    details.reset(new LoadNotificationDetails(
3156        entry->GetVirtualURL(),
3157        entry->GetTransitionType(),
3158        elapsed,
3159        &controller_,
3160        controller_.GetCurrentEntryIndex()));
3161  }
3162
3163  SetIsLoading(false, details.get());
3164
3165  // Notify observers about navigation.
3166  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3167                    DidStopLoading(render_view_host));
3168}
3169
3170void WebContentsImpl::DidCancelLoading() {
3171  controller_.DiscardNonCommittedEntries();
3172
3173  // Update the URL display.
3174  NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
3175}
3176
3177void WebContentsImpl::DidChangeLoadProgress(double progress) {
3178#if defined(OS_ANDROID)
3179  if (delegate_)
3180    delegate_->LoadProgressChanged(this, progress);
3181#endif
3182}
3183
3184void WebContentsImpl::DidDisownOpener(RenderViewHost* rvh) {
3185  if (opener_) {
3186    // Clear our opener so that future cross-process navigations don't have an
3187    // opener assigned.
3188    RemoveDestructionObserver(opener_);
3189    opener_ = NULL;
3190  }
3191
3192  // Notify all swapped out RenderViewHosts for this tab.  This is important
3193  // in case we go back to them, or if another window in those processes tries
3194  // to access window.opener.
3195  render_manager_.DidDisownOpener(rvh);
3196}
3197
3198void WebContentsImpl::DidAccessInitialDocument() {
3199  // Update the URL display.
3200  NotifyNavigationStateChanged(content::INVALIDATE_TYPE_URL);
3201}
3202
3203void WebContentsImpl::DocumentAvailableInMainFrame(
3204    RenderViewHost* render_view_host) {
3205  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3206                    DocumentAvailableInMainFrame());
3207}
3208
3209void WebContentsImpl::DocumentOnLoadCompletedInMainFrame(
3210    RenderViewHost* render_view_host,
3211    int32 page_id) {
3212  NotificationService::current()->Notify(
3213      NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
3214      Source<WebContents>(this),
3215      Details<int>(&page_id));
3216}
3217
3218void WebContentsImpl::RequestOpenURL(RenderViewHost* rvh,
3219                                     const GURL& url,
3220                                     const Referrer& referrer,
3221                                     WindowOpenDisposition disposition,
3222                                     int64 source_frame_id,
3223                                     bool should_replace_current_entry,
3224                                     bool user_gesture) {
3225  // If this came from a swapped out RenderViewHost, we only allow the request
3226  // if we are still in the same BrowsingInstance.
3227  if (static_cast<RenderViewHostImpl*>(rvh)->is_swapped_out() &&
3228      !rvh->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance())) {
3229    return;
3230  }
3231
3232  // Delegate to RequestTransferURL because this is just the generic
3233  // case where |old_request_id| is empty.
3234  RequestTransferURL(url, referrer, disposition, source_frame_id,
3235                     GlobalRequestID(),
3236                     should_replace_current_entry, user_gesture);
3237}
3238
3239void WebContentsImpl::RequestTransferURL(
3240    const GURL& url,
3241    const Referrer& referrer,
3242    WindowOpenDisposition disposition,
3243    int64 source_frame_id,
3244    const GlobalRequestID& old_request_id,
3245    bool should_replace_current_entry,
3246    bool user_gesture) {
3247  WebContents* new_contents = NULL;
3248  PageTransition transition_type = PAGE_TRANSITION_LINK;
3249  if (render_manager_.web_ui()) {
3250    // When we're a Web UI, it will provide a page transition type for us (this
3251    // is so the new tab page can specify AUTO_BOOKMARK for automatically
3252    // generated suggestions).
3253    //
3254    // Note also that we hide the referrer for Web UI pages. We don't really
3255    // want web sites to see a referrer of "chrome://blah" (and some
3256    // chrome: URLs might have search terms or other stuff we don't want to
3257    // send to the site), so we send no referrer.
3258    OpenURLParams params(url, Referrer(), source_frame_id, disposition,
3259        render_manager_.web_ui()->GetLinkTransitionType(),
3260        false /* is_renderer_initiated */);
3261    params.transferred_global_request_id = old_request_id;
3262    new_contents = OpenURL(params);
3263    transition_type = render_manager_.web_ui()->GetLinkTransitionType();
3264  } else {
3265    OpenURLParams params(url, referrer, source_frame_id, disposition,
3266        PAGE_TRANSITION_LINK, true /* is_renderer_initiated */);
3267    params.transferred_global_request_id = old_request_id;
3268    params.should_replace_current_entry = should_replace_current_entry;
3269    params.user_gesture = user_gesture;
3270    new_contents = OpenURL(params);
3271  }
3272  if (new_contents) {
3273    // Notify observers.
3274    FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3275                      DidOpenRequestedURL(new_contents,
3276                                          url,
3277                                          referrer,
3278                                          disposition,
3279                                          transition_type,
3280                                          source_frame_id));
3281  }
3282}
3283
3284void WebContentsImpl::RouteCloseEvent(RenderViewHost* rvh) {
3285  // Tell the active RenderViewHost to run unload handlers and close, as long
3286  // as the request came from a RenderViewHost in the same BrowsingInstance.
3287  // In most cases, we receive this from a swapped out RenderViewHost.
3288  // It is possible to receive it from one that has just been swapped in,
3289  // in which case we might as well deliver the message anyway.
3290  if (rvh->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()))
3291    GetRenderViewHost()->ClosePage();
3292}
3293
3294void WebContentsImpl::RouteMessageEvent(
3295    RenderViewHost* rvh,
3296    const ViewMsg_PostMessage_Params& params) {
3297  // Only deliver the message to the active RenderViewHost if the request
3298  // came from a RenderViewHost in the same BrowsingInstance or if this
3299  // WebContents is dedicated to a browser plugin guest.
3300  // Note: This check means that an embedder could theoretically receive a
3301  // postMessage from anyone (not just its own guests). However, this is
3302  // probably not a risk for apps since other pages won't have references
3303  // to App windows.
3304  if (!rvh->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()) &&
3305      !GetBrowserPluginGuest() && !GetBrowserPluginEmbedder())
3306    return;
3307
3308  ViewMsg_PostMessage_Params new_params(params);
3309
3310  // If there is a source_routing_id, translate it to the routing ID for
3311  // the equivalent swapped out RVH in the target process.  If we need
3312  // to create a swapped out RVH for the source tab, we create its opener
3313  // chain as well, since those will also be accessible to the target page.
3314  if (new_params.source_routing_id != MSG_ROUTING_NONE) {
3315    // Try to look up the WebContents for the source page.
3316    WebContentsImpl* source_contents = NULL;
3317    RenderViewHostImpl* source_rvh = RenderViewHostImpl::FromID(
3318        rvh->GetProcess()->GetID(), params.source_routing_id);
3319    if (source_rvh) {
3320      source_contents = static_cast<WebContentsImpl*>(
3321          source_rvh->GetDelegate()->GetAsWebContents());
3322    }
3323
3324    if (source_contents) {
3325      if (GetBrowserPluginGuest()) {
3326        // We create a swapped out RenderView for the embedder in the guest's
3327        // render process but we intentionally do not expose the embedder's
3328        // opener chain to it.
3329        new_params.source_routing_id =
3330            source_contents->CreateSwappedOutRenderView(GetSiteInstance());
3331      } else {
3332        new_params.source_routing_id =
3333            source_contents->CreateOpenerRenderViews(GetSiteInstance());
3334      }
3335    } else {
3336      // We couldn't find it, so don't pass a source frame.
3337      new_params.source_routing_id = MSG_ROUTING_NONE;
3338    }
3339  }
3340
3341  // In most cases, we receive this from a swapped out RenderViewHost.
3342  // It is possible to receive it from one that has just been swapped in,
3343  // in which case we might as well deliver the message anyway.
3344  Send(new ViewMsg_PostMessageEvent(GetRoutingID(), new_params));
3345}
3346
3347void WebContentsImpl::RunJavaScriptMessage(
3348    RenderViewHost* rvh,
3349    const string16& message,
3350    const string16& default_prompt,
3351    const GURL& frame_url,
3352    JavaScriptMessageType javascript_message_type,
3353    IPC::Message* reply_msg,
3354    bool* did_suppress_message) {
3355  // Suppress JavaScript dialogs when requested. Also suppress messages when
3356  // showing an interstitial as it's shown over the previous page and we don't
3357  // want the hidden page's dialogs to interfere with the interstitial.
3358  bool suppress_this_message =
3359      static_cast<RenderViewHostImpl*>(rvh)->is_swapped_out() ||
3360      ShowingInterstitialPage() ||
3361      !delegate_ ||
3362      delegate_->ShouldSuppressDialogs() ||
3363      !delegate_->GetJavaScriptDialogManager();
3364
3365  if (!suppress_this_message) {
3366    std::string accept_lang = GetContentClient()->browser()->
3367      GetAcceptLangs(GetBrowserContext());
3368    dialog_manager_ = delegate_->GetJavaScriptDialogManager();
3369    dialog_manager_->RunJavaScriptDialog(
3370        this,
3371        frame_url.GetOrigin(),
3372        accept_lang,
3373        javascript_message_type,
3374        message,
3375        default_prompt,
3376        base::Bind(&WebContentsImpl::OnDialogClosed,
3377                   base::Unretained(this),
3378                   rvh,
3379                   reply_msg),
3380        &suppress_this_message);
3381  }
3382
3383  if (suppress_this_message) {
3384    // If we are suppressing messages, just reply as if the user immediately
3385    // pressed "Cancel".
3386    OnDialogClosed(rvh, reply_msg, false, string16());
3387  }
3388
3389  *did_suppress_message = suppress_this_message;
3390}
3391
3392void WebContentsImpl::RunBeforeUnloadConfirm(RenderViewHost* rvh,
3393                                             const string16& message,
3394                                             bool is_reload,
3395                                             IPC::Message* reply_msg) {
3396  RenderViewHostImpl* rvhi = static_cast<RenderViewHostImpl*>(rvh);
3397  if (delegate_)
3398    delegate_->WillRunBeforeUnloadConfirm();
3399
3400  bool suppress_this_message =
3401      rvhi->is_swapped_out() ||
3402      !delegate_ ||
3403      delegate_->ShouldSuppressDialogs() ||
3404      !delegate_->GetJavaScriptDialogManager();
3405  if (suppress_this_message) {
3406    // The reply must be sent to the RVH that sent the request.
3407    rvhi->JavaScriptDialogClosed(reply_msg, true, string16());
3408    return;
3409  }
3410
3411  is_showing_before_unload_dialog_ = true;
3412  dialog_manager_ = delegate_->GetJavaScriptDialogManager();
3413  dialog_manager_->RunBeforeUnloadDialog(
3414      this, message, is_reload,
3415      base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this), rvh,
3416                 reply_msg));
3417}
3418
3419bool WebContentsImpl::AddMessageToConsole(int32 level,
3420                                          const string16& message,
3421                                          int32 line_no,
3422                                          const string16& source_id) {
3423  if (!delegate_)
3424    return false;
3425  return delegate_->AddMessageToConsole(this, level, message, line_no,
3426                                        source_id);
3427}
3428
3429WebPreferences WebContentsImpl::GetWebkitPrefs() {
3430  // We want to base the page config off of the real URL, rather than the
3431  // display URL.
3432  GURL url = controller_.GetActiveEntry()
3433      ? controller_.GetActiveEntry()->GetURL() : GURL::EmptyGURL();
3434  return GetWebkitPrefs(GetRenderViewHost(), url);
3435}
3436
3437int WebContentsImpl::CreateSwappedOutRenderView(
3438    SiteInstance* instance) {
3439  return render_manager_.CreateRenderView(instance, MSG_ROUTING_NONE, true);
3440}
3441
3442void WebContentsImpl::OnUserGesture() {
3443  // Notify observers.
3444  FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidGetUserGesture());
3445
3446  ResourceDispatcherHostImpl* rdh = ResourceDispatcherHostImpl::Get();
3447  if (rdh)  // NULL in unittests.
3448    rdh->OnUserGesture(this);
3449}
3450
3451void WebContentsImpl::OnIgnoredUIEvent() {
3452  // Notify observers.
3453  FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidGetIgnoredUIEvent());
3454}
3455
3456void WebContentsImpl::RendererUnresponsive(RenderViewHost* rvh,
3457                                           bool is_during_unload) {
3458  // Don't show hung renderer dialog for a swapped out RVH.
3459  if (rvh != GetRenderViewHost())
3460    return;
3461
3462  RenderViewHostImpl* rvhi = static_cast<RenderViewHostImpl*>(rvh);
3463
3464  // Ignore renderer unresponsive event if debugger is attached to the tab
3465  // since the event may be a result of the renderer sitting on a breakpoint.
3466  // See http://crbug.com/65458
3467  if (DevToolsAgentHost::IsDebuggerAttached(this))
3468    return;
3469
3470  if (is_during_unload) {
3471    // Hang occurred while firing the beforeunload/unload handler.
3472    // Pretend the handler fired so tab closing continues as if it had.
3473    rvhi->set_sudden_termination_allowed(true);
3474
3475    if (!render_manager_.ShouldCloseTabOnUnresponsiveRenderer())
3476      return;
3477
3478    // If the tab hangs in the beforeunload/unload handler there's really
3479    // nothing we can do to recover. Pretend the unload listeners have
3480    // all fired and close the tab. If the hang is in the beforeunload handler
3481    // then the user will not have the option of cancelling the close.
3482    Close(rvh);
3483    return;
3484  }
3485
3486  if (!GetRenderViewHostImpl() || !GetRenderViewHostImpl()->IsRenderViewLive())
3487    return;
3488
3489  if (delegate_)
3490    delegate_->RendererUnresponsive(this);
3491}
3492
3493void WebContentsImpl::RendererResponsive(RenderViewHost* render_view_host) {
3494  if (delegate_)
3495    delegate_->RendererResponsive(this);
3496}
3497
3498void WebContentsImpl::LoadStateChanged(
3499    const GURL& url,
3500    const net::LoadStateWithParam& load_state,
3501    uint64 upload_position,
3502    uint64 upload_size) {
3503  load_state_ = load_state;
3504  upload_position_ = upload_position;
3505  upload_size_ = upload_size;
3506  load_state_host_ = net::IDNToUnicode(url.host(),
3507      GetContentClient()->browser()->GetAcceptLangs(
3508          GetBrowserContext()));
3509  if (load_state_.state == net::LOAD_STATE_READING_RESPONSE)
3510    SetNotWaitingForResponse();
3511  if (IsLoading()) {
3512    NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD | INVALIDATE_TYPE_TAB);
3513  }
3514}
3515
3516void WebContentsImpl::WorkerCrashed() {
3517  if (delegate_)
3518    delegate_->WorkerCrashed(this);
3519}
3520
3521void WebContentsImpl::BeforeUnloadFiredFromRenderManager(
3522    bool proceed, const base::TimeTicks& proceed_time,
3523    bool* proceed_to_fire_unload) {
3524  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3525                    BeforeUnloadFired(proceed_time));
3526  if (delegate_)
3527    delegate_->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
3528  // Note: |this| might be deleted at this point.
3529}
3530
3531void WebContentsImpl::RenderProcessGoneFromRenderManager(
3532    RenderViewHost* render_view_host) {
3533  DCHECK(crashed_status_ != base::TERMINATION_STATUS_STILL_RUNNING);
3534  RenderViewTerminated(render_view_host, crashed_status_, crashed_error_code_);
3535}
3536
3537void WebContentsImpl::UpdateRenderViewSizeForRenderManager() {
3538  // TODO(brettw) this is a hack. See WebContentsView::SizeContents.
3539  gfx::Size size = view_->GetContainerSize();
3540  // 0x0 isn't a valid window size (minimal window size is 1x1) but it may be
3541  // here during container initialization and normal window size will be set
3542  // later. In case of tab duplication this resizing to 0x0 prevents setting
3543  // normal size later so just ignore it.
3544  if (!size.IsEmpty())
3545    view_->SizeContents(size);
3546}
3547
3548void WebContentsImpl::NotifySwappedFromRenderManager(RenderViewHost* rvh) {
3549  NotifySwapped(rvh);
3550
3551  // Make sure the visible RVH reflects the new delegate's preferences.
3552  if (delegate_)
3553    view_->SetOverscrollControllerEnabled(delegate_->CanOverscrollContent());
3554
3555  view_->RenderViewSwappedIn(render_manager_.current_host());
3556
3557  FrameTreeNode* root = NULL;
3558  RenderViewHostImpl* new_rvh = static_cast<RenderViewHostImpl*>(
3559      render_manager_.current_host());
3560
3561  // We are doing a cross-site navigation and swapping processes. Since frame
3562  // ids are unique to a process, we need to recreate the frame tree with the
3563  // proper main frame id.
3564  // Note that it is possible for this method to be called before the new RVH
3565  // has committed a navigation (if RenderViewHostManager short-circuits the
3566  // CommitPending call because the current RVH is dead). In that case, we
3567  // haven't heard a valid frame id to use to initialize the root node, so clear
3568  // out the root node and the first subsequent navigation message will set it
3569  // correctly.
3570  if (new_rvh->main_frame_id() != -1)
3571    root = new FrameTreeNode(new_rvh->main_frame_id(), std::string());
3572
3573  frame_tree_root_.reset(root);
3574}
3575
3576int WebContentsImpl::CreateOpenerRenderViewsForRenderManager(
3577    SiteInstance* instance) {
3578  if (!opener_)
3579    return MSG_ROUTING_NONE;
3580
3581  // Recursively create RenderViews for anything else in the opener chain.
3582  return opener_->CreateOpenerRenderViews(instance);
3583}
3584
3585int WebContentsImpl::CreateOpenerRenderViews(SiteInstance* instance) {
3586  int opener_route_id = MSG_ROUTING_NONE;
3587
3588  // If this tab has an opener, ensure it has a RenderView in the given
3589  // SiteInstance as well.
3590  if (opener_)
3591    opener_route_id = opener_->CreateOpenerRenderViews(instance);
3592
3593  // If any of the renderers (current, pending, or swapped out) for this
3594  // WebContents has the same SiteInstance, use it.
3595  if (render_manager_.current_host()->GetSiteInstance() == instance)
3596    return render_manager_.current_host()->GetRoutingID();
3597
3598  if (render_manager_.pending_render_view_host() &&
3599      render_manager_.pending_render_view_host()->GetSiteInstance() == instance)
3600    return render_manager_.pending_render_view_host()->GetRoutingID();
3601
3602  RenderViewHostImpl* rvh = render_manager_.GetSwappedOutRenderViewHost(
3603      instance);
3604  if (rvh)
3605    return rvh->GetRoutingID();
3606
3607  // Create a swapped out RenderView in the given SiteInstance if none exists,
3608  // setting its opener to the given route_id.  Return the new view's route_id.
3609  return render_manager_.CreateRenderView(instance, opener_route_id, true);
3610}
3611
3612NavigationControllerImpl& WebContentsImpl::GetControllerForRenderManager() {
3613  return GetController();
3614}
3615
3616WebUIImpl* WebContentsImpl::CreateWebUIForRenderManager(const GURL& url) {
3617  return static_cast<WebUIImpl*>(CreateWebUI(url));
3618}
3619
3620NavigationEntry*
3621    WebContentsImpl::GetLastCommittedNavigationEntryForRenderManager() {
3622  return controller_.GetLastCommittedEntry();
3623}
3624
3625bool WebContentsImpl::CreateRenderViewForRenderManager(
3626    RenderViewHost* render_view_host, int opener_route_id) {
3627  TRACE_EVENT0("browser", "WebContentsImpl::CreateRenderViewForRenderManager");
3628  // Can be NULL during tests.
3629  RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(render_view_host);
3630
3631  // Now that the RenderView has been created, we need to tell it its size.
3632  if (rwh_view)
3633    rwh_view->SetSize(view_->GetContainerSize());
3634
3635  // Make sure we use the correct starting page_id in the new RenderView.
3636  UpdateMaxPageIDIfNecessary(render_view_host);
3637  int32 max_page_id =
3638      GetMaxPageIDForSiteInstance(render_view_host->GetSiteInstance());
3639
3640  if (!static_cast<RenderViewHostImpl*>(
3641          render_view_host)->CreateRenderView(string16(),
3642                                              opener_route_id,
3643                                              max_page_id)) {
3644    return false;
3645  }
3646
3647#if defined(OS_LINUX) || defined(OS_OPENBSD)
3648  // Force a ViewMsg_Resize to be sent, needed to make plugins show up on
3649  // linux. See crbug.com/83941.
3650  if (rwh_view) {
3651    if (RenderWidgetHost* render_widget_host = rwh_view->GetRenderWidgetHost())
3652      render_widget_host->WasResized();
3653  }
3654#endif
3655
3656  return true;
3657}
3658
3659void WebContentsImpl::OnDialogClosed(RenderViewHost* rvh,
3660                                     IPC::Message* reply_msg,
3661                                     bool success,
3662                                     const string16& user_input) {
3663  if (is_showing_before_unload_dialog_ && !success) {
3664    // If a beforeunload dialog is canceled, we need to stop the throbber from
3665    // spinning, since we forced it to start spinning in Navigate.
3666    DidStopLoading(rvh);
3667    controller_.DiscardNonCommittedEntries();
3668
3669    FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3670                      BeforeUnloadDialogCancelled());
3671  }
3672  is_showing_before_unload_dialog_ = false;
3673  static_cast<RenderViewHostImpl*>(
3674      rvh)->JavaScriptDialogClosed(reply_msg, success, user_input);
3675}
3676
3677void WebContentsImpl::SetEncoding(const std::string& encoding) {
3678  encoding_ = GetContentClient()->browser()->
3679      GetCanonicalEncodingNameByAliasName(encoding);
3680}
3681
3682void WebContentsImpl::CreateViewAndSetSizeForRVH(RenderViewHost* rvh) {
3683  RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(rvh);
3684  // Can be NULL during tests.
3685  if (rwh_view)
3686    rwh_view->SetSize(GetView()->GetContainerSize());
3687}
3688
3689RenderViewHostImpl* WebContentsImpl::GetRenderViewHostImpl() {
3690  return static_cast<RenderViewHostImpl*>(GetRenderViewHost());
3691}
3692
3693BrowserPluginGuest* WebContentsImpl::GetBrowserPluginGuest() const {
3694  return browser_plugin_guest_.get();
3695}
3696
3697void WebContentsImpl::SetBrowserPluginGuest(BrowserPluginGuest* guest) {
3698  CHECK(!browser_plugin_guest_);
3699  browser_plugin_guest_.reset(guest);
3700}
3701
3702BrowserPluginEmbedder* WebContentsImpl::GetBrowserPluginEmbedder() const {
3703  return browser_plugin_embedder_.get();
3704}
3705
3706BrowserPluginGuestManager*
3707    WebContentsImpl::GetBrowserPluginGuestManager() const {
3708  return static_cast<BrowserPluginGuestManager*>(
3709      GetBrowserContext()->GetUserData(
3710          browser_plugin::kBrowserPluginGuestManagerKeyName));
3711}
3712
3713void WebContentsImpl::ClearPowerSaveBlockers(
3714    RenderViewHost* render_view_host) {
3715  STLDeleteValues(&power_save_blockers_[render_view_host]);
3716  power_save_blockers_.erase(render_view_host);
3717}
3718
3719void WebContentsImpl::ClearAllPowerSaveBlockers() {
3720  for (PowerSaveBlockerMap::iterator i(power_save_blockers_.begin());
3721       i != power_save_blockers_.end(); ++i)
3722    STLDeleteValues(&power_save_blockers_[i->first]);
3723  power_save_blockers_.clear();
3724}
3725
3726}  // namespace content
3727