interstitial_page_impl.cc revision 6e8cce623b6e4fe0c9e4af605d675dd9d0338c38
1// Copyright 2013 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/frame_host/interstitial_page_impl.h"
6
7#include <vector>
8
9#include "base/bind.h"
10#include "base/compiler_specific.h"
11#include "base/message_loop/message_loop.h"
12#include "base/strings/string_util.h"
13#include "base/strings/utf_string_conversions.h"
14#include "base/threading/thread.h"
15#include "content/browser/dom_storage/dom_storage_context_wrapper.h"
16#include "content/browser/dom_storage/session_storage_namespace_impl.h"
17#include "content/browser/frame_host/interstitial_page_navigator_impl.h"
18#include "content/browser/frame_host/navigation_controller_impl.h"
19#include "content/browser/frame_host/navigation_entry_impl.h"
20#include "content/browser/loader/resource_dispatcher_host_impl.h"
21#include "content/browser/renderer_host/render_process_host_impl.h"
22#include "content/browser/renderer_host/render_view_host_delegate_view.h"
23#include "content/browser/renderer_host/render_view_host_factory.h"
24#include "content/browser/renderer_host/render_view_host_impl.h"
25#include "content/browser/renderer_host/render_widget_host_view_base.h"
26#include "content/browser/site_instance_impl.h"
27#include "content/browser/web_contents/web_contents_impl.h"
28#include "content/browser/web_contents/web_contents_view.h"
29#include "content/common/frame_messages.h"
30#include "content/common/view_messages.h"
31#include "content/public/browser/browser_context.h"
32#include "content/public/browser/browser_thread.h"
33#include "content/public/browser/content_browser_client.h"
34#include "content/public/browser/dom_operation_notification_details.h"
35#include "content/public/browser/interstitial_page_delegate.h"
36#include "content/public/browser/invalidate_type.h"
37#include "content/public/browser/notification_service.h"
38#include "content/public/browser/notification_source.h"
39#include "content/public/browser/storage_partition.h"
40#include "content/public/browser/user_metrics.h"
41#include "content/public/browser/web_contents_delegate.h"
42#include "content/public/common/bindings_policy.h"
43#include "content/public/common/page_transition_types.h"
44#include "net/base/escape.h"
45#include "net/url_request/url_request_context_getter.h"
46
47using blink::WebDragOperation;
48using blink::WebDragOperationsMask;
49
50namespace content {
51namespace {
52
53void ResourceRequestHelper(ResourceDispatcherHostImpl* rdh,
54                           int process_id,
55                           int render_view_host_id,
56                           ResourceRequestAction action) {
57  switch (action) {
58    case BLOCK:
59      rdh->BlockRequestsForRoute(process_id, render_view_host_id);
60      break;
61    case RESUME:
62      rdh->ResumeBlockedRequestsForRoute(process_id, render_view_host_id);
63      break;
64    case CANCEL:
65      rdh->CancelBlockedRequestsForRoute(process_id, render_view_host_id);
66      break;
67    default:
68      NOTREACHED();
69  }
70}
71
72}  // namespace
73
74class InterstitialPageImpl::InterstitialPageRVHDelegateView
75  : public RenderViewHostDelegateView {
76 public:
77  explicit InterstitialPageRVHDelegateView(InterstitialPageImpl* page);
78
79  // RenderViewHostDelegateView implementation:
80#if defined(OS_MACOSX) || defined(OS_ANDROID)
81  virtual void ShowPopupMenu(const gfx::Rect& bounds,
82                             int item_height,
83                             double item_font_size,
84                             int selected_item,
85                             const std::vector<MenuItem>& items,
86                             bool right_aligned,
87                             bool allow_multiple_selection) OVERRIDE;
88  virtual void HidePopupMenu() OVERRIDE;
89#endif
90  virtual void StartDragging(const DropData& drop_data,
91                             WebDragOperationsMask operations_allowed,
92                             const gfx::ImageSkia& image,
93                             const gfx::Vector2d& image_offset,
94                             const DragEventSourceInfo& event_info) OVERRIDE;
95  virtual void UpdateDragCursor(WebDragOperation operation) OVERRIDE;
96  virtual void GotFocus() OVERRIDE;
97  virtual void TakeFocus(bool reverse) OVERRIDE;
98  virtual void OnFindReply(int request_id,
99                           int number_of_matches,
100                           const gfx::Rect& selection_rect,
101                           int active_match_ordinal,
102                           bool final_update);
103
104 private:
105  InterstitialPageImpl* interstitial_page_;
106
107  DISALLOW_COPY_AND_ASSIGN(InterstitialPageRVHDelegateView);
108};
109
110
111// We keep a map of the various blocking pages shown as the UI tests need to
112// be able to retrieve them.
113typedef std::map<WebContents*, InterstitialPageImpl*> InterstitialPageMap;
114static InterstitialPageMap* g_web_contents_to_interstitial_page;
115
116// Initializes g_web_contents_to_interstitial_page in a thread-safe manner.
117// Should be called before accessing g_web_contents_to_interstitial_page.
118static void InitInterstitialPageMap() {
119  if (!g_web_contents_to_interstitial_page)
120    g_web_contents_to_interstitial_page = new InterstitialPageMap;
121}
122
123InterstitialPage* InterstitialPage::Create(WebContents* web_contents,
124                                           bool new_navigation,
125                                           const GURL& url,
126                                           InterstitialPageDelegate* delegate) {
127  return new InterstitialPageImpl(
128      web_contents,
129      static_cast<RenderWidgetHostDelegate*>(
130          static_cast<WebContentsImpl*>(web_contents)),
131      new_navigation, url, delegate);
132}
133
134InterstitialPage* InterstitialPage::GetInterstitialPage(
135    WebContents* web_contents) {
136  InitInterstitialPageMap();
137  InterstitialPageMap::const_iterator iter =
138      g_web_contents_to_interstitial_page->find(web_contents);
139  if (iter == g_web_contents_to_interstitial_page->end())
140    return NULL;
141
142  return iter->second;
143}
144
145InterstitialPageImpl::InterstitialPageImpl(
146    WebContents* web_contents,
147    RenderWidgetHostDelegate* render_widget_host_delegate,
148    bool new_navigation,
149    const GURL& url,
150    InterstitialPageDelegate* delegate)
151    : WebContentsObserver(web_contents),
152      web_contents_(web_contents),
153      controller_(static_cast<NavigationControllerImpl*>(
154          &web_contents->GetController())),
155      render_widget_host_delegate_(render_widget_host_delegate),
156      url_(url),
157      new_navigation_(new_navigation),
158      should_discard_pending_nav_entry_(new_navigation),
159      reload_on_dont_proceed_(false),
160      enabled_(true),
161      action_taken_(NO_ACTION),
162      render_view_host_(NULL),
163      // TODO(nasko): The InterstitialPageImpl will need to provide its own
164      // NavigationControllerImpl to the Navigator, which is separate from
165      // the WebContents one, so we can enforce no navigation policy here.
166      // While we get the code to a point to do this, pass NULL for it.
167      // TODO(creis): We will also need to pass delegates for the RVHM as we
168      // start to use it.
169      frame_tree_(new InterstitialPageNavigatorImpl(this, controller_),
170                  this, this, this,
171                  static_cast<WebContentsImpl*>(web_contents)),
172      original_child_id_(web_contents->GetRenderProcessHost()->GetID()),
173      original_rvh_id_(web_contents->GetRenderViewHost()->GetRoutingID()),
174      should_revert_web_contents_title_(false),
175      web_contents_was_loading_(false),
176      resource_dispatcher_host_notified_(false),
177      rvh_delegate_view_(new InterstitialPageRVHDelegateView(this)),
178      create_view_(true),
179      delegate_(delegate),
180      weak_ptr_factory_(this) {
181  InitInterstitialPageMap();
182  // It would be inconsistent to create an interstitial with no new navigation
183  // (which is the case when the interstitial was triggered by a sub-resource on
184  // a page) when we have a pending entry (in the process of loading a new top
185  // frame).
186  DCHECK(new_navigation || !web_contents->GetController().GetPendingEntry());
187}
188
189InterstitialPageImpl::~InterstitialPageImpl() {
190}
191
192void InterstitialPageImpl::Show() {
193  if (!enabled())
194    return;
195
196  // If an interstitial is already showing or about to be shown, close it before
197  // showing the new one.
198  // Be careful not to take an action on the old interstitial more than once.
199  InterstitialPageMap::const_iterator iter =
200      g_web_contents_to_interstitial_page->find(web_contents_);
201  if (iter != g_web_contents_to_interstitial_page->end()) {
202    InterstitialPageImpl* interstitial = iter->second;
203    if (interstitial->action_taken_ != NO_ACTION) {
204      interstitial->Hide();
205    } else {
206      // If we are currently showing an interstitial page for which we created
207      // a transient entry and a new interstitial is shown as the result of a
208      // new browser initiated navigation, then that transient entry has already
209      // been discarded and a new pending navigation entry created.
210      // So we should not discard that new pending navigation entry.
211      // See http://crbug.com/9791
212      if (new_navigation_ && interstitial->new_navigation_)
213        interstitial->should_discard_pending_nav_entry_= false;
214      interstitial->DontProceed();
215    }
216  }
217
218  // Block the resource requests for the render view host while it is hidden.
219  TakeActionOnResourceDispatcher(BLOCK);
220  // We need to be notified when the RenderViewHost is destroyed so we can
221  // cancel the blocked requests.  We cannot do that on
222  // NOTIFY_WEB_CONTENTS_DESTROYED as at that point the RenderViewHost has
223  // already been destroyed.
224  notification_registrar_.Add(
225      this, NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
226      Source<RenderWidgetHost>(controller_->delegate()->GetRenderViewHost()));
227
228  // Update the g_web_contents_to_interstitial_page map.
229  iter = g_web_contents_to_interstitial_page->find(web_contents_);
230  DCHECK(iter == g_web_contents_to_interstitial_page->end());
231  (*g_web_contents_to_interstitial_page)[web_contents_] = this;
232
233  if (new_navigation_) {
234    NavigationEntryImpl* entry = new NavigationEntryImpl;
235    entry->SetURL(url_);
236    entry->SetVirtualURL(url_);
237    entry->set_page_type(PAGE_TYPE_INTERSTITIAL);
238
239    // Give delegates a chance to set some states on the navigation entry.
240    delegate_->OverrideEntry(entry);
241
242    controller_->SetTransientEntry(entry);
243  }
244
245  DCHECK(!render_view_host_);
246  render_view_host_ = static_cast<RenderViewHostImpl*>(CreateRenderViewHost());
247  render_view_host_->AttachToFrameTree();
248  CreateWebContentsView();
249
250  std::string data_url = "data:text/html;charset=utf-8," +
251                         net::EscapePath(delegate_->GetHTMLContents());
252  render_view_host_->NavigateToURL(GURL(data_url));
253
254  notification_registrar_.Add(this, NOTIFICATION_NAV_ENTRY_PENDING,
255      Source<NavigationController>(controller_));
256}
257
258void InterstitialPageImpl::Hide() {
259  // We may have already been hidden, and are just waiting to be deleted.
260  // We can't check for enabled() here, because some callers have already
261  // called Disable.
262  if (!render_view_host_)
263    return;
264
265  Disable();
266
267  RenderWidgetHostView* old_view =
268      controller_->delegate()->GetRenderViewHost()->GetView();
269  if (controller_->delegate()->GetInterstitialPage() == this &&
270      old_view &&
271      !old_view->IsShowing() &&
272      !controller_->delegate()->IsHidden()) {
273    // Show the original RVH since we're going away.  Note it might not exist if
274    // the renderer crashed while the interstitial was showing.
275    // Note that it is important that we don't call Show() if the view is
276    // already showing. That would result in bad things (unparented HWND on
277    // Windows for example) happening.
278    old_view->Show();
279  }
280
281  // If the focus was on the interstitial, let's keep it to the page.
282  // (Note that in unit-tests the RVH may not have a view).
283  if (render_view_host_->GetView() &&
284      render_view_host_->GetView()->HasFocus() &&
285      controller_->delegate()->GetRenderViewHost()->GetView()) {
286    controller_->delegate()->GetRenderViewHost()->GetView()->Focus();
287  }
288
289  // Delete this and call Shutdown on the RVH asynchronously, as we may have
290  // been called from a RVH delegate method, and we can't delete the RVH out
291  // from under itself.
292  base::MessageLoop::current()->PostNonNestableTask(
293      FROM_HERE,
294      base::Bind(&InterstitialPageImpl::Shutdown,
295                 weak_ptr_factory_.GetWeakPtr()));
296  render_view_host_ = NULL;
297  frame_tree_.ResetForMainFrameSwap();
298  controller_->delegate()->DetachInterstitialPage();
299  // Let's revert to the original title if necessary.
300  NavigationEntry* entry = controller_->GetVisibleEntry();
301  if (!new_navigation_ && should_revert_web_contents_title_) {
302    entry->SetTitle(original_web_contents_title_);
303    controller_->delegate()->NotifyNavigationStateChanged(
304        INVALIDATE_TYPE_TITLE);
305  }
306
307  InterstitialPageMap::iterator iter =
308      g_web_contents_to_interstitial_page->find(web_contents_);
309  DCHECK(iter != g_web_contents_to_interstitial_page->end());
310  if (iter != g_web_contents_to_interstitial_page->end())
311    g_web_contents_to_interstitial_page->erase(iter);
312
313  // Clear the WebContents pointer, because it may now be deleted.
314  // This signifies that we are in the process of shutting down.
315  web_contents_ = NULL;
316}
317
318void InterstitialPageImpl::Observe(
319    int type,
320    const NotificationSource& source,
321    const NotificationDetails& details) {
322  switch (type) {
323    case NOTIFICATION_NAV_ENTRY_PENDING:
324      // We are navigating away from the interstitial (the user has typed a URL
325      // in the location bar or clicked a bookmark).  Make sure clicking on the
326      // interstitial will have no effect.  Also cancel any blocked requests
327      // on the ResourceDispatcherHost.  Note that when we get this notification
328      // the RenderViewHost has not yet navigated so we'll unblock the
329      // RenderViewHost before the resource request for the new page we are
330      // navigating arrives in the ResourceDispatcherHost.  This ensures that
331      // request won't be blocked if the same RenderViewHost was used for the
332      // new navigation.
333      Disable();
334      TakeActionOnResourceDispatcher(CANCEL);
335      break;
336    case NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED:
337      if (action_taken_ == NO_ACTION) {
338        // The RenderViewHost is being destroyed (as part of the tab being
339        // closed); make sure we clear the blocked requests.
340        RenderViewHost* rvh = static_cast<RenderViewHost*>(
341            static_cast<RenderViewHostImpl*>(
342                RenderWidgetHostImpl::From(
343                    Source<RenderWidgetHost>(source).ptr())));
344        DCHECK(rvh->GetProcess()->GetID() == original_child_id_ &&
345               rvh->GetRoutingID() == original_rvh_id_);
346        TakeActionOnResourceDispatcher(CANCEL);
347      }
348      break;
349    default:
350      NOTREACHED();
351  }
352}
353
354void InterstitialPageImpl::NavigationEntryCommitted(
355    const LoadCommittedDetails& load_details) {
356  OnNavigatingAwayOrTabClosing();
357}
358
359void InterstitialPageImpl::WebContentsDestroyed() {
360  OnNavigatingAwayOrTabClosing();
361}
362
363bool InterstitialPageImpl::OnMessageReceived(
364    const IPC::Message& message,
365    RenderFrameHost* render_frame_host) {
366  return OnMessageReceived(message);
367}
368
369bool InterstitialPageImpl::OnMessageReceived(RenderFrameHost* render_frame_host,
370                                             const IPC::Message& message) {
371  return OnMessageReceived(message);
372}
373
374bool InterstitialPageImpl::OnMessageReceived(RenderViewHost* render_view_host,
375                                             const IPC::Message& message) {
376  return OnMessageReceived(message);
377}
378
379bool InterstitialPageImpl::OnMessageReceived(const IPC::Message& message) {
380
381  bool handled = true;
382  IPC_BEGIN_MESSAGE_MAP(InterstitialPageImpl, message)
383    IPC_MESSAGE_HANDLER(FrameHostMsg_DomOperationResponse,
384                        OnDomOperationResponse)
385    IPC_MESSAGE_UNHANDLED(handled = false)
386  IPC_END_MESSAGE_MAP()
387
388  return handled;
389}
390
391void InterstitialPageImpl::RenderFrameCreated(
392    RenderFrameHost* render_frame_host) {
393  // Note this is only for subframes in the interstitial, the notification for
394  // the main frame happens in RenderViewCreated.
395  controller_->delegate()->RenderFrameForInterstitialPageCreated(
396      render_frame_host);
397}
398
399void InterstitialPageImpl::UpdateTitle(
400    RenderFrameHost* render_frame_host,
401    int32 page_id,
402    const base::string16& title,
403    base::i18n::TextDirection title_direction) {
404  if (!enabled())
405    return;
406
407  RenderViewHost* render_view_host = render_frame_host->GetRenderViewHost();
408  DCHECK(render_view_host == render_view_host_);
409  NavigationEntry* entry = controller_->GetVisibleEntry();
410  if (!entry) {
411    // Crash reports from the field indicate this can be NULL.
412    // This is unexpected as InterstitialPages constructed with the
413    // new_navigation flag set to true create a transient navigation entry
414    // (that is returned as the active entry). And the only case so far of
415    // interstitial created with that flag set to false is with the
416    // SafeBrowsingBlockingPage, when the resource triggering the interstitial
417    // is a sub-resource, meaning the main page has already been loaded and a
418    // navigation entry should have been created.
419    NOTREACHED();
420    return;
421  }
422
423  // If this interstitial is shown on an existing navigation entry, we'll need
424  // to remember its title so we can revert to it when hidden.
425  if (!new_navigation_ && !should_revert_web_contents_title_) {
426    original_web_contents_title_ = entry->GetTitle();
427    should_revert_web_contents_title_ = true;
428  }
429  // TODO(evan): make use of title_direction.
430  // http://code.google.com/p/chromium/issues/detail?id=27094
431  entry->SetTitle(title);
432  controller_->delegate()->NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE);
433}
434
435AccessibilityMode InterstitialPageImpl::GetAccessibilityMode() const {
436  if (web_contents_)
437    return static_cast<WebContentsImpl*>(web_contents_)->GetAccessibilityMode();
438  else
439    return AccessibilityModeOff;
440}
441
442RenderViewHostDelegateView* InterstitialPageImpl::GetDelegateView() {
443  return rvh_delegate_view_.get();
444}
445
446const GURL& InterstitialPageImpl::GetMainFrameLastCommittedURL() const {
447  return url_;
448}
449
450void InterstitialPageImpl::RenderViewTerminated(
451    RenderViewHost* render_view_host,
452    base::TerminationStatus status,
453    int error_code) {
454  // Our renderer died. This should not happen in normal cases.
455  // If we haven't already started shutdown, just dismiss the interstitial.
456  // We cannot check for enabled() here, because we may have called Disable
457  // without calling Hide.
458  if (render_view_host_)
459    DontProceed();
460}
461
462void InterstitialPageImpl::DidNavigate(
463    RenderViewHost* render_view_host,
464    const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
465  // A fast user could have navigated away from the page that triggered the
466  // interstitial while the interstitial was loading, that would have disabled
467  // us. In that case we can dismiss ourselves.
468  if (!enabled()) {
469    DontProceed();
470    return;
471  }
472  if (PageTransitionCoreTypeIs(params.transition,
473                               PAGE_TRANSITION_AUTO_SUBFRAME)) {
474    // No need to handle navigate message from iframe in the interstitial page.
475    return;
476  }
477
478  // The RenderViewHost has loaded its contents, we can show it now.
479  if (!controller_->delegate()->IsHidden())
480    render_view_host_->GetView()->Show();
481  controller_->delegate()->AttachInterstitialPage(this);
482
483  RenderWidgetHostView* rwh_view =
484      controller_->delegate()->GetRenderViewHost()->GetView();
485
486  // The RenderViewHost may already have crashed before we even get here.
487  if (rwh_view) {
488    // If the page has focus, focus the interstitial.
489    if (rwh_view->HasFocus())
490      Focus();
491
492    // Hide the original RVH since we're showing the interstitial instead.
493    rwh_view->Hide();
494  }
495
496  // Notify the tab we are not loading so the throbber is stopped. It also
497  // causes a WebContentsObserver::DidStopLoading callback that the
498  // AutomationProvider (used by the UI tests) expects to consider a navigation
499  // as complete. Without this, navigating in a UI test to a URL that triggers
500  // an interstitial would hang.
501  web_contents_was_loading_ = controller_->delegate()->IsLoading();
502  controller_->delegate()->SetIsLoading(
503      controller_->delegate()->GetRenderViewHost(), false, true, NULL);
504}
505
506RendererPreferences InterstitialPageImpl::GetRendererPrefs(
507    BrowserContext* browser_context) const {
508  delegate_->OverrideRendererPrefs(&renderer_preferences_);
509  return renderer_preferences_;
510}
511
512WebPreferences InterstitialPageImpl::ComputeWebkitPrefs() {
513  if (!enabled())
514    return WebPreferences();
515
516  return render_view_host_->ComputeWebkitPrefs(url_);
517}
518
519void InterstitialPageImpl::RenderWidgetDeleted(
520    RenderWidgetHostImpl* render_widget_host) {
521  // TODO(creis): Remove this method once we verify the shutdown path is sane.
522  CHECK(!web_contents_);
523}
524
525bool InterstitialPageImpl::PreHandleKeyboardEvent(
526    const NativeWebKeyboardEvent& event,
527    bool* is_keyboard_shortcut) {
528  if (!enabled())
529    return false;
530  return render_widget_host_delegate_->PreHandleKeyboardEvent(
531      event, is_keyboard_shortcut);
532}
533
534void InterstitialPageImpl::HandleKeyboardEvent(
535      const NativeWebKeyboardEvent& event) {
536  if (enabled())
537    render_widget_host_delegate_->HandleKeyboardEvent(event);
538}
539
540#if defined(OS_WIN)
541gfx::NativeViewAccessible
542InterstitialPageImpl::GetParentNativeViewAccessible() {
543  if (web_contents_) {
544    WebContentsImpl* wci = static_cast<WebContentsImpl*>(web_contents_);
545    return wci->GetParentNativeViewAccessible();
546  }
547  return NULL;
548}
549#endif
550
551WebContents* InterstitialPageImpl::web_contents() const {
552  return web_contents_;
553}
554
555RenderViewHost* InterstitialPageImpl::CreateRenderViewHost() {
556  if (!enabled())
557    return NULL;
558
559  // Interstitial pages don't want to share the session storage so we mint a
560  // new one.
561  BrowserContext* browser_context = web_contents()->GetBrowserContext();
562  scoped_refptr<SiteInstance> site_instance =
563      SiteInstance::Create(browser_context);
564  DOMStorageContextWrapper* dom_storage_context =
565      static_cast<DOMStorageContextWrapper*>(
566          BrowserContext::GetStoragePartition(
567              browser_context, site_instance.get())->GetDOMStorageContext());
568  session_storage_namespace_ =
569      new SessionStorageNamespaceImpl(dom_storage_context);
570
571  // Use the RenderViewHost from our FrameTree.
572  frame_tree_.root()->render_manager()->Init(
573      browser_context, site_instance.get(), MSG_ROUTING_NONE, MSG_ROUTING_NONE);
574  return frame_tree_.root()->current_frame_host()->render_view_host();
575}
576
577WebContentsView* InterstitialPageImpl::CreateWebContentsView() {
578  if (!enabled() || !create_view_)
579    return NULL;
580  WebContentsView* wcv =
581      static_cast<WebContentsImpl*>(web_contents())->GetView();
582  RenderWidgetHostViewBase* view =
583      wcv->CreateViewForWidget(render_view_host_);
584  render_view_host_->SetView(view);
585  render_view_host_->AllowBindings(BINDINGS_POLICY_DOM_AUTOMATION);
586
587  int32 max_page_id = web_contents()->
588      GetMaxPageIDForSiteInstance(render_view_host_->GetSiteInstance());
589  render_view_host_->CreateRenderView(base::string16(),
590                                      MSG_ROUTING_NONE,
591                                      MSG_ROUTING_NONE,
592                                      max_page_id,
593                                      false);
594  controller_->delegate()->RenderFrameForInterstitialPageCreated(
595      frame_tree_.root()->current_frame_host());
596  view->SetSize(web_contents()->GetContainerBounds().size());
597  // Don't show the interstitial until we have navigated to it.
598  view->Hide();
599  return wcv;
600}
601
602void InterstitialPageImpl::Proceed() {
603  // Don't repeat this if we are already shutting down.  We cannot check for
604  // enabled() here, because we may have called Disable without calling Hide.
605  if (!render_view_host_)
606    return;
607
608  if (action_taken_ != NO_ACTION) {
609    NOTREACHED();
610    return;
611  }
612  Disable();
613  action_taken_ = PROCEED_ACTION;
614
615  // Resumes the throbber, if applicable.
616  if (web_contents_was_loading_)
617    controller_->delegate()->SetIsLoading(
618        controller_->delegate()->GetRenderViewHost(), true, true, NULL);
619
620  // If this is a new navigation, the old page is going away, so we cancel any
621  // blocked requests for it.  If it is not a new navigation, then it means the
622  // interstitial was shown as a result of a resource loading in the page.
623  // Since the user wants to proceed, we'll let any blocked request go through.
624  if (new_navigation_)
625    TakeActionOnResourceDispatcher(CANCEL);
626  else
627    TakeActionOnResourceDispatcher(RESUME);
628
629  // No need to hide if we are a new navigation, we'll get hidden when the
630  // navigation is committed.
631  if (!new_navigation_) {
632    Hide();
633    delegate_->OnProceed();
634    return;
635  }
636
637  delegate_->OnProceed();
638}
639
640void InterstitialPageImpl::DontProceed() {
641  // Don't repeat this if we are already shutting down.  We cannot check for
642  // enabled() here, because we may have called Disable without calling Hide.
643  if (!render_view_host_)
644    return;
645  DCHECK(action_taken_ != DONT_PROCEED_ACTION);
646
647  Disable();
648  action_taken_ = DONT_PROCEED_ACTION;
649
650  // If this is a new navigation, we are returning to the original page, so we
651  // resume blocked requests for it.  If it is not a new navigation, then it
652  // means the interstitial was shown as a result of a resource loading in the
653  // page and we won't return to the original page, so we cancel blocked
654  // requests in that case.
655  if (new_navigation_)
656    TakeActionOnResourceDispatcher(RESUME);
657  else
658    TakeActionOnResourceDispatcher(CANCEL);
659
660  if (should_discard_pending_nav_entry_) {
661    // Since no navigation happens we have to discard the transient entry
662    // explicitely.  Note that by calling DiscardNonCommittedEntries() we also
663    // discard the pending entry, which is what we want, since the navigation is
664    // cancelled.
665    controller_->DiscardNonCommittedEntries();
666  }
667
668  if (reload_on_dont_proceed_)
669    controller_->Reload(true);
670
671  Hide();
672  delegate_->OnDontProceed();
673}
674
675void InterstitialPageImpl::CancelForNavigation() {
676  // The user is trying to navigate away.  We should unblock the renderer and
677  // disable the interstitial, but keep it visible until the navigation
678  // completes.
679  Disable();
680  // If this interstitial was shown for a new navigation, allow any navigations
681  // on the original page to resume (e.g., subresource requests, XHRs, etc).
682  // Otherwise, cancel the pending, possibly dangerous navigations.
683  if (new_navigation_)
684    TakeActionOnResourceDispatcher(RESUME);
685  else
686    TakeActionOnResourceDispatcher(CANCEL);
687}
688
689void InterstitialPageImpl::SetSize(const gfx::Size& size) {
690  if (!enabled())
691    return;
692#if !defined(OS_MACOSX)
693  // When a tab is closed, we might be resized after our view was NULLed
694  // (typically if there was an info-bar).
695  if (render_view_host_->GetView())
696    render_view_host_->GetView()->SetSize(size);
697#else
698  // TODO(port): Does Mac need to SetSize?
699  NOTIMPLEMENTED();
700#endif
701}
702
703void InterstitialPageImpl::Focus() {
704  // Focus the native window.
705  if (!enabled())
706    return;
707  render_view_host_->GetView()->Focus();
708}
709
710void InterstitialPageImpl::FocusThroughTabTraversal(bool reverse) {
711  if (!enabled())
712    return;
713  render_view_host_->SetInitialFocus(reverse);
714}
715
716RenderWidgetHostView* InterstitialPageImpl::GetView() {
717  return render_view_host_->GetView();
718}
719
720RenderViewHost* InterstitialPageImpl::GetRenderViewHostForTesting() const {
721  return render_view_host_;
722}
723
724#if defined(OS_ANDROID)
725RenderViewHost* InterstitialPageImpl::GetRenderViewHost() const {
726  return render_view_host_;
727}
728#endif
729
730InterstitialPageDelegate* InterstitialPageImpl::GetDelegateForTesting() {
731  return delegate_.get();
732}
733
734void InterstitialPageImpl::DontCreateViewForTesting() {
735  create_view_ = false;
736}
737
738gfx::Rect InterstitialPageImpl::GetRootWindowResizerRect() const {
739  return gfx::Rect();
740}
741
742void InterstitialPageImpl::CreateNewWindow(
743    int render_process_id,
744    int route_id,
745    int main_frame_route_id,
746    const ViewHostMsg_CreateWindow_Params& params,
747    SessionStorageNamespace* session_storage_namespace) {
748  NOTREACHED() << "InterstitialPage does not support showing popups yet.";
749}
750
751void InterstitialPageImpl::CreateNewWidget(int render_process_id,
752                                           int route_id,
753                                           blink::WebPopupType popup_type) {
754  NOTREACHED() << "InterstitialPage does not support showing drop-downs yet.";
755}
756
757void InterstitialPageImpl::CreateNewFullscreenWidget(int render_process_id,
758                                                     int route_id) {
759  NOTREACHED()
760      << "InterstitialPage does not support showing full screen popups.";
761}
762
763void InterstitialPageImpl::ShowCreatedWindow(int route_id,
764                                             WindowOpenDisposition disposition,
765                                             const gfx::Rect& initial_pos,
766                                             bool user_gesture) {
767  NOTREACHED() << "InterstitialPage does not support showing popups yet.";
768}
769
770void InterstitialPageImpl::ShowCreatedWidget(int route_id,
771                                             const gfx::Rect& initial_pos) {
772  NOTREACHED() << "InterstitialPage does not support showing drop-downs yet.";
773}
774
775void InterstitialPageImpl::ShowCreatedFullscreenWidget(int route_id) {
776  NOTREACHED()
777      << "InterstitialPage does not support showing full screen popups.";
778}
779
780SessionStorageNamespace* InterstitialPageImpl::GetSessionStorageNamespace(
781    SiteInstance* instance) {
782  return session_storage_namespace_.get();
783}
784
785FrameTree* InterstitialPageImpl::GetFrameTree() {
786  return &frame_tree_;
787}
788
789void InterstitialPageImpl::Disable() {
790  enabled_ = false;
791}
792
793void InterstitialPageImpl::Shutdown() {
794  delete this;
795}
796
797void InterstitialPageImpl::OnNavigatingAwayOrTabClosing() {
798  if (action_taken_ == NO_ACTION) {
799    // We are navigating away from the interstitial or closing a tab with an
800    // interstitial.  Default to DontProceed(). We don't just call Hide as
801    // subclasses will almost certainly override DontProceed to do some work
802    // (ex: close pending connections).
803    DontProceed();
804  } else {
805    // User decided to proceed and either the navigation was committed or
806    // the tab was closed before that.
807    Hide();
808  }
809}
810
811void InterstitialPageImpl::TakeActionOnResourceDispatcher(
812    ResourceRequestAction action) {
813  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)) <<
814      "TakeActionOnResourceDispatcher should be called on the main thread.";
815
816  if (action == CANCEL || action == RESUME) {
817    if (resource_dispatcher_host_notified_)
818      return;
819    resource_dispatcher_host_notified_ = true;
820  }
821
822  // The tab might not have a render_view_host if it was closed (in which case,
823  // we have taken care of the blocked requests when processing
824  // NOTIFY_RENDER_WIDGET_HOST_DESTROYED.
825  // Also we need to test there is a ResourceDispatcherHostImpl, as when unit-
826  // tests we don't have one.
827  RenderViewHostImpl* rvh = RenderViewHostImpl::FromID(original_child_id_,
828                                                       original_rvh_id_);
829  if (!rvh || !ResourceDispatcherHostImpl::Get())
830    return;
831
832  BrowserThread::PostTask(
833      BrowserThread::IO,
834      FROM_HERE,
835      base::Bind(
836          &ResourceRequestHelper,
837          ResourceDispatcherHostImpl::Get(),
838          original_child_id_,
839          original_rvh_id_,
840          action));
841}
842
843void InterstitialPageImpl::OnDomOperationResponse(
844    const std::string& json_string,
845    int automation_id) {
846  // Needed by test code.
847  DomOperationNotificationDetails details(json_string, automation_id);
848  NotificationService::current()->Notify(
849      NOTIFICATION_DOM_OPERATION_RESPONSE,
850      Source<WebContents>(web_contents()),
851      Details<DomOperationNotificationDetails>(&details));
852
853  if (!enabled())
854    return;
855  delegate_->CommandReceived(details.json);
856}
857
858
859InterstitialPageImpl::InterstitialPageRVHDelegateView::
860    InterstitialPageRVHDelegateView(InterstitialPageImpl* page)
861    : interstitial_page_(page) {
862}
863
864#if defined(OS_MACOSX) || defined(OS_ANDROID)
865void InterstitialPageImpl::InterstitialPageRVHDelegateView::ShowPopupMenu(
866    const gfx::Rect& bounds,
867    int item_height,
868    double item_font_size,
869    int selected_item,
870    const std::vector<MenuItem>& items,
871    bool right_aligned,
872    bool allow_multiple_selection) {
873  NOTREACHED() << "InterstitialPage does not support showing popup menus.";
874}
875
876void InterstitialPageImpl::InterstitialPageRVHDelegateView::HidePopupMenu() {
877  NOTREACHED() << "InterstitialPage does not support showing popup menus.";
878}
879#endif
880
881void InterstitialPageImpl::InterstitialPageRVHDelegateView::StartDragging(
882    const DropData& drop_data,
883    WebDragOperationsMask allowed_operations,
884    const gfx::ImageSkia& image,
885    const gfx::Vector2d& image_offset,
886    const DragEventSourceInfo& event_info) {
887  interstitial_page_->render_view_host_->DragSourceSystemDragEnded();
888  DVLOG(1) << "InterstitialPage does not support dragging yet.";
889}
890
891void InterstitialPageImpl::InterstitialPageRVHDelegateView::UpdateDragCursor(
892    WebDragOperation) {
893  NOTREACHED() << "InterstitialPage does not support dragging yet.";
894}
895
896void InterstitialPageImpl::InterstitialPageRVHDelegateView::GotFocus() {
897  WebContents* web_contents = interstitial_page_->web_contents();
898  if (web_contents && web_contents->GetDelegate())
899    web_contents->GetDelegate()->WebContentsFocused(web_contents);
900}
901
902void InterstitialPageImpl::InterstitialPageRVHDelegateView::TakeFocus(
903    bool reverse) {
904  if (!interstitial_page_->web_contents())
905    return;
906  WebContentsImpl* web_contents =
907      static_cast<WebContentsImpl*>(interstitial_page_->web_contents());
908  if (!web_contents->GetDelegateView())
909    return;
910
911  web_contents->GetDelegateView()->TakeFocus(reverse);
912}
913
914void InterstitialPageImpl::InterstitialPageRVHDelegateView::OnFindReply(
915    int request_id, int number_of_matches, const gfx::Rect& selection_rect,
916    int active_match_ordinal, bool final_update) {
917}
918
919}  // namespace content
920