render_frame_host_manager.h revision 5c02ac1a9c1b504631c0a3d2b6e737b5d738bae1
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#ifndef CONTENT_BROWSER_FRAME_HOST_RENDER_FRAME_HOST_MANAGER_H_
6#define CONTENT_BROWSER_FRAME_HOST_RENDER_FRAME_HOST_MANAGER_H_
7
8#include "base/basictypes.h"
9#include "base/logging.h"
10#include "base/memory/scoped_ptr.h"
11#include "base/memory/weak_ptr.h"
12#include "content/browser/renderer_host/render_view_host_delegate.h"
13#include "content/browser/site_instance_impl.h"
14#include "content/common/content_export.h"
15#include "content/public/browser/global_request_id.h"
16#include "content/public/browser/notification_observer.h"
17#include "content/public/browser/notification_registrar.h"
18#include "content/public/common/referrer.h"
19
20
21namespace content {
22class BrowserContext;
23class CrossProcessFrameConnector;
24class CrossSiteTransferringRequest;
25class InterstitialPageImpl;
26class FrameTreeNode;
27class NavigationControllerImpl;
28class NavigationEntry;
29class NavigationEntryImpl;
30class RenderFrameHostDelegate;
31class RenderFrameHostImpl;
32class RenderFrameHostManagerTest;
33class RenderFrameProxyHost;
34class RenderViewHost;
35class RenderViewHostImpl;
36class RenderWidgetHostDelegate;
37class RenderWidgetHostView;
38class TestWebContents;
39class WebUIImpl;
40
41// Manages RenderFrameHosts for a FrameTreeNode.  This class acts as a state
42// machine to make cross-process navigations in a frame possible.
43class CONTENT_EXPORT RenderFrameHostManager : public NotificationObserver {
44 public:
45  // Functions implemented by our owner that we need.
46  //
47  // TODO(brettw) Clean this up! These are all the functions in WebContentsImpl
48  // that are required to run this class. The design should probably be better
49  // such that these are more clear.
50  //
51  // There is additional complexity that some of the functions we need in
52  // WebContentsImpl are inherited and non-virtual. These are named with
53  // "RenderManager" so that the duplicate implementation of them will be clear.
54  class CONTENT_EXPORT Delegate {
55   public:
56    // Initializes the given renderer if necessary and creates the view ID
57    // corresponding to this view host. If this method is not called and the
58    // process is not shared, then the WebContentsImpl will act as though the
59    // renderer is not running (i.e., it will render "sad tab"). This method is
60    // automatically called from LoadURL.
61    //
62    // If you are attaching to an already-existing RenderView, you should call
63    // InitWithExistingID.
64    virtual bool CreateRenderViewForRenderManager(
65        RenderViewHost* render_view_host,
66        int opener_route_id,
67        CrossProcessFrameConnector* cross_process_frame_connector) = 0;
68    virtual void BeforeUnloadFiredFromRenderManager(
69        bool proceed, const base::TimeTicks& proceed_time,
70        bool* proceed_to_fire_unload) = 0;
71    virtual void RenderProcessGoneFromRenderManager(
72        RenderViewHost* render_view_host) = 0;
73    virtual void UpdateRenderViewSizeForRenderManager() = 0;
74    virtual void CancelModalDialogsForRenderManager() = 0;
75    virtual void NotifySwappedFromRenderManager(
76        RenderViewHost* old_host, RenderViewHost* new_host) = 0;
77    virtual NavigationControllerImpl&
78        GetControllerForRenderManager() = 0;
79
80    // Create swapped out RenderViews in the given SiteInstance for each tab in
81    // the opener chain of this tab, if any.  This allows the current tab to
82    // make cross-process script calls to its opener(s).  Returns the route ID
83    // of the immediate opener, if one exists (otherwise MSG_ROUTING_NONE).
84    virtual int CreateOpenerRenderViewsForRenderManager(
85        SiteInstance* instance) = 0;
86
87    // Creates a WebUI object for the given URL if one applies. Ownership of the
88    // returned pointer will be passed to the caller. If no WebUI applies,
89    // returns NULL.
90    virtual WebUIImpl* CreateWebUIForRenderManager(const GURL& url) = 0;
91
92    // Returns the navigation entry of the current navigation, or NULL if there
93    // is none.
94    virtual NavigationEntry*
95        GetLastCommittedNavigationEntryForRenderManager() = 0;
96
97    // Returns true if the location bar should be focused by default rather than
98    // the page contents. The view calls this function when the tab is focused
99    // to see what it should do.
100    virtual bool FocusLocationBarByDefault() = 0;
101
102    // Focuses the location bar.
103    virtual void SetFocusToLocationBar(bool select_all) = 0;
104
105    // Creates a view and sets the size for the specified RVH.
106    virtual void CreateViewAndSetSizeForRVH(RenderViewHost* rvh) = 0;
107
108    // Returns true if views created for this delegate should be created in a
109    // hidden state.
110    virtual bool IsHidden() = 0;
111
112   protected:
113    virtual ~Delegate() {}
114  };
115
116  // Used with FrameTree::ForEach to delete RenderFrameHosts pending shutdown
117  // from a FrameTreeNode's RenderFrameHostManager. Used during destruction of
118  // WebContentsImpl.
119  static bool ClearRFHsPendingShutdown(FrameTreeNode* node);
120
121  // All three delegate pointers must be non-NULL and are not owned by this
122  // class.  They must outlive this class. The RenderViewHostDelegate and
123  // RenderWidgetHostDelegate are what will be installed into all
124  // RenderViewHosts that are created.
125  //
126  // You must call Init() before using this class.
127  RenderFrameHostManager(
128      FrameTreeNode* frame_tree_node,
129      RenderFrameHostDelegate* render_frame_delegate,
130      RenderViewHostDelegate* render_view_delegate,
131      RenderWidgetHostDelegate* render_widget_delegate,
132      Delegate* delegate);
133  virtual ~RenderFrameHostManager();
134
135  // For arguments, see WebContentsImpl constructor.
136  void Init(BrowserContext* browser_context,
137            SiteInstance* site_instance,
138            int view_routing_id,
139            int frame_routing_id);
140
141  // Returns the currently active RenderFrameHost.
142  //
143  // This will be non-NULL between Init() and Shutdown(). You may want to NULL
144  // check it in many cases, however. Windows can send us messages during the
145  // destruction process after it has been shut down.
146  RenderFrameHostImpl* current_frame_host() const {
147    return render_frame_host_.get();
148  }
149
150  // TODO(creis): Remove this when we no longer use RVH for navigation.
151  RenderViewHostImpl* current_host() const;
152
153  // Returns the view associated with the current RenderViewHost, or NULL if
154  // there is no current one.
155  RenderWidgetHostView* GetRenderWidgetHostView() const;
156
157  // Returns the pending RenderFrameHost, or NULL if there is no pending one.
158  RenderFrameHostImpl* pending_frame_host() const {
159    return pending_render_frame_host_.get();
160  }
161
162  // TODO(creis): Remove this when we no longer use RVH for navigation.
163  RenderViewHostImpl* pending_render_view_host() const;
164
165  // Returns the current committed Web UI or NULL if none applies.
166  WebUIImpl* web_ui() const { return web_ui_.get(); }
167
168  // Returns the Web UI for the pending navigation, or NULL of none applies.
169  WebUIImpl* pending_web_ui() const {
170    return pending_web_ui_.get() ? pending_web_ui_.get() :
171                                   pending_and_current_web_ui_.get();
172  }
173
174  // Sets the pending Web UI for the pending navigation, ensuring that the
175  // bindings are appropriate for the given NavigationEntry.
176  void SetPendingWebUI(const NavigationEntryImpl& entry);
177
178  // Called when we want to instruct the renderer to navigate to the given
179  // navigation entry. It may create a new RenderFrameHost or re-use an existing
180  // one. The RenderFrameHost to navigate will be returned. Returns NULL if one
181  // could not be created.
182  RenderFrameHostImpl* Navigate(const NavigationEntryImpl& entry);
183
184  // Instructs the various live views to stop. Called when the user directed the
185  // page to stop loading.
186  void Stop();
187
188  // Notifies the regular and pending RenderViewHosts that a load is or is not
189  // happening. Even though the message is only for one of them, we don't know
190  // which one so we tell both.
191  void SetIsLoading(bool is_loading);
192
193  // Whether to close the tab or not when there is a hang during an unload
194  // handler. If we are mid-crosssite navigation, then we should proceed
195  // with the navigation instead of closing the tab.
196  bool ShouldCloseTabOnUnresponsiveRenderer();
197
198  // Confirms whether we should close the page or navigate away.  This is called
199  // before a cross-site request or before a tab/window is closed (as indicated
200  // by the first parameter) to allow the appropriate renderer to approve or
201  // deny the request.  |proceed| indicates whether the user chose to proceed.
202  // |proceed_time| is the time when the request was allowed to proceed.
203  void OnBeforeUnloadACK(bool for_cross_site_transition,
204                         bool proceed,
205                         const base::TimeTicks& proceed_time);
206
207  // The |pending_render_frame_host| is ready to commit a page.  We should
208  // ensure that the old RenderFrameHost runs its unload handler first and
209  // determine whether a RenderFrameHost transfer is needed.
210  // |cross_site_transferring_request| is NULL if a request is not being
211  // transferred between renderers.
212  void OnCrossSiteResponse(
213      RenderFrameHostImpl* pending_render_frame_host,
214      const GlobalRequestID& global_request_id,
215      scoped_ptr<CrossSiteTransferringRequest> cross_site_transferring_request,
216      const std::vector<GURL>& transfer_url_chain,
217      const Referrer& referrer,
218      PageTransition page_transition,
219      bool should_replace_current_entry);
220
221  // The RenderFrameHost has been swapped out, so we should resume the pending
222  // network response and allow the pending RenderFrameHost to commit.
223  void SwappedOut(RenderFrameHostImpl* render_frame_host);
224
225  // Called when a renderer's frame navigates.
226  void DidNavigateFrame(RenderFrameHostImpl* render_frame_host);
227
228  // Called when a renderer sets its opener to null.
229  void DidDisownOpener(RenderViewHost* render_view_host);
230
231  // Helper method to create and initialize a RenderFrameHost.  If |swapped_out|
232  // is true, it will be initially placed on the swapped out hosts list.
233  // Otherwise, it will be used for a pending cross-site navigation.
234  int CreateRenderFrame(SiteInstance* instance,
235                        int opener_route_id,
236                        bool swapped_out,
237                        bool hidden);
238
239  // Sets the passed passed interstitial as the currently showing interstitial.
240  // |interstitial_page| should be non NULL (use the remove_interstitial_page
241  // method to unset the interstitial) and no interstitial page should be set
242  // when there is already a non NULL interstitial page set.
243  void set_interstitial_page(InterstitialPageImpl* interstitial_page) {
244    DCHECK(!interstitial_page_ && interstitial_page);
245    interstitial_page_ = interstitial_page;
246  }
247
248  // Unsets the currently showing interstitial.
249  void remove_interstitial_page() {
250    DCHECK(interstitial_page_);
251    interstitial_page_ = NULL;
252  }
253
254  // Returns the currently showing interstitial, NULL if no interstitial is
255  // showing.
256  InterstitialPageImpl* interstitial_page() const { return interstitial_page_; }
257
258  // NotificationObserver implementation.
259  virtual void Observe(int type,
260                       const NotificationSource& source,
261                       const NotificationDetails& details) OVERRIDE;
262
263  // Called when a RenderViewHost is about to be deleted.
264  void RenderViewDeleted(RenderViewHost* rvh);
265
266  // Returns whether the given RenderFrameHost (or its associated
267  // RenderViewHost) is on the list of swapped out RenderFrameHosts.
268  bool IsRVHOnSwappedOutList(RenderViewHostImpl* rvh) const;
269  bool IsOnSwappedOutList(RenderFrameHostImpl* rfh) const;
270
271  // Returns the swapped out RenderViewHost or RenderFrameHost for the given
272  // SiteInstance, if any. This method is *deprecated* and
273  // GetRenderFrameProxyHost should be used.
274  RenderViewHostImpl* GetSwappedOutRenderViewHost(SiteInstance* instance) const;
275  RenderFrameProxyHost* GetRenderFrameProxyHost(
276      SiteInstance* instance) const;
277
278  // Runs the unload handler in the current page, when we know that a pending
279  // cross-process navigation is going to commit.  We may initiate a transfer
280  // to a new process after this completes or times out.
281  void SwapOutOldPage();
282
283  // Deletes a RenderFrameHost that was pending shutdown.
284  void ClearPendingShutdownRFHForSiteInstance(int32 site_instance_id,
285                                              RenderFrameHostImpl* rfh);
286
287 private:
288  friend class RenderFrameHostManagerTest;
289  friend class TestWebContents;
290
291  // Tracks information about a navigation while a cross-process transition is
292  // in progress, in case we need to transfer it to a new RenderFrameHost.
293  // When a request is being transferred, deleting the PendingNavigationParams,
294  // and thus |cross_site_transferring_request|, will cancel the request being
295  // transferred, unless its ReleaseRequest method has been called.
296  struct PendingNavigationParams {
297    PendingNavigationParams(
298        const GlobalRequestID& global_request_id,
299        scoped_ptr<CrossSiteTransferringRequest>
300            cross_site_transferring_request,
301        const std::vector<GURL>& transfer_url,
302        Referrer referrer,
303        PageTransition page_transition,
304        int render_frame_id,
305        bool should_replace_current_entry);
306    ~PendingNavigationParams();
307
308    // The child ID and request ID for the pending navigation.  Present whether
309    // |request_transfer| is NULL or not.
310    GlobalRequestID global_request_id;
311
312    // If a pending request needs to be transferred to another process, this
313    // owns the request until it's transferred to the new process, so it will be
314    // cleaned up if the navigation is cancelled.  Otherwise, this is NULL.
315    scoped_ptr<CrossSiteTransferringRequest> cross_site_transferring_request;
316
317    // If |request_transfer| is non-NULL, the values below are all set.
318
319    // The first entry is the original request URL, and the last entry is the
320    // destination URL to request in the new process.
321    std::vector<GURL> transfer_url_chain;
322
323    // This is the referrer to use for the request in the new process.
324    Referrer referrer;
325
326    // This is the transition type for the original navigation.
327    PageTransition page_transition;
328
329    // This is the frame routing ID to use in RequestTransferURL.
330    int render_frame_id;
331
332    // This is whether the navigation should replace the current history entry.
333    bool should_replace_current_entry;
334  };
335
336  // Used with FrameTree::ForEach to erase RenderFrameProxyHosts from a
337  // FrameTreeNode's RenderFrameHostManager.
338  static bool ClearProxiesInSiteInstance(int32 site_instance_id,
339                                         FrameTreeNode* node);
340
341  // Returns whether this tab should transition to a new renderer for
342  // cross-site URLs.  Enabled unless we see the --process-per-tab command line
343  // switch.  Can be overridden in unit tests.
344  bool ShouldTransitionCrossSite();
345
346  // Returns true if for the navigation from |current_entry| to |new_entry|,
347  // a new SiteInstance and BrowsingInstance should be created (even if we are
348  // in a process model that doesn't usually swap).  This forces a process swap
349  // and severs script connections with existing tabs.  Cases where this can
350  // happen include transitions between WebUI and regular web pages.
351  // Either of the entries may be NULL.
352  bool ShouldSwapBrowsingInstancesForNavigation(
353      const NavigationEntry* current_entry,
354      const NavigationEntryImpl* new_entry) const;
355
356  // Returns true if it is safe to reuse the current WebUI when navigating from
357  // |current_entry| to |new_entry|.
358  bool ShouldReuseWebUI(
359      const NavigationEntry* current_entry,
360      const NavigationEntryImpl* new_entry) const;
361
362  // Returns an appropriate SiteInstance object for the given NavigationEntry,
363  // possibly reusing the current SiteInstance.  If --process-per-tab is used,
364  // this is only called when ShouldSwapBrowsingInstancesForNavigation returns
365  // true.
366  SiteInstance* GetSiteInstanceForEntry(
367      const NavigationEntryImpl& entry,
368      SiteInstance* current_instance,
369      bool force_browsing_instance_swap);
370
371  // Creates a RenderFrameHost and corresponding RenderViewHost if necessary.
372  scoped_ptr<RenderFrameHostImpl> CreateRenderFrameHost(SiteInstance* instance,
373                                                        int view_routing_id,
374                                                        int frame_routing_id,
375                                                        bool swapped_out,
376                                                        bool hidden);
377
378  // Sets up the necessary state for a new RenderViewHost with the given opener,
379  // if necessary.  Returns early if the RenderViewHost has already been
380  // initialized for another RenderFrameHost.
381  // TODO(creis): opener_route_id is currently for the RenderViewHost but should
382  // be for the RenderFrame, since frames can have openers.
383  bool InitRenderView(RenderViewHost* render_view_host, int opener_route_id);
384
385  // Sets the pending RenderFrameHost/WebUI to be the active one. Note that this
386  // doesn't require the pending render_frame_host_ pointer to be non-NULL,
387  // since there could be Web UI switching as well. Call this for every commit.
388  void CommitPending();
389
390  // Shutdown all RenderFrameHosts in a SiteInstance. This is called to shutdown
391  // frames when all the frames in a SiteInstance are confirmed to be swapped
392  // out.
393  void ShutdownRenderFrameHostsInSiteInstance(int32 site_instance_id);
394
395  // Helper method to terminate the pending RenderViewHost.
396  void CancelPending();
397
398  RenderFrameHostImpl* UpdateStateForNavigate(
399      const NavigationEntryImpl& entry);
400
401  // Called when a renderer process is starting to close.  We should not
402  // schedule new navigations in its swapped out RenderFrameHosts after this.
403  void RendererProcessClosing(RenderProcessHost* render_process_host);
404
405  // For use in creating RenderFrameHosts.
406  FrameTreeNode* frame_tree_node_;
407
408  // Our delegate, not owned by us. Guaranteed non-NULL.
409  Delegate* delegate_;
410
411  // Whether a navigation requiring different RenderFrameHosts is pending. This
412  // is either for cross-site requests or when required for the process type
413  // (like WebUI).
414  bool cross_navigation_pending_;
415
416  // Implemented by the owner of this class.  These delegates are installed into
417  // all the RenderFrameHosts that we create.
418  RenderFrameHostDelegate* render_frame_delegate_;
419  RenderViewHostDelegate* render_view_delegate_;
420  RenderWidgetHostDelegate* render_widget_delegate_;
421
422  // Our RenderFrameHost and its associated Web UI (if any, will be NULL for
423  // non-WebUI pages). This object is responsible for all communication with
424  // a child RenderFrame instance.
425  // For now, RenderFrameHost keeps a RenderViewHost in its SiteInstance alive.
426  // Eventually, RenderViewHost will be replaced with a page context.
427  scoped_ptr<RenderFrameHostImpl> render_frame_host_;
428  scoped_ptr<WebUIImpl> web_ui_;
429
430  // A RenderFrameHost used to load a cross-site page. This remains hidden
431  // while a cross-site request is pending until it calls DidNavigate. It may
432  // have an associated Web UI, in which case the Web UI pointer will be non-
433  // NULL.
434  //
435  // The |pending_web_ui_| may be non-NULL even when the
436  // |pending_render_frame_host_| is NULL. This will happen when we're
437  // transitioning between two Web UI pages: the RFH won't be swapped, so the
438  // pending pointer will be unused, but there will be a pending Web UI
439  // associated with the navigation.
440  scoped_ptr<RenderFrameHostImpl> pending_render_frame_host_;
441
442  // Tracks information about any current pending cross-process navigation.
443  scoped_ptr<PendingNavigationParams> pending_nav_params_;
444
445  // If either of these is non-NULL, the pending navigation is to a chrome:
446  // page. The scoped_ptr is used if pending_web_ui_ != web_ui_, the WeakPtr is
447  // used for when they reference the same object. If either is non-NULL, the
448  // other should be NULL.
449  scoped_ptr<WebUIImpl> pending_web_ui_;
450  base::WeakPtr<WebUIImpl> pending_and_current_web_ui_;
451
452  // A map of site instance ID to RenderFrameProxyHosts.
453  typedef base::hash_map<int32, RenderFrameProxyHost*> RenderFrameProxyHostMap;
454  RenderFrameProxyHostMap proxy_hosts_;
455
456  // A map of RenderFrameHosts pending shutdown.
457  typedef base::hash_map<int32, linked_ptr<RenderFrameHostImpl> >
458      RFHPendingDeleteMap;
459  RFHPendingDeleteMap pending_delete_hosts_;
460
461  // The intersitial page currently shown if any, not own by this class
462  // (the InterstitialPage is self-owned, it deletes itself when hidden).
463  InterstitialPageImpl* interstitial_page_;
464
465  NotificationRegistrar registrar_;
466
467  // When |render_frame_host_| is in a different process from its parent in
468  // the frame tree, this class connects its associated RenderWidgetHostView
469  // to the proxy RenderFrameHost for the parent's renderer process. NULL
470  // when |render_frame_host_| is the frame tree root or is in the same
471  // process as its parent.
472  CrossProcessFrameConnector* cross_process_frame_connector_;
473
474  base::WeakPtrFactory<RenderFrameHostManager> weak_factory_;
475
476  DISALLOW_COPY_AND_ASSIGN(RenderFrameHostManager);
477};
478
479}  // namespace content
480
481#endif  // CONTENT_BROWSER_FRAME_HOST_RENDER_FRAME_HOST_MANAGER_H_
482