web_contents_impl.cc revision a36e5920737c6adbddd3e43b760e5de8431db6e0
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  // Create a pending entry for this provisional load (if none exists) using the
2140  // current SiteInstance, and ensure the address bar updates accordingly.
2141  // We don't know the referrer or extra headers at this point, but the referrer
2142  // will be set properly upon commit.
2143  if (is_main_frame && !controller_.GetPendingEntry()) {
2144    NavigationEntryImpl* entry = NavigationEntryImpl::FromNavigationEntry(
2145        controller_.CreateNavigationEntry(validated_url,
2146                                          content::Referrer(),
2147                                          content::PAGE_TRANSITION_LINK,
2148                                          true /* is_renderer_initiated */,
2149                                          std::string(), GetBrowserContext()));
2150    entry->set_site_instance(
2151        static_cast<SiteInstanceImpl*>(GetSiteInstance()));
2152    controller_.SetPendingEntry(entry);
2153    NotifyNavigationStateChanged(content::INVALIDATE_TYPE_URL);
2154  }
2155
2156  // Notify observers about the start of the provisional load.
2157  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2158                    DidStartProvisionalLoadForFrame(frame_id, parent_frame_id,
2159                    is_main_frame, validated_url, is_error_page,
2160                    is_iframe_srcdoc, render_view_host));
2161
2162  if (is_main_frame) {
2163    // Notify observers about the provisional change in the main frame URL.
2164    FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2165                      ProvisionalChangeToMainFrameUrl(validated_url,
2166                                                      render_view_host));
2167  }
2168}
2169
2170void WebContentsImpl::DidRedirectProvisionalLoad(
2171    RenderViewHost* render_view_host,
2172    int32 page_id,
2173    const GURL& source_url,
2174    const GURL& target_url) {
2175  // TODO(creis): Remove this method and have the pre-rendering code listen to
2176  // the ResourceDispatcherHost's RESOURCE_RECEIVED_REDIRECT notification
2177  // instead.  See http://crbug.com/78512.
2178  GURL validated_source_url(source_url);
2179  GURL validated_target_url(target_url);
2180  RenderProcessHost* render_process_host =
2181      render_view_host->GetProcess();
2182  RenderViewHost::FilterURL(render_process_host, false, &validated_source_url);
2183  RenderViewHost::FilterURL(render_process_host, false, &validated_target_url);
2184  NavigationEntry* entry;
2185  if (page_id == -1) {
2186    entry = controller_.GetPendingEntry();
2187  } else {
2188    entry = controller_.GetEntryWithPageID(render_view_host->GetSiteInstance(),
2189                                           page_id);
2190  }
2191  if (!entry || entry->GetURL() != validated_source_url)
2192    return;
2193
2194  // Notify observers about the provisional change in the main frame URL.
2195  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2196                    ProvisionalChangeToMainFrameUrl(validated_target_url,
2197                                                    render_view_host));
2198}
2199
2200void WebContentsImpl::DidFailProvisionalLoadWithError(
2201    RenderViewHost* render_view_host,
2202    const ViewHostMsg_DidFailProvisionalLoadWithError_Params& params) {
2203  VLOG(1) << "Failed Provisional Load: " << params.url.possibly_invalid_spec()
2204          << ", error_code: " << params.error_code
2205          << ", error_description: " << params.error_description
2206          << ", is_main_frame: " << params.is_main_frame
2207          << ", showing_repost_interstitial: " <<
2208            params.showing_repost_interstitial
2209          << ", frame_id: " << params.frame_id;
2210  GURL validated_url(params.url);
2211  RenderProcessHost* render_process_host =
2212      render_view_host->GetProcess();
2213  RenderViewHost::FilterURL(render_process_host, false, &validated_url);
2214
2215  if (net::ERR_ABORTED == params.error_code) {
2216    // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
2217    // This means that the interstitial won't be torn down properly, which is
2218    // bad. But if we have an interstitial, go back to another tab type, and
2219    // then load the same interstitial again, we could end up getting the first
2220    // interstitial's "failed" message (as a result of the cancel) when we're on
2221    // the second one.
2222    //
2223    // We can't tell this apart, so we think we're tearing down the current page
2224    // which will cause a crash later one. There is also some code in
2225    // RenderViewHostManager::RendererAbortedProvisionalLoad that is commented
2226    // out because of this problem.
2227    //
2228    // http://code.google.com/p/chromium/issues/detail?id=2855
2229    // Because this will not tear down the interstitial properly, if "back" is
2230    // back to another tab type, the interstitial will still be somewhat alive
2231    // in the previous tab type. If you navigate somewhere that activates the
2232    // tab with the interstitial again, you'll see a flash before the new load
2233    // commits of the interstitial page.
2234    if (ShowingInterstitialPage()) {
2235      LOG(WARNING) << "Discarding message during interstitial.";
2236      return;
2237    }
2238
2239    // Do not clear the pending entry if one exists, so that the user's typed
2240    // URL is not lost when a navigation fails or is aborted.  We'll allow
2241    // the view to clear the pending entry and typed URL if the user requests.
2242
2243    render_manager_.RendererAbortedProvisionalLoad(render_view_host);
2244  }
2245
2246  FOR_EACH_OBSERVER(WebContentsObserver,
2247                    observers_,
2248                    DidFailProvisionalLoad(params.frame_id,
2249                                           params.is_main_frame,
2250                                           validated_url,
2251                                           params.error_code,
2252                                           params.error_description,
2253                                           render_view_host));
2254}
2255
2256void WebContentsImpl::OnDidLoadResourceFromMemoryCache(
2257    const GURL& url,
2258    const std::string& security_info,
2259    const std::string& http_method,
2260    const std::string& mime_type,
2261    ResourceType::Type resource_type) {
2262  base::StatsCounter cache("WebKit.CacheHit");
2263  cache.Increment();
2264
2265  // Send out a notification that we loaded a resource from our memory cache.
2266  int cert_id = 0;
2267  net::CertStatus cert_status = 0;
2268  int security_bits = -1;
2269  int connection_status = 0;
2270  DeserializeSecurityInfo(security_info, &cert_id, &cert_status,
2271                          &security_bits, &connection_status);
2272  LoadFromMemoryCacheDetails details(
2273      url, GetRenderProcessHost()->GetID(), cert_id, cert_status, http_method,
2274      mime_type, resource_type);
2275
2276  NotificationService::current()->Notify(
2277      NOTIFICATION_LOAD_FROM_MEMORY_CACHE,
2278      Source<NavigationController>(&controller_),
2279      Details<LoadFromMemoryCacheDetails>(&details));
2280}
2281
2282void WebContentsImpl::OnDidDisplayInsecureContent() {
2283  RecordAction(UserMetricsAction("SSL.DisplayedInsecureContent"));
2284  displayed_insecure_content_ = true;
2285  SSLManager::NotifySSLInternalStateChanged(
2286      GetController().GetBrowserContext());
2287}
2288
2289void WebContentsImpl::OnDidRunInsecureContent(
2290    const std::string& security_origin, const GURL& target_url) {
2291  LOG(INFO) << security_origin << " ran insecure content from "
2292            << target_url.possibly_invalid_spec();
2293  RecordAction(UserMetricsAction("SSL.RanInsecureContent"));
2294  if (EndsWith(security_origin, kDotGoogleDotCom, false))
2295    RecordAction(UserMetricsAction("SSL.RanInsecureContentGoogle"));
2296  controller_.ssl_manager()->DidRunInsecureContent(security_origin);
2297  displayed_insecure_content_ = true;
2298  SSLManager::NotifySSLInternalStateChanged(
2299      GetController().GetBrowserContext());
2300}
2301
2302void WebContentsImpl::OnDocumentLoadedInFrame(int64 frame_id) {
2303  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2304                    DocumentLoadedInFrame(frame_id, message_source_));
2305}
2306
2307void WebContentsImpl::OnDidFinishLoad(
2308    int64 frame_id,
2309    const GURL& url,
2310    bool is_main_frame) {
2311  GURL validated_url(url);
2312  RenderProcessHost* render_process_host = message_source_->GetProcess();
2313  RenderViewHost::FilterURL(render_process_host, false, &validated_url);
2314  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2315                    DidFinishLoad(frame_id, validated_url, is_main_frame,
2316                                  message_source_));
2317}
2318
2319void WebContentsImpl::OnDidFailLoadWithError(
2320    int64 frame_id,
2321    const GURL& url,
2322    bool is_main_frame,
2323    int error_code,
2324    const string16& error_description) {
2325  GURL validated_url(url);
2326  RenderProcessHost* render_process_host = message_source_->GetProcess();
2327  RenderViewHost::FilterURL(render_process_host, false, &validated_url);
2328  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2329                    DidFailLoad(frame_id, validated_url, is_main_frame,
2330                                error_code, error_description,
2331                                message_source_));
2332}
2333
2334void WebContentsImpl::OnGoToEntryAtOffset(int offset) {
2335  if (!delegate_ || delegate_->OnGoToEntryOffset(offset)) {
2336    NavigationEntryImpl* entry = NavigationEntryImpl::FromNavigationEntry(
2337        controller_.GetEntryAtOffset(offset));
2338    if (!entry)
2339      return;
2340    // Note that we don't call NavigationController::GotToOffset() as we don't
2341    // want to create a pending navigation entry (it might end up lingering
2342    // http://crbug.com/51680).
2343    entry->SetTransitionType(
2344        PageTransitionFromInt(
2345            entry->GetTransitionType() |
2346            PAGE_TRANSITION_FORWARD_BACK));
2347    NavigateToEntry(*entry, NavigationControllerImpl::NO_RELOAD);
2348
2349    // If the entry is being restored and doesn't have a SiteInstance yet, fill
2350    // it in now that we know. This allows us to find the entry when it commits.
2351    if (!entry->site_instance() &&
2352        entry->restore_type() != NavigationEntryImpl::RESTORE_NONE) {
2353      entry->set_site_instance(
2354          static_cast<SiteInstanceImpl*>(GetPendingSiteInstance()));
2355    }
2356  }
2357}
2358
2359void WebContentsImpl::OnUpdateZoomLimits(int minimum_percent,
2360                                         int maximum_percent,
2361                                         bool remember) {
2362  minimum_zoom_percent_ = minimum_percent;
2363  maximum_zoom_percent_ = maximum_percent;
2364  temporary_zoom_settings_ = !remember;
2365}
2366
2367void WebContentsImpl::OnEnumerateDirectory(int request_id,
2368                                           const base::FilePath& path) {
2369  if (!delegate_)
2370    return;
2371
2372  ChildProcessSecurityPolicyImpl* policy =
2373      ChildProcessSecurityPolicyImpl::GetInstance();
2374  if (policy->CanReadDirectory(GetRenderProcessHost()->GetID(), path))
2375    delegate_->EnumerateDirectory(this, request_id, path);
2376}
2377
2378void WebContentsImpl::OnJSOutOfMemory() {
2379  if (delegate_)
2380    delegate_->JSOutOfMemory(this);
2381}
2382
2383void WebContentsImpl::OnRegisterProtocolHandler(const std::string& protocol,
2384                                                const GURL& url,
2385                                                const string16& title,
2386                                                bool user_gesture) {
2387  if (!delegate_)
2388    return;
2389
2390  ChildProcessSecurityPolicyImpl* policy =
2391      ChildProcessSecurityPolicyImpl::GetInstance();
2392  if (policy->IsPseudoScheme(protocol))
2393    return;
2394
2395  delegate_->RegisterProtocolHandler(this, protocol, url, title, user_gesture);
2396}
2397
2398void WebContentsImpl::OnFindReply(int request_id,
2399                                  int number_of_matches,
2400                                  const gfx::Rect& selection_rect,
2401                                  int active_match_ordinal,
2402                                  bool final_update) {
2403  if (delegate_) {
2404    delegate_->FindReply(this, request_id, number_of_matches, selection_rect,
2405                         active_match_ordinal, final_update);
2406  }
2407}
2408
2409void WebContentsImpl::OnDidProgrammaticallyScroll(
2410    const gfx::Vector2d& scroll_point) {
2411  if (delegate_)
2412    delegate_->DidProgrammaticallyScroll(this, scroll_point);
2413}
2414
2415#if defined(OS_ANDROID)
2416void WebContentsImpl::OnFindMatchRectsReply(
2417    int version,
2418    const std::vector<gfx::RectF>& rects,
2419    const gfx::RectF& active_rect) {
2420  if (delegate_)
2421    delegate_->FindMatchRectsReply(this, version, rects, active_rect);
2422}
2423
2424void WebContentsImpl::OnOpenDateTimeDialog(
2425    const ViewHostMsg_DateTimeDialogValue_Params& value) {
2426  date_time_chooser_->ShowDialog(
2427      ContentViewCore::FromWebContents(this), GetRenderViewHost(),
2428      value.dialog_type, value.year, value.month, value.day, value.hour,
2429      value.minute, value.second, value.week, value.minimum, value.maximum);
2430}
2431
2432#endif
2433
2434void WebContentsImpl::OnCrashedPlugin(const base::FilePath& plugin_path,
2435                                      base::ProcessId plugin_pid) {
2436  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2437                    PluginCrashed(plugin_path, plugin_pid));
2438}
2439
2440void WebContentsImpl::OnAppCacheAccessed(const GURL& manifest_url,
2441                                         bool blocked_by_policy) {
2442  // Notify observers about navigation.
2443  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2444                    AppCacheAccessed(manifest_url, blocked_by_policy));
2445}
2446
2447void WebContentsImpl::OnOpenColorChooser(int color_chooser_id,
2448                                         SkColor color) {
2449  ColorChooser* new_color_chooser = delegate_->OpenColorChooser(this, color);
2450  if (color_chooser_ == new_color_chooser)
2451    return;
2452  color_chooser_.reset(new_color_chooser);
2453  color_chooser_identifier_ = color_chooser_id;
2454}
2455
2456void WebContentsImpl::OnEndColorChooser(int color_chooser_id) {
2457  if (color_chooser_ &&
2458      color_chooser_id == color_chooser_identifier_)
2459    color_chooser_->End();
2460}
2461
2462void WebContentsImpl::OnSetSelectedColorInColorChooser(int color_chooser_id,
2463                                                       SkColor color) {
2464  if (color_chooser_ &&
2465      color_chooser_id == color_chooser_identifier_)
2466    color_chooser_->SetSelectedColor(color);
2467}
2468
2469void WebContentsImpl::OnPepperPluginHung(int plugin_child_id,
2470                                         const base::FilePath& path,
2471                                         bool is_hung) {
2472  UMA_HISTOGRAM_COUNTS("Pepper.PluginHung", 1);
2473
2474  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2475                    PluginHungStatusChanged(plugin_child_id, path, is_hung));
2476}
2477
2478// This exists for render views that don't have a WebUI, but do have WebUI
2479// bindings enabled.
2480void WebContentsImpl::OnWebUISend(const GURL& source_url,
2481                                  const std::string& name,
2482                                  const base::ListValue& args) {
2483  if (delegate_)
2484    delegate_->WebUISend(this, source_url, name, args);
2485}
2486
2487void WebContentsImpl::OnRequestPpapiBrokerPermission(
2488    int request_id,
2489    const GURL& url,
2490    const base::FilePath& plugin_path) {
2491  if (!delegate_) {
2492    OnPpapiBrokerPermissionResult(request_id, false);
2493    return;
2494  }
2495
2496  if (!delegate_->RequestPpapiBrokerPermission(
2497      this, url, plugin_path,
2498      base::Bind(&WebContentsImpl::OnPpapiBrokerPermissionResult,
2499                 base::Unretained(this), request_id))) {
2500    NOTIMPLEMENTED();
2501    OnPpapiBrokerPermissionResult(request_id, false);
2502  }
2503}
2504
2505void WebContentsImpl::OnPpapiBrokerPermissionResult(int request_id,
2506                                                    bool result) {
2507  RenderViewHostImpl* rvh = GetRenderViewHostImpl();
2508  rvh->Send(new ViewMsg_PpapiBrokerPermissionResult(rvh->GetRoutingID(),
2509                                                    request_id,
2510                                                    result));
2511}
2512
2513void WebContentsImpl::OnBrowserPluginMessage(const IPC::Message& message) {
2514  // This creates a BrowserPluginEmbedder, which handles all the BrowserPlugin
2515  // specific messages for this WebContents. This means that any message from
2516  // a BrowserPlugin prior to this will be ignored.
2517  // For more info, see comment above classes BrowserPluginEmbedder and
2518  // BrowserPluginGuest.
2519  CHECK(!browser_plugin_embedder_.get());
2520  browser_plugin_embedder_.reset(BrowserPluginEmbedder::Create(this));
2521  browser_plugin_embedder_->OnMessageReceived(message);
2522}
2523
2524void WebContentsImpl::OnDidDownloadImage(
2525    int id,
2526    int http_status_code,
2527    const GURL& image_url,
2528    int requested_size,
2529    const std::vector<SkBitmap>& bitmaps) {
2530  ImageDownloadMap::iterator iter = image_download_map_.find(id);
2531  if (iter == image_download_map_.end()) {
2532    // Currently WebContents notifies us of ANY downloads so that it is
2533    // possible to get here.
2534    return;
2535  }
2536  if (!iter->second.is_null()) {
2537    iter->second.Run(id, http_status_code, image_url, requested_size, bitmaps);
2538  }
2539  image_download_map_.erase(id);
2540}
2541
2542void WebContentsImpl::OnUpdateFaviconURL(
2543    int32 page_id,
2544    const std::vector<FaviconURL>& candidates) {
2545  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2546                    DidUpdateFaviconURL(page_id, candidates));
2547}
2548
2549FrameTreeNode* WebContentsImpl::FindFrameTreeNodeByID(int64 frame_id) {
2550  // TODO(nasko): Remove this check once we move to creating the root node
2551  // through RenderFrameHost creation.
2552  if (!frame_tree_root_.get())
2553    return NULL;
2554
2555  FrameTreeNode* node = NULL;
2556  std::queue<FrameTreeNode*> queue;
2557  queue.push(frame_tree_root_.get());
2558
2559  while (!queue.empty()) {
2560    node = queue.front();
2561    queue.pop();
2562    if (node->frame_id() == frame_id)
2563      return node;
2564
2565    for (size_t i = 0; i < node->child_count(); ++i)
2566      queue.push(node->child_at(i));
2567  }
2568
2569  return NULL;
2570}
2571
2572void WebContentsImpl::OnFrameAttached(
2573    int64 parent_frame_id,
2574    int64 frame_id,
2575    const std::string& frame_name) {
2576  FrameTreeNode* parent = FindFrameTreeNodeByID(parent_frame_id);
2577  if (!parent)
2578    return;
2579
2580  FrameTreeNode* node = new FrameTreeNode(frame_id, frame_name);
2581  parent->AddChild(node);
2582}
2583
2584void WebContentsImpl::OnFrameDetached(int64 parent_frame_id, int64 frame_id) {
2585  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2586                    FrameDetached(message_source_, frame_id));
2587
2588  FrameTreeNode* parent = FindFrameTreeNodeByID(parent_frame_id);
2589  if (!parent)
2590    return;
2591
2592  parent->RemoveChild(frame_id);
2593}
2594
2595void WebContentsImpl::OnMediaNotification(int64 player_cookie,
2596                                          bool has_video,
2597                                          bool has_audio,
2598                                          bool is_playing) {
2599  // Chrome OS does its own detection of audio and video.
2600#if !defined(OS_CHROMEOS)
2601  if (is_playing) {
2602    scoped_ptr<PowerSaveBlocker> blocker;
2603    if (has_video) {
2604      blocker = PowerSaveBlocker::Create(
2605          PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep,
2606          "Playing video");
2607#if defined(OS_ANDROID)
2608      static_cast<PowerSaveBlockerImpl*>(blocker.get())->
2609          InitDisplaySleepBlocker(GetView()->GetTopLevelNativeWindow());
2610#endif
2611    } else if (has_audio) {
2612      blocker = PowerSaveBlocker::Create(
2613          PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension,
2614          "Playing audio");
2615    }
2616
2617    if (blocker)
2618      power_save_blockers_[message_source_][player_cookie] = blocker.release();
2619  } else {
2620    delete power_save_blockers_[message_source_][player_cookie];
2621    power_save_blockers_[message_source_].erase(player_cookie);
2622  }
2623#endif  // !defined(OS_CHROMEOS)
2624}
2625
2626
2627void WebContentsImpl::DidChangeVisibleSSLState() {
2628  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2629                    DidChangeVisibleSSLState());
2630}
2631
2632void WebContentsImpl::NotifyBeforeFormRepostWarningShow() {
2633  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2634                    BeforeFormRepostWarningShow());
2635}
2636
2637// Notifies the RenderWidgetHost instance about the fact that the page is
2638// loading, or done loading and calls the base implementation.
2639void WebContentsImpl::SetIsLoading(bool is_loading,
2640                                   LoadNotificationDetails* details) {
2641  if (is_loading == is_loading_)
2642    return;
2643
2644  if (!is_loading) {
2645    load_state_ = net::LoadStateWithParam(net::LOAD_STATE_IDLE, string16());
2646    load_state_host_.clear();
2647    upload_size_ = 0;
2648    upload_position_ = 0;
2649  }
2650
2651  render_manager_.SetIsLoading(is_loading);
2652
2653  is_loading_ = is_loading;
2654  waiting_for_response_ = is_loading;
2655
2656  if (delegate_)
2657    delegate_->LoadingStateChanged(this);
2658  NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD);
2659
2660  if (is_loading)
2661    TRACE_EVENT_ASYNC_BEGIN0("browser", "WebContentsImpl Loading", this);
2662  else
2663    TRACE_EVENT_ASYNC_END0("browser", "WebContentsImpl Loading", this);
2664  int type = is_loading ? NOTIFICATION_LOAD_START : NOTIFICATION_LOAD_STOP;
2665  NotificationDetails det = NotificationService::NoDetails();
2666  if (details)
2667      det = Details<LoadNotificationDetails>(details);
2668  NotificationService::current()->Notify(
2669      type, Source<NavigationController>(&controller_), det);
2670}
2671
2672void WebContentsImpl::DidNavigateMainFramePostCommit(
2673    const LoadCommittedDetails& details,
2674    const ViewHostMsg_FrameNavigate_Params& params) {
2675  if (details.is_navigation_to_different_page()) {
2676    // Clear the status bubble. This is a workaround for a bug where WebKit
2677    // doesn't let us know that the cursor left an element during a
2678    // transition (this is also why the mouse cursor remains as a hand after
2679    // clicking on a link); see bugs 1184641 and 980803. We don't want to
2680    // clear the bubble when a user navigates to a named anchor in the same
2681    // page.
2682    UpdateTargetURL(details.entry->GetPageID(), GURL());
2683  }
2684
2685  if (!details.is_in_page) {
2686    // Once the main frame is navigated, we're no longer considered to have
2687    // displayed insecure content.
2688    displayed_insecure_content_ = false;
2689    SSLManager::NotifySSLInternalStateChanged(
2690        GetController().GetBrowserContext());
2691  }
2692
2693  // Notify observers about navigation.
2694  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2695                    DidNavigateMainFrame(details, params));
2696}
2697
2698void WebContentsImpl::DidNavigateAnyFramePostCommit(
2699    RenderViewHost* render_view_host,
2700    const LoadCommittedDetails& details,
2701    const ViewHostMsg_FrameNavigate_Params& params) {
2702  // If we navigate off the page, close all JavaScript dialogs.
2703  if (dialog_manager_ && !details.is_in_page)
2704    dialog_manager_->CancelActiveAndPendingDialogs(this);
2705
2706  // Notify observers about navigation.
2707  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2708                    DidNavigateAnyFrame(details, params));
2709}
2710
2711bool WebContentsImpl::ShouldAssignSiteForURL(const GURL& url) {
2712  // about:blank should not "use up" a new SiteInstance.  The SiteInstance can
2713  // still be used for a normal web site.
2714  if (url == GURL(kAboutBlankURL))
2715    return false;
2716
2717  // The embedder will then have the opportunity to determine if the URL
2718  // should "use up" the SiteInstance.
2719  return GetContentClient()->browser()->ShouldAssignSiteForURL(url);
2720}
2721
2722void WebContentsImpl::UpdateMaxPageIDIfNecessary(RenderViewHost* rvh) {
2723  // If we are creating a RVH for a restored controller, then we need to make
2724  // sure the RenderView starts with a next_page_id_ larger than the number
2725  // of restored entries.  This must be called before the RenderView starts
2726  // navigating (to avoid a race between the browser updating max_page_id and
2727  // the renderer updating next_page_id_).  Because of this, we only call this
2728  // from CreateRenderView and allow that to notify the RenderView for us.
2729  int max_restored_page_id = controller_.GetMaxRestoredPageID();
2730  if (max_restored_page_id >
2731      GetMaxPageIDForSiteInstance(rvh->GetSiteInstance()))
2732    UpdateMaxPageIDForSiteInstance(rvh->GetSiteInstance(),
2733                                   max_restored_page_id);
2734}
2735
2736bool WebContentsImpl::UpdateTitleForEntry(NavigationEntryImpl* entry,
2737                                          const string16& title) {
2738  // For file URLs without a title, use the pathname instead. In the case of a
2739  // synthesized title, we don't want the update to count toward the "one set
2740  // per page of the title to history."
2741  string16 final_title;
2742  bool explicit_set;
2743  if (entry && entry->GetURL().SchemeIsFile() && title.empty()) {
2744    final_title = UTF8ToUTF16(entry->GetURL().ExtractFileName());
2745    explicit_set = false;  // Don't count synthetic titles toward the set limit.
2746  } else {
2747    TrimWhitespace(title, TRIM_ALL, &final_title);
2748    explicit_set = true;
2749  }
2750
2751  // If a page is created via window.open and never navigated,
2752  // there will be no navigation entry. In this situation,
2753  // |page_title_when_no_navigation_entry_| will be used for page title.
2754  if (entry) {
2755    if (final_title == entry->GetTitle())
2756      return false;  // Nothing changed, don't bother.
2757
2758    entry->SetTitle(final_title);
2759  } else {
2760    if (page_title_when_no_navigation_entry_ == final_title)
2761      return false;  // Nothing changed, don't bother.
2762
2763    page_title_when_no_navigation_entry_ = final_title;
2764  }
2765
2766  // Lastly, set the title for the view.
2767  view_->SetPageTitle(final_title);
2768
2769  std::pair<NavigationEntry*, bool> details =
2770      std::make_pair(entry, explicit_set);
2771
2772  NotificationService::current()->Notify(
2773      NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED,
2774      Source<WebContents>(this),
2775      Details<std::pair<NavigationEntry*, bool> >(&details));
2776
2777  return true;
2778}
2779
2780void WebContentsImpl::NotifySwapped(RenderViewHost* old_render_view_host) {
2781  // After sending out a swap notification, we need to send a disconnect
2782  // notification so that clients that pick up a pointer to |this| can NULL the
2783  // pointer.  See Bug 1230284.
2784  notify_disconnection_ = true;
2785  NotificationService::current()->Notify(
2786      NOTIFICATION_WEB_CONTENTS_SWAPPED,
2787      Source<WebContents>(this),
2788      Details<RenderViewHost>(old_render_view_host));
2789
2790  // Ensure that the associated embedder gets cleared after a RenderViewHost
2791  // gets swapped, so we don't reuse the same embedder next time a
2792  // RenderViewHost is attached to this WebContents.
2793  RemoveBrowserPluginEmbedder();
2794}
2795
2796void WebContentsImpl::NotifyConnected() {
2797  notify_disconnection_ = true;
2798  NotificationService::current()->Notify(
2799      NOTIFICATION_WEB_CONTENTS_CONNECTED,
2800      Source<WebContents>(this),
2801      NotificationService::NoDetails());
2802}
2803
2804void WebContentsImpl::NotifyDisconnected() {
2805  if (!notify_disconnection_)
2806    return;
2807
2808  notify_disconnection_ = false;
2809  NotificationService::current()->Notify(
2810      NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
2811      Source<WebContents>(this),
2812      NotificationService::NoDetails());
2813}
2814
2815void WebContentsImpl::NotifyNavigationEntryCommitted(
2816    const LoadCommittedDetails& load_details) {
2817  FOR_EACH_OBSERVER(
2818      WebContentsObserver, observers_, NavigationEntryCommitted(load_details));
2819}
2820
2821RenderViewHostDelegateView* WebContentsImpl::GetDelegateView() {
2822  return render_view_host_delegate_view_;
2823}
2824
2825RenderViewHostDelegate::RendererManagement*
2826WebContentsImpl::GetRendererManagementDelegate() {
2827  return &render_manager_;
2828}
2829
2830RendererPreferences WebContentsImpl::GetRendererPrefs(
2831    BrowserContext* browser_context) const {
2832  return renderer_preferences_;
2833}
2834
2835WebContents* WebContentsImpl::GetAsWebContents() {
2836  return this;
2837}
2838
2839gfx::Rect WebContentsImpl::GetRootWindowResizerRect() const {
2840  if (delegate_)
2841    return delegate_->GetRootWindowResizerRect();
2842  return gfx::Rect();
2843}
2844
2845void WebContentsImpl::RemoveBrowserPluginEmbedder() {
2846  if (browser_plugin_embedder_)
2847    browser_plugin_embedder_.reset();
2848}
2849
2850void WebContentsImpl::RenderViewCreated(RenderViewHost* render_view_host) {
2851  // Don't send notifications if we are just creating a swapped-out RVH for
2852  // the opener chain.  These won't be used for view-source or WebUI, so it's
2853  // ok to return early.
2854  if (static_cast<RenderViewHostImpl*>(render_view_host)->is_swapped_out())
2855    return;
2856
2857  if (delegate_)
2858    view_->SetOverscrollControllerEnabled(delegate_->CanOverscrollContent());
2859
2860  NotificationService::current()->Notify(
2861      NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED,
2862      Source<WebContents>(this),
2863      Details<RenderViewHost>(render_view_host));
2864  NavigationEntry* entry = controller_.GetActiveEntry();
2865  if (!entry)
2866    return;
2867
2868  // When we're creating views, we're still doing initial setup, so we always
2869  // use the pending Web UI rather than any possibly existing committed one.
2870  if (render_manager_.pending_web_ui())
2871    render_manager_.pending_web_ui()->RenderViewCreated(render_view_host);
2872
2873  if (entry->IsViewSourceMode()) {
2874    // Put the renderer in view source mode.
2875    render_view_host->Send(
2876        new ViewMsg_EnableViewSourceMode(render_view_host->GetRoutingID()));
2877  }
2878
2879  view_->RenderViewCreated(render_view_host);
2880
2881  FOR_EACH_OBSERVER(
2882      WebContentsObserver, observers_, RenderViewCreated(render_view_host));
2883}
2884
2885void WebContentsImpl::RenderViewReady(RenderViewHost* rvh) {
2886  if (rvh != GetRenderViewHost()) {
2887    // Don't notify the world, since this came from a renderer in the
2888    // background.
2889    return;
2890  }
2891
2892  NotifyConnected();
2893  bool was_crashed = IsCrashed();
2894  SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING, 0);
2895
2896  // Restore the focus to the tab (otherwise the focus will be on the top
2897  // window).
2898  if (was_crashed && !FocusLocationBarByDefault() &&
2899      (!delegate_ || delegate_->ShouldFocusPageAfterCrash())) {
2900    view_->Focus();
2901  }
2902
2903  FOR_EACH_OBSERVER(WebContentsObserver, observers_, RenderViewReady());
2904}
2905
2906void WebContentsImpl::RenderViewTerminated(RenderViewHost* rvh,
2907                                           base::TerminationStatus status,
2908                                           int error_code) {
2909  if (rvh != GetRenderViewHost()) {
2910    // The pending page's RenderViewHost is gone.
2911    return;
2912  }
2913
2914  ClearPowerSaveBlockers(rvh);
2915  SetIsLoading(false, NULL);
2916  NotifyDisconnected();
2917  SetIsCrashed(status, error_code);
2918  GetView()->OnTabCrashed(GetCrashedStatus(), crashed_error_code_);
2919
2920  FOR_EACH_OBSERVER(WebContentsObserver,
2921                    observers_,
2922                    RenderProcessGone(GetCrashedStatus()));
2923}
2924
2925void WebContentsImpl::RenderViewDeleted(RenderViewHost* rvh) {
2926  ClearPowerSaveBlockers(rvh);
2927  render_manager_.RenderViewDeleted(rvh);
2928  FOR_EACH_OBSERVER(WebContentsObserver, observers_, RenderViewDeleted(rvh));
2929}
2930
2931void WebContentsImpl::DidNavigate(
2932    RenderViewHost* rvh,
2933    const ViewHostMsg_FrameNavigate_Params& params) {
2934  // If we don't have a frame tree root yet, this is the first navigation in
2935  // using the current RenderViewHost, so we need to create it with the proper
2936  // frame id.
2937  if (!frame_tree_root_.get()) {
2938    DCHECK(PageTransitionIsMainFrame(params.transition));
2939    frame_tree_root_.reset(new FrameTreeNode(params.frame_id, std::string()));
2940  }
2941
2942  if (PageTransitionIsMainFrame(params.transition)) {
2943    // When overscroll navigation gesture is enabled, a screenshot of the page
2944    // in its current state is taken so that it can be used during the
2945    // nav-gesture. It is necessary to take the screenshot here, before calling
2946    // RenderViewHostManager::DidNavigateMainFrame, because that can change
2947    // WebContents::GetRenderViewHost to return the new host, instead of the one
2948    // that may have just been swapped out.
2949    if (delegate_ && delegate_->CanOverscrollContent())
2950      controller_.TakeScreenshot();
2951
2952    render_manager_.DidNavigateMainFrame(rvh);
2953  }
2954
2955  // We expect to have a valid frame tree root node at all times when
2956  // navigating.
2957  DCHECK(frame_tree_root_.get());
2958
2959  // Update the site of the SiteInstance if it doesn't have one yet, unless
2960  // assigning a site is not necessary for this URL.  In that case, the
2961  // SiteInstance can still be considered unused until a navigation to a real
2962  // page.
2963  if (!static_cast<SiteInstanceImpl*>(GetSiteInstance())->HasSite() &&
2964      ShouldAssignSiteForURL(params.url)) {
2965    static_cast<SiteInstanceImpl*>(GetSiteInstance())->SetSite(params.url);
2966  }
2967
2968  // Need to update MIME type here because it's referred to in
2969  // UpdateNavigationCommands() called by RendererDidNavigate() to
2970  // determine whether or not to enable the encoding menu.
2971  // It's updated only for the main frame. For a subframe,
2972  // RenderView::UpdateURL does not set params.contents_mime_type.
2973  // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
2974  // TODO(jungshik): Add a test for the encoding menu to avoid
2975  // regressing it again.
2976  if (PageTransitionIsMainFrame(params.transition))
2977    contents_mime_type_ = params.contents_mime_type;
2978
2979  LoadCommittedDetails details;
2980  bool did_navigate = controller_.RendererDidNavigate(params, &details);
2981
2982  // For now, keep track of each frame's URL in its FrameTreeNode.  This lets
2983  // us estimate our process count for implementing OOP iframes.
2984  // TODO(creis): Remove this when we track which pages commit in each frame.
2985  FrameTreeNode* node = FindFrameTreeNodeByID(params.frame_id);
2986  if (node)
2987    node->set_current_url(params.url);
2988
2989  // Send notification about committed provisional loads. This notification is
2990  // different from the NAV_ENTRY_COMMITTED notification which doesn't include
2991  // the actual URL navigated to and isn't sent for AUTO_SUBFRAME navigations.
2992  if (details.type != NAVIGATION_TYPE_NAV_IGNORE) {
2993    // For AUTO_SUBFRAME navigations, an event for the main frame is generated
2994    // that is not recorded in the navigation history. For the purpose of
2995    // tracking navigation events, we treat this event as a sub frame navigation
2996    // event.
2997    bool is_main_frame = did_navigate ? details.is_main_frame : false;
2998    PageTransition transition_type = params.transition;
2999    // Whether or not a page transition was triggered by going backward or
3000    // forward in the history is only stored in the navigation controller's
3001    // entry list.
3002    if (did_navigate &&
3003        (controller_.GetActiveEntry()->GetTransitionType() &
3004            PAGE_TRANSITION_FORWARD_BACK)) {
3005      transition_type = PageTransitionFromInt(
3006          params.transition | PAGE_TRANSITION_FORWARD_BACK);
3007    }
3008    // Notify observers about the commit of the provisional load.
3009    FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3010                      DidCommitProvisionalLoadForFrame(params.frame_id,
3011                      is_main_frame, params.url, transition_type, rvh));
3012  }
3013
3014  if (!did_navigate)
3015    return;  // No navigation happened.
3016
3017  // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
3018  // for the appropriate notification (best) or you can add it to
3019  // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
3020  // necessary, please).
3021
3022  // Run post-commit tasks.
3023  if (details.is_main_frame) {
3024    DidNavigateMainFramePostCommit(details, params);
3025    if (delegate_) {
3026      delegate_->DidNavigateMainFramePostCommit(this);
3027      view_->SetOverscrollControllerEnabled(delegate_->CanOverscrollContent());
3028    }
3029  }
3030  DidNavigateAnyFramePostCommit(rvh, details, params);
3031}
3032
3033void WebContentsImpl::UpdateState(RenderViewHost* rvh,
3034                                  int32 page_id,
3035                                  const PageState& page_state) {
3036  // Ensure that this state update comes from either the active RVH or one of
3037  // the swapped out RVHs.  We don't expect to hear from any other RVHs.
3038  DCHECK(rvh == GetRenderViewHost() || render_manager_.IsOnSwappedOutList(rvh));
3039
3040  // We must be prepared to handle state updates for any page, these occur
3041  // when the user is scrolling and entering form data, as well as when we're
3042  // leaving a page, in which case our state may have already been moved to
3043  // the next page. The navigation controller will look up the appropriate
3044  // NavigationEntry and update it when it is notified via the delegate.
3045
3046  int entry_index = controller_.GetEntryIndexWithPageID(
3047      rvh->GetSiteInstance(), page_id);
3048  if (entry_index < 0)
3049    return;
3050  NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
3051
3052  if (page_state == entry->GetPageState())
3053    return;  // Nothing to update.
3054  entry->SetPageState(page_state);
3055  controller_.NotifyEntryChanged(entry, entry_index);
3056}
3057
3058void WebContentsImpl::UpdateTitle(RenderViewHost* rvh,
3059                                  int32 page_id,
3060                                  const string16& title,
3061                                  base::i18n::TextDirection title_direction) {
3062  // If we have a title, that's a pretty good indication that we've started
3063  // getting useful data.
3064  SetNotWaitingForResponse();
3065
3066  // Try to find the navigation entry, which might not be the current one.
3067  // For example, it might be from a pending RVH for the pending entry.
3068  NavigationEntryImpl* entry = controller_.GetEntryWithPageID(
3069      rvh->GetSiteInstance(), page_id);
3070
3071  // We can handle title updates when we don't have an entry in
3072  // UpdateTitleForEntry, but only if the update is from the current RVH.
3073  if (!entry && rvh != GetRenderViewHost())
3074    return;
3075
3076  // TODO(evan): make use of title_direction.
3077  // http://code.google.com/p/chromium/issues/detail?id=27094
3078  if (!UpdateTitleForEntry(entry, title))
3079    return;
3080
3081  // Broadcast notifications when the UI should be updated.
3082  if (entry == controller_.GetEntryAtOffset(0))
3083    NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE);
3084}
3085
3086void WebContentsImpl::UpdateEncoding(RenderViewHost* render_view_host,
3087                                     const std::string& encoding) {
3088  SetEncoding(encoding);
3089}
3090
3091void WebContentsImpl::UpdateTargetURL(int32 page_id, const GURL& url) {
3092  if (delegate_)
3093    delegate_->UpdateTargetURL(this, page_id, url);
3094}
3095
3096void WebContentsImpl::Close(RenderViewHost* rvh) {
3097#if defined(OS_MACOSX)
3098  // The UI may be in an event-tracking loop, such as between the
3099  // mouse-down and mouse-up in text selection or a button click.
3100  // Defer the close until after tracking is complete, so that we
3101  // don't free objects out from under the UI.
3102  // TODO(shess): This could get more fine-grained.  For instance,
3103  // closing a tab in another window while selecting text in the
3104  // current window's Omnibox should be just fine.
3105  if (view_->IsEventTracking()) {
3106    view_->CloseTabAfterEventTracking();
3107    return;
3108  }
3109#endif
3110
3111  // Ignore this if it comes from a RenderViewHost that we aren't showing.
3112  if (delegate_ && rvh == GetRenderViewHost())
3113    delegate_->CloseContents(this);
3114}
3115
3116void WebContentsImpl::SwappedOut(RenderViewHost* rvh) {
3117  if (delegate_ && rvh == GetRenderViewHost())
3118    delegate_->SwappedOut(this);
3119
3120  // Allow the navigation to proceed.
3121  render_manager_.SwappedOut(rvh);
3122}
3123
3124void WebContentsImpl::RequestMove(const gfx::Rect& new_bounds) {
3125  if (delegate_ && delegate_->IsPopupOrPanel(this))
3126    delegate_->MoveContents(this, new_bounds);
3127}
3128
3129void WebContentsImpl::DidStartLoading(RenderViewHost* render_view_host) {
3130  SetIsLoading(true, NULL);
3131
3132  // Notify observers about navigation.
3133  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3134                    DidStartLoading(render_view_host));
3135}
3136
3137void WebContentsImpl::DidStopLoading(RenderViewHost* render_view_host) {
3138  scoped_ptr<LoadNotificationDetails> details;
3139
3140  // Use the last committed entry rather than the active one, in case a
3141  // pending entry has been created.
3142  NavigationEntry* entry = controller_.GetLastCommittedEntry();
3143
3144  // An entry may not exist for a stop when loading an initial blank page or
3145  // if an iframe injected by script into a blank page finishes loading.
3146  if (entry) {
3147    base::TimeDelta elapsed = base::TimeTicks::Now() - current_load_start_;
3148
3149    details.reset(new LoadNotificationDetails(
3150        entry->GetVirtualURL(),
3151        entry->GetTransitionType(),
3152        elapsed,
3153        &controller_,
3154        controller_.GetCurrentEntryIndex()));
3155  }
3156
3157  SetIsLoading(false, details.get());
3158
3159  // Notify observers about navigation.
3160  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3161                    DidStopLoading(render_view_host));
3162}
3163
3164void WebContentsImpl::DidCancelLoading() {
3165  controller_.DiscardNonCommittedEntries();
3166
3167  // Update the URL display.
3168  NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
3169}
3170
3171void WebContentsImpl::DidChangeLoadProgress(double progress) {
3172#if defined(OS_ANDROID)
3173  if (delegate_)
3174    delegate_->LoadProgressChanged(this, progress);
3175#endif
3176}
3177
3178void WebContentsImpl::DidDisownOpener(RenderViewHost* rvh) {
3179  if (opener_) {
3180    // Clear our opener so that future cross-process navigations don't have an
3181    // opener assigned.
3182    RemoveDestructionObserver(opener_);
3183    opener_ = NULL;
3184  }
3185
3186  // Notify all swapped out RenderViewHosts for this tab.  This is important
3187  // in case we go back to them, or if another window in those processes tries
3188  // to access window.opener.
3189  render_manager_.DidDisownOpener(rvh);
3190}
3191
3192void WebContentsImpl::DidAccessInitialDocument() {
3193  // Update the URL display.
3194  NotifyNavigationStateChanged(content::INVALIDATE_TYPE_URL);
3195}
3196
3197void WebContentsImpl::DocumentAvailableInMainFrame(
3198    RenderViewHost* render_view_host) {
3199  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3200                    DocumentAvailableInMainFrame());
3201}
3202
3203void WebContentsImpl::DocumentOnLoadCompletedInMainFrame(
3204    RenderViewHost* render_view_host,
3205    int32 page_id) {
3206  NotificationService::current()->Notify(
3207      NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
3208      Source<WebContents>(this),
3209      Details<int>(&page_id));
3210}
3211
3212void WebContentsImpl::RequestOpenURL(RenderViewHost* rvh,
3213                                     const GURL& url,
3214                                     const Referrer& referrer,
3215                                     WindowOpenDisposition disposition,
3216                                     int64 source_frame_id,
3217                                     bool should_replace_current_entry,
3218                                     bool user_gesture) {
3219  // If this came from a swapped out RenderViewHost, we only allow the request
3220  // if we are still in the same BrowsingInstance.
3221  if (static_cast<RenderViewHostImpl*>(rvh)->is_swapped_out() &&
3222      !rvh->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance())) {
3223    return;
3224  }
3225
3226  // Delegate to RequestTransferURL because this is just the generic
3227  // case where |old_request_id| is empty.
3228  RequestTransferURL(url, referrer, disposition, source_frame_id,
3229                     GlobalRequestID(),
3230                     should_replace_current_entry, user_gesture);
3231}
3232
3233void WebContentsImpl::RequestTransferURL(
3234    const GURL& url,
3235    const Referrer& referrer,
3236    WindowOpenDisposition disposition,
3237    int64 source_frame_id,
3238    const GlobalRequestID& old_request_id,
3239    bool should_replace_current_entry,
3240    bool user_gesture) {
3241  WebContents* new_contents = NULL;
3242  PageTransition transition_type = PAGE_TRANSITION_LINK;
3243  if (render_manager_.web_ui()) {
3244    // When we're a Web UI, it will provide a page transition type for us (this
3245    // is so the new tab page can specify AUTO_BOOKMARK for automatically
3246    // generated suggestions).
3247    //
3248    // Note also that we hide the referrer for Web UI pages. We don't really
3249    // want web sites to see a referrer of "chrome://blah" (and some
3250    // chrome: URLs might have search terms or other stuff we don't want to
3251    // send to the site), so we send no referrer.
3252    OpenURLParams params(url, Referrer(), source_frame_id, disposition,
3253        render_manager_.web_ui()->GetLinkTransitionType(),
3254        false /* is_renderer_initiated */);
3255    params.transferred_global_request_id = old_request_id;
3256    new_contents = OpenURL(params);
3257    transition_type = render_manager_.web_ui()->GetLinkTransitionType();
3258  } else {
3259    OpenURLParams params(url, referrer, source_frame_id, disposition,
3260        PAGE_TRANSITION_LINK, true /* is_renderer_initiated */);
3261    params.transferred_global_request_id = old_request_id;
3262    params.should_replace_current_entry = should_replace_current_entry;
3263    params.user_gesture = user_gesture;
3264    new_contents = OpenURL(params);
3265  }
3266  if (new_contents) {
3267    // Notify observers.
3268    FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3269                      DidOpenRequestedURL(new_contents,
3270                                          url,
3271                                          referrer,
3272                                          disposition,
3273                                          transition_type,
3274                                          source_frame_id));
3275  }
3276}
3277
3278void WebContentsImpl::RouteCloseEvent(RenderViewHost* rvh) {
3279  // Tell the active RenderViewHost to run unload handlers and close, as long
3280  // as the request came from a RenderViewHost in the same BrowsingInstance.
3281  // In most cases, we receive this from a swapped out RenderViewHost.
3282  // It is possible to receive it from one that has just been swapped in,
3283  // in which case we might as well deliver the message anyway.
3284  if (rvh->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()))
3285    GetRenderViewHost()->ClosePage();
3286}
3287
3288void WebContentsImpl::RouteMessageEvent(
3289    RenderViewHost* rvh,
3290    const ViewMsg_PostMessage_Params& params) {
3291  // Only deliver the message to the active RenderViewHost if the request
3292  // came from a RenderViewHost in the same BrowsingInstance or if this
3293  // WebContents is dedicated to a browser plugin guest.
3294  // Note: This check means that an embedder could theoretically receive a
3295  // postMessage from anyone (not just its own guests). However, this is
3296  // probably not a risk for apps since other pages won't have references
3297  // to App windows.
3298  if (!rvh->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()) &&
3299      !GetBrowserPluginGuest() && !GetBrowserPluginEmbedder())
3300    return;
3301
3302  ViewMsg_PostMessage_Params new_params(params);
3303
3304  // If there is a source_routing_id, translate it to the routing ID for
3305  // the equivalent swapped out RVH in the target process.  If we need
3306  // to create a swapped out RVH for the source tab, we create its opener
3307  // chain as well, since those will also be accessible to the target page.
3308  if (new_params.source_routing_id != MSG_ROUTING_NONE) {
3309    // Try to look up the WebContents for the source page.
3310    WebContentsImpl* source_contents = NULL;
3311    RenderViewHostImpl* source_rvh = RenderViewHostImpl::FromID(
3312        rvh->GetProcess()->GetID(), params.source_routing_id);
3313    if (source_rvh) {
3314      source_contents = static_cast<WebContentsImpl*>(
3315          source_rvh->GetDelegate()->GetAsWebContents());
3316    }
3317
3318    if (source_contents) {
3319      if (GetBrowserPluginGuest()) {
3320        // We create a swapped out RenderView for the embedder in the guest's
3321        // render process but we intentionally do not expose the embedder's
3322        // opener chain to it.
3323        new_params.source_routing_id =
3324            source_contents->CreateSwappedOutRenderView(GetSiteInstance());
3325      } else {
3326        new_params.source_routing_id =
3327            source_contents->CreateOpenerRenderViews(GetSiteInstance());
3328      }
3329    } else {
3330      // We couldn't find it, so don't pass a source frame.
3331      new_params.source_routing_id = MSG_ROUTING_NONE;
3332    }
3333  }
3334
3335  // In most cases, we receive this from a swapped out RenderViewHost.
3336  // It is possible to receive it from one that has just been swapped in,
3337  // in which case we might as well deliver the message anyway.
3338  Send(new ViewMsg_PostMessageEvent(GetRoutingID(), new_params));
3339}
3340
3341void WebContentsImpl::RunJavaScriptMessage(
3342    RenderViewHost* rvh,
3343    const string16& message,
3344    const string16& default_prompt,
3345    const GURL& frame_url,
3346    JavaScriptMessageType javascript_message_type,
3347    IPC::Message* reply_msg,
3348    bool* did_suppress_message) {
3349  // Suppress JavaScript dialogs when requested. Also suppress messages when
3350  // showing an interstitial as it's shown over the previous page and we don't
3351  // want the hidden page's dialogs to interfere with the interstitial.
3352  bool suppress_this_message =
3353      static_cast<RenderViewHostImpl*>(rvh)->is_swapped_out() ||
3354      ShowingInterstitialPage() ||
3355      !delegate_ ||
3356      delegate_->ShouldSuppressDialogs() ||
3357      !delegate_->GetJavaScriptDialogManager();
3358
3359  if (!suppress_this_message) {
3360    std::string accept_lang = GetContentClient()->browser()->
3361      GetAcceptLangs(GetBrowserContext());
3362    dialog_manager_ = delegate_->GetJavaScriptDialogManager();
3363    dialog_manager_->RunJavaScriptDialog(
3364        this,
3365        frame_url.GetOrigin(),
3366        accept_lang,
3367        javascript_message_type,
3368        message,
3369        default_prompt,
3370        base::Bind(&WebContentsImpl::OnDialogClosed,
3371                   base::Unretained(this),
3372                   rvh,
3373                   reply_msg),
3374        &suppress_this_message);
3375  }
3376
3377  if (suppress_this_message) {
3378    // If we are suppressing messages, just reply as if the user immediately
3379    // pressed "Cancel".
3380    OnDialogClosed(rvh, reply_msg, false, string16());
3381  }
3382
3383  *did_suppress_message = suppress_this_message;
3384}
3385
3386void WebContentsImpl::RunBeforeUnloadConfirm(RenderViewHost* rvh,
3387                                             const string16& message,
3388                                             bool is_reload,
3389                                             IPC::Message* reply_msg) {
3390  RenderViewHostImpl* rvhi = static_cast<RenderViewHostImpl*>(rvh);
3391  if (delegate_)
3392    delegate_->WillRunBeforeUnloadConfirm();
3393
3394  bool suppress_this_message =
3395      rvhi->is_swapped_out() ||
3396      !delegate_ ||
3397      delegate_->ShouldSuppressDialogs() ||
3398      !delegate_->GetJavaScriptDialogManager();
3399  if (suppress_this_message) {
3400    // The reply must be sent to the RVH that sent the request.
3401    rvhi->JavaScriptDialogClosed(reply_msg, true, string16());
3402    return;
3403  }
3404
3405  is_showing_before_unload_dialog_ = true;
3406  dialog_manager_ = delegate_->GetJavaScriptDialogManager();
3407  dialog_manager_->RunBeforeUnloadDialog(
3408      this, message, is_reload,
3409      base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this), rvh,
3410                 reply_msg));
3411}
3412
3413bool WebContentsImpl::AddMessageToConsole(int32 level,
3414                                          const string16& message,
3415                                          int32 line_no,
3416                                          const string16& source_id) {
3417  if (!delegate_)
3418    return false;
3419  return delegate_->AddMessageToConsole(this, level, message, line_no,
3420                                        source_id);
3421}
3422
3423WebPreferences WebContentsImpl::GetWebkitPrefs() {
3424  // We want to base the page config off of the real URL, rather than the
3425  // display URL.
3426  GURL url = controller_.GetActiveEntry()
3427      ? controller_.GetActiveEntry()->GetURL() : GURL::EmptyGURL();
3428  return GetWebkitPrefs(GetRenderViewHost(), url);
3429}
3430
3431int WebContentsImpl::CreateSwappedOutRenderView(
3432    SiteInstance* instance) {
3433  return render_manager_.CreateRenderView(instance, MSG_ROUTING_NONE, true);
3434}
3435
3436void WebContentsImpl::OnUserGesture() {
3437  // Notify observers.
3438  FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidGetUserGesture());
3439
3440  ResourceDispatcherHostImpl* rdh = ResourceDispatcherHostImpl::Get();
3441  if (rdh)  // NULL in unittests.
3442    rdh->OnUserGesture(this);
3443}
3444
3445void WebContentsImpl::OnIgnoredUIEvent() {
3446  // Notify observers.
3447  FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidGetIgnoredUIEvent());
3448}
3449
3450void WebContentsImpl::RendererUnresponsive(RenderViewHost* rvh,
3451                                           bool is_during_unload) {
3452  // Don't show hung renderer dialog for a swapped out RVH.
3453  if (rvh != GetRenderViewHost())
3454    return;
3455
3456  RenderViewHostImpl* rvhi = static_cast<RenderViewHostImpl*>(rvh);
3457
3458  // Ignore renderer unresponsive event if debugger is attached to the tab
3459  // since the event may be a result of the renderer sitting on a breakpoint.
3460  // See http://crbug.com/65458
3461  if (DevToolsAgentHost::IsDebuggerAttached(this))
3462    return;
3463
3464  if (is_during_unload) {
3465    // Hang occurred while firing the beforeunload/unload handler.
3466    // Pretend the handler fired so tab closing continues as if it had.
3467    rvhi->set_sudden_termination_allowed(true);
3468
3469    if (!render_manager_.ShouldCloseTabOnUnresponsiveRenderer())
3470      return;
3471
3472    // If the tab hangs in the beforeunload/unload handler there's really
3473    // nothing we can do to recover. Pretend the unload listeners have
3474    // all fired and close the tab. If the hang is in the beforeunload handler
3475    // then the user will not have the option of cancelling the close.
3476    Close(rvh);
3477    return;
3478  }
3479
3480  if (!GetRenderViewHostImpl() || !GetRenderViewHostImpl()->IsRenderViewLive())
3481    return;
3482
3483  if (delegate_)
3484    delegate_->RendererUnresponsive(this);
3485}
3486
3487void WebContentsImpl::RendererResponsive(RenderViewHost* render_view_host) {
3488  if (delegate_)
3489    delegate_->RendererResponsive(this);
3490}
3491
3492void WebContentsImpl::LoadStateChanged(
3493    const GURL& url,
3494    const net::LoadStateWithParam& load_state,
3495    uint64 upload_position,
3496    uint64 upload_size) {
3497  load_state_ = load_state;
3498  upload_position_ = upload_position;
3499  upload_size_ = upload_size;
3500  load_state_host_ = net::IDNToUnicode(url.host(),
3501      GetContentClient()->browser()->GetAcceptLangs(
3502          GetBrowserContext()));
3503  if (load_state_.state == net::LOAD_STATE_READING_RESPONSE)
3504    SetNotWaitingForResponse();
3505  if (IsLoading()) {
3506    NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD | INVALIDATE_TYPE_TAB);
3507  }
3508}
3509
3510void WebContentsImpl::WorkerCrashed() {
3511  if (delegate_)
3512    delegate_->WorkerCrashed(this);
3513}
3514
3515void WebContentsImpl::BeforeUnloadFiredFromRenderManager(
3516    bool proceed, const base::TimeTicks& proceed_time,
3517    bool* proceed_to_fire_unload) {
3518  FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3519                    BeforeUnloadFired(proceed_time));
3520  if (delegate_)
3521    delegate_->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
3522  // Note: |this| might be deleted at this point.
3523}
3524
3525void WebContentsImpl::RenderProcessGoneFromRenderManager(
3526    RenderViewHost* render_view_host) {
3527  DCHECK(crashed_status_ != base::TERMINATION_STATUS_STILL_RUNNING);
3528  RenderViewTerminated(render_view_host, crashed_status_, crashed_error_code_);
3529}
3530
3531void WebContentsImpl::UpdateRenderViewSizeForRenderManager() {
3532  // TODO(brettw) this is a hack. See WebContentsView::SizeContents.
3533  gfx::Size size = view_->GetContainerSize();
3534  // 0x0 isn't a valid window size (minimal window size is 1x1) but it may be
3535  // here during container initialization and normal window size will be set
3536  // later. In case of tab duplication this resizing to 0x0 prevents setting
3537  // normal size later so just ignore it.
3538  if (!size.IsEmpty())
3539    view_->SizeContents(size);
3540}
3541
3542void WebContentsImpl::NotifySwappedFromRenderManager(RenderViewHost* rvh) {
3543  NotifySwapped(rvh);
3544
3545  // Make sure the visible RVH reflects the new delegate's preferences.
3546  if (delegate_)
3547    view_->SetOverscrollControllerEnabled(delegate_->CanOverscrollContent());
3548
3549  view_->RenderViewSwappedIn(render_manager_.current_host());
3550
3551  FrameTreeNode* root = NULL;
3552  RenderViewHostImpl* new_rvh = static_cast<RenderViewHostImpl*>(
3553      render_manager_.current_host());
3554
3555  // We are doing a cross-site navigation and swapping processes. Since frame
3556  // ids are unique to a process, we need to recreate the frame tree with the
3557  // proper main frame id.
3558  // Note that it is possible for this method to be called before the new RVH
3559  // has committed a navigation (if RenderViewHostManager short-circuits the
3560  // CommitPending call because the current RVH is dead). In that case, we
3561  // haven't heard a valid frame id to use to initialize the root node, so clear
3562  // out the root node and the first subsequent navigation message will set it
3563  // correctly.
3564  if (new_rvh->main_frame_id() != -1)
3565    root = new FrameTreeNode(new_rvh->main_frame_id(), std::string());
3566
3567  frame_tree_root_.reset(root);
3568}
3569
3570int WebContentsImpl::CreateOpenerRenderViewsForRenderManager(
3571    SiteInstance* instance) {
3572  if (!opener_)
3573    return MSG_ROUTING_NONE;
3574
3575  // Recursively create RenderViews for anything else in the opener chain.
3576  return opener_->CreateOpenerRenderViews(instance);
3577}
3578
3579int WebContentsImpl::CreateOpenerRenderViews(SiteInstance* instance) {
3580  int opener_route_id = MSG_ROUTING_NONE;
3581
3582  // If this tab has an opener, ensure it has a RenderView in the given
3583  // SiteInstance as well.
3584  if (opener_)
3585    opener_route_id = opener_->CreateOpenerRenderViews(instance);
3586
3587  // If any of the renderers (current, pending, or swapped out) for this
3588  // WebContents has the same SiteInstance, use it.
3589  if (render_manager_.current_host()->GetSiteInstance() == instance)
3590    return render_manager_.current_host()->GetRoutingID();
3591
3592  if (render_manager_.pending_render_view_host() &&
3593      render_manager_.pending_render_view_host()->GetSiteInstance() == instance)
3594    return render_manager_.pending_render_view_host()->GetRoutingID();
3595
3596  RenderViewHostImpl* rvh = render_manager_.GetSwappedOutRenderViewHost(
3597      instance);
3598  if (rvh)
3599    return rvh->GetRoutingID();
3600
3601  // Create a swapped out RenderView in the given SiteInstance if none exists,
3602  // setting its opener to the given route_id.  Return the new view's route_id.
3603  return render_manager_.CreateRenderView(instance, opener_route_id, true);
3604}
3605
3606NavigationControllerImpl& WebContentsImpl::GetControllerForRenderManager() {
3607  return GetController();
3608}
3609
3610WebUIImpl* WebContentsImpl::CreateWebUIForRenderManager(const GURL& url) {
3611  return static_cast<WebUIImpl*>(CreateWebUI(url));
3612}
3613
3614NavigationEntry*
3615    WebContentsImpl::GetLastCommittedNavigationEntryForRenderManager() {
3616  return controller_.GetLastCommittedEntry();
3617}
3618
3619bool WebContentsImpl::CreateRenderViewForRenderManager(
3620    RenderViewHost* render_view_host, int opener_route_id) {
3621  TRACE_EVENT0("browser", "WebContentsImpl::CreateRenderViewForRenderManager");
3622  // Can be NULL during tests.
3623  RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(render_view_host);
3624
3625  // Now that the RenderView has been created, we need to tell it its size.
3626  if (rwh_view)
3627    rwh_view->SetSize(view_->GetContainerSize());
3628
3629  // Make sure we use the correct starting page_id in the new RenderView.
3630  UpdateMaxPageIDIfNecessary(render_view_host);
3631  int32 max_page_id =
3632      GetMaxPageIDForSiteInstance(render_view_host->GetSiteInstance());
3633
3634  if (!static_cast<RenderViewHostImpl*>(
3635          render_view_host)->CreateRenderView(string16(),
3636                                              opener_route_id,
3637                                              max_page_id)) {
3638    return false;
3639  }
3640
3641#if defined(OS_LINUX) || defined(OS_OPENBSD)
3642  // Force a ViewMsg_Resize to be sent, needed to make plugins show up on
3643  // linux. See crbug.com/83941.
3644  if (rwh_view) {
3645    if (RenderWidgetHost* render_widget_host = rwh_view->GetRenderWidgetHost())
3646      render_widget_host->WasResized();
3647  }
3648#endif
3649
3650  return true;
3651}
3652
3653void WebContentsImpl::OnDialogClosed(RenderViewHost* rvh,
3654                                     IPC::Message* reply_msg,
3655                                     bool success,
3656                                     const string16& user_input) {
3657  if (is_showing_before_unload_dialog_ && !success) {
3658    // If a beforeunload dialog is canceled, we need to stop the throbber from
3659    // spinning, since we forced it to start spinning in Navigate.
3660    DidStopLoading(rvh);
3661    controller_.DiscardNonCommittedEntries();
3662
3663    FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3664                      BeforeUnloadDialogCancelled());
3665  }
3666  is_showing_before_unload_dialog_ = false;
3667  static_cast<RenderViewHostImpl*>(
3668      rvh)->JavaScriptDialogClosed(reply_msg, success, user_input);
3669}
3670
3671void WebContentsImpl::SetEncoding(const std::string& encoding) {
3672  encoding_ = GetContentClient()->browser()->
3673      GetCanonicalEncodingNameByAliasName(encoding);
3674}
3675
3676void WebContentsImpl::CreateViewAndSetSizeForRVH(RenderViewHost* rvh) {
3677  RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(rvh);
3678  // Can be NULL during tests.
3679  if (rwh_view)
3680    rwh_view->SetSize(GetView()->GetContainerSize());
3681}
3682
3683RenderViewHostImpl* WebContentsImpl::GetRenderViewHostImpl() {
3684  return static_cast<RenderViewHostImpl*>(GetRenderViewHost());
3685}
3686
3687BrowserPluginGuest* WebContentsImpl::GetBrowserPluginGuest() const {
3688  return browser_plugin_guest_.get();
3689}
3690
3691void WebContentsImpl::SetBrowserPluginGuest(BrowserPluginGuest* guest) {
3692  CHECK(!browser_plugin_guest_);
3693  browser_plugin_guest_.reset(guest);
3694}
3695
3696BrowserPluginEmbedder* WebContentsImpl::GetBrowserPluginEmbedder() const {
3697  return browser_plugin_embedder_.get();
3698}
3699
3700BrowserPluginGuestManager*
3701    WebContentsImpl::GetBrowserPluginGuestManager() const {
3702  return static_cast<BrowserPluginGuestManager*>(
3703      GetBrowserContext()->GetUserData(
3704          browser_plugin::kBrowserPluginGuestManagerKeyName));
3705}
3706
3707void WebContentsImpl::ClearPowerSaveBlockers(
3708    RenderViewHost* render_view_host) {
3709  STLDeleteValues(&power_save_blockers_[render_view_host]);
3710  power_save_blockers_.erase(render_view_host);
3711}
3712
3713void WebContentsImpl::ClearAllPowerSaveBlockers() {
3714  for (PowerSaveBlockerMap::iterator i(power_save_blockers_.begin());
3715       i != power_save_blockers_.end(); ++i)
3716    STLDeleteValues(&power_save_blockers_[i->first]);
3717  power_save_blockers_.clear();
3718}
3719
3720}  // namespace content
3721