web_contents_impl.h revision 424c4d7b64af9d0d8fd9624f381f469654d5e3d2
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#ifndef CONTENT_BROWSER_WEB_CONTENTS_WEB_CONTENTS_IMPL_H_
6#define CONTENT_BROWSER_WEB_CONTENTS_WEB_CONTENTS_IMPL_H_
7
8#include <map>
9#include <set>
10#include <string>
11
12#include "base/compiler_specific.h"
13#include "base/gtest_prod_util.h"
14#include "base/memory/scoped_ptr.h"
15#include "base/observer_list.h"
16#include "base/process/process.h"
17#include "base/values.h"
18#include "content/browser/renderer_host/render_view_host_delegate.h"
19#include "content/browser/renderer_host/render_widget_host_delegate.h"
20#include "content/browser/web_contents/frame_tree_node.h"
21#include "content/browser/web_contents/navigation_controller_impl.h"
22#include "content/browser/web_contents/render_view_host_manager.h"
23#include "content/common/content_export.h"
24#include "content/public/browser/notification_observer.h"
25#include "content/public/browser/notification_registrar.h"
26#include "content/public/browser/web_contents.h"
27#include "content/public/common/renderer_preferences.h"
28#include "content/public/common/three_d_api_types.h"
29#include "net/base/load_states.h"
30#include "third_party/WebKit/public/web/WebDragOperation.h"
31#include "ui/gfx/rect_f.h"
32#include "ui/gfx/size.h"
33#include "ui/gfx/vector2d.h"
34#include "webkit/common/resource_type.h"
35
36struct BrowserPluginHostMsg_ResizeGuest_Params;
37struct ViewHostMsg_DateTimeDialogValue_Params;
38struct ViewMsg_PostMessage_Params;
39
40namespace content {
41class BrowserPluginEmbedder;
42class BrowserPluginGuest;
43class BrowserPluginGuestManager;
44class ColorChooser;
45class DateTimeChooserAndroid;
46class DownloadItem;
47class InterstitialPageImpl;
48class JavaBridgeDispatcherHostManager;
49class JavaScriptDialogManager;
50class PowerSaveBlocker;
51class RenderViewHost;
52class RenderViewHostDelegateView;
53class RenderViewHostImpl;
54class RenderWidgetHostImpl;
55class RenderWidgetHostViewPort;
56class SavePackage;
57class SessionStorageNamespaceImpl;
58class SiteInstance;
59class TestWebContents;
60class WebContentsDelegate;
61class WebContentsImpl;
62class WebContentsObserver;
63class WebContentsViewPort;
64class WebContentsViewDelegate;
65struct FaviconURL;
66struct LoadNotificationDetails;
67
68// Factory function for the implementations that content knows about. Takes
69// ownership of |delegate|.
70WebContentsViewPort* CreateWebContentsView(
71    WebContentsImpl* web_contents,
72    WebContentsViewDelegate* delegate,
73    RenderViewHostDelegateView** render_view_host_delegate_view);
74
75class CONTENT_EXPORT WebContentsImpl
76    : public NON_EXPORTED_BASE(WebContents),
77      public RenderViewHostDelegate,
78      public RenderWidgetHostDelegate,
79      public RenderViewHostManager::Delegate,
80      public NotificationObserver {
81 public:
82  virtual ~WebContentsImpl();
83
84  static WebContentsImpl* CreateWithOpener(
85      const WebContents::CreateParams& params,
86      WebContentsImpl* opener);
87
88  // Returns the opener WebContentsImpl, if any. This can be set to null if the
89  // opener is closed or the page clears its window.opener.
90  WebContentsImpl* opener() const { return opener_; }
91
92  // Creates a WebContents to be used as a browser plugin guest.
93  static BrowserPluginGuest* CreateGuest(
94      BrowserContext* browser_context,
95      content::SiteInstance* site_instance,
96      int guest_instance_id,
97      scoped_ptr<base::DictionaryValue> extra_params);
98
99  // Returns the content specific prefs for the given RVH.
100  static WebPreferences GetWebkitPrefs(
101      RenderViewHost* rvh, const GURL& url);
102
103  // Creates a swapped out RenderView. This is used by the browser plugin to
104  // create a swapped out RenderView in the embedder render process for the
105  // guest, to expose the guest's window object to the embedder.
106  // This returns the routing ID of the newly created swapped out RenderView.
107  int CreateSwappedOutRenderView(SiteInstance* instance);
108
109  // Complex initialization here. Specifically needed to avoid having
110  // members call back into our virtual functions in the constructor.
111  virtual void Init(const WebContents::CreateParams& params);
112
113  // Returns the SavePackage which manages the page saving job. May be NULL.
114  SavePackage* save_package() const { return save_package_.get(); }
115
116  // Updates the max page ID for the current SiteInstance in this
117  // WebContentsImpl to be at least |page_id|.
118  void UpdateMaxPageID(int32 page_id);
119
120  // Updates the max page ID for the given SiteInstance in this WebContentsImpl
121  // to be at least |page_id|.
122  void UpdateMaxPageIDForSiteInstance(SiteInstance* site_instance,
123                                      int32 page_id);
124
125  // Copy the current map of SiteInstance ID to max page ID from another tab.
126  // This is necessary when this tab adopts the NavigationEntries from
127  // |web_contents|.
128  void CopyMaxPageIDsFrom(WebContentsImpl* web_contents);
129
130  // Called by the NavigationController to cause the WebContentsImpl to navigate
131  // to the current pending entry. The NavigationController should be called
132  // back with RendererDidNavigate on success or DiscardPendingEntry on failure.
133  // The callbacks can be inside of this function, or at some future time.
134  //
135  // The entry has a PageID of -1 if newly created (corresponding to navigation
136  // to a new URL).
137  //
138  // If this method returns false, then the navigation is discarded (equivalent
139  // to calling DiscardPendingEntry on the NavigationController).
140  bool NavigateToPendingEntry(NavigationController::ReloadType reload_type);
141
142  // Called by InterstitialPageImpl when it creates a RenderViewHost.
143  void RenderViewForInterstitialPageCreated(RenderViewHost* render_view_host);
144
145  // Sets the passed interstitial as the currently showing interstitial.
146  // No interstitial page should already be attached.
147  void AttachInterstitialPage(InterstitialPageImpl* interstitial_page);
148
149  // Unsets the currently showing interstitial.
150  void DetachInterstitialPage();
151
152#if defined(OS_ANDROID)
153  JavaBridgeDispatcherHostManager* java_bridge_dispatcher_host_manager() const {
154    return java_bridge_dispatcher_host_manager_.get();
155  }
156
157  // In Android WebView, the RenderView needs created even there is no
158  // navigation entry, this allows Android WebViews to use
159  // javascript: URLs that load into the DOMWindow before the first page
160  // load. This is not safe to do in any context that a web page could get a
161  // reference to the DOMWindow before the first page load.
162  bool CreateRenderViewForInitialEmptyDocument();
163#endif
164
165  // Expose the render manager for testing.
166  RenderViewHostManager* GetRenderManagerForTesting();
167
168  // Returns guest browser plugin object, or NULL if this WebContents is not a
169  // guest.
170  BrowserPluginGuest* GetBrowserPluginGuest() const;
171
172  // Sets a BrowserPluginGuest object for this WebContents. If this WebContents
173  // has a BrowserPluginGuest then that implies that it is being hosted by
174  // a BrowserPlugin object in an embedder renderer process.
175  void SetBrowserPluginGuest(BrowserPluginGuest* guest);
176
177  // Returns embedder browser plugin object, or NULL if this WebContents is not
178  // an embedder.
179  BrowserPluginEmbedder* GetBrowserPluginEmbedder() const;
180
181  // Returns the BrowserPluginGuestManager object, or NULL if this web contents
182  // does not have a BrowserPluginGuestManager.
183  BrowserPluginGuestManager* GetBrowserPluginGuestManager() const;
184
185  // Gets the current fullscreen render widget's routing ID. Returns
186  // MSG_ROUTING_NONE when there is no fullscreen render widget.
187  int GetFullscreenWidgetRoutingID() const;
188
189  // Invoked when visible SSL state (as defined by SSLStatus) changes.
190  void DidChangeVisibleSSLState();
191
192  // Invoked before a form repost warning is shown.
193  void NotifyBeforeFormRepostWarningShow();
194
195
196  // Informs the render view host and the BrowserPluginEmbedder, if present, of
197  // a Drag Source End.
198  void DragSourceEndedAt(int client_x, int client_y, int screen_x,
199      int screen_y, WebKit::WebDragOperation operation);
200
201  // Informs the render view host and the BrowserPluginEmbedder, if present, of
202  // a Drag Source Move.
203  void DragSourceMovedTo(int client_x, int client_y,
204                         int screen_x, int screen_y);
205
206  FrameTreeNode* GetFrameTreeRootForTesting() {
207    return frame_tree_root_.get();
208  }
209
210  // WebContents ------------------------------------------------------
211  virtual WebContentsDelegate* GetDelegate() OVERRIDE;
212  virtual void SetDelegate(WebContentsDelegate* delegate) OVERRIDE;
213  virtual NavigationControllerImpl& GetController() OVERRIDE;
214  virtual const NavigationControllerImpl& GetController() const OVERRIDE;
215  virtual BrowserContext* GetBrowserContext() const OVERRIDE;
216  virtual RenderProcessHost* GetRenderProcessHost() const OVERRIDE;
217  virtual RenderViewHost* GetRenderViewHost() const OVERRIDE;
218  virtual void GetRenderViewHostAtPosition(
219      int x,
220      int y,
221      const GetRenderViewHostCallback& callback) OVERRIDE;
222  virtual WebContents* GetEmbedderWebContents() const OVERRIDE;
223  virtual int GetEmbeddedInstanceID() const OVERRIDE;
224  virtual int GetRoutingID() const OVERRIDE;
225  virtual RenderWidgetHostView* GetRenderWidgetHostView() const OVERRIDE;
226  virtual WebContentsView* GetView() const OVERRIDE;
227  virtual WebUI* CreateWebUI(const GURL& url) OVERRIDE;
228  virtual WebUI* GetWebUI() const OVERRIDE;
229  virtual WebUI* GetCommittedWebUI() const OVERRIDE;
230  virtual void SetUserAgentOverride(const std::string& override) OVERRIDE;
231  virtual const std::string& GetUserAgentOverride() const OVERRIDE;
232#if defined(OS_WIN) && defined(USE_AURA)
233  virtual void SetParentNativeViewAccessible(
234      gfx::NativeViewAccessible accessible_parent) OVERRIDE;
235#endif
236  virtual const string16& GetTitle() const OVERRIDE;
237  virtual int32 GetMaxPageID() OVERRIDE;
238  virtual int32 GetMaxPageIDForSiteInstance(
239      SiteInstance* site_instance) OVERRIDE;
240  virtual SiteInstance* GetSiteInstance() const OVERRIDE;
241  virtual SiteInstance* GetPendingSiteInstance() const OVERRIDE;
242  virtual bool IsLoading() const OVERRIDE;
243  virtual bool IsWaitingForResponse() const OVERRIDE;
244  virtual const net::LoadStateWithParam& GetLoadState() const OVERRIDE;
245  virtual const string16& GetLoadStateHost() const OVERRIDE;
246  virtual uint64 GetUploadSize() const OVERRIDE;
247  virtual uint64 GetUploadPosition() const OVERRIDE;
248  virtual std::set<GURL> GetSitesInTab() const OVERRIDE;
249  virtual const std::string& GetEncoding() const OVERRIDE;
250  virtual bool DisplayedInsecureContent() const OVERRIDE;
251  virtual void IncrementCapturerCount() OVERRIDE;
252  virtual void DecrementCapturerCount() OVERRIDE;
253  virtual int GetCapturerCount() const OVERRIDE;
254  virtual bool IsCrashed() const OVERRIDE;
255  virtual void SetIsCrashed(base::TerminationStatus status,
256                            int error_code) OVERRIDE;
257  virtual base::TerminationStatus GetCrashedStatus() const OVERRIDE;
258  virtual bool IsBeingDestroyed() const OVERRIDE;
259  virtual void NotifyNavigationStateChanged(unsigned changed_flags) OVERRIDE;
260  virtual base::TimeTicks GetLastSelectedTime() const OVERRIDE;
261  virtual void WasShown() OVERRIDE;
262  virtual void WasHidden() OVERRIDE;
263  virtual bool NeedToFireBeforeUnload() OVERRIDE;
264  virtual void Stop() OVERRIDE;
265  virtual WebContents* Clone() OVERRIDE;
266  virtual void FocusThroughTabTraversal(bool reverse) OVERRIDE;
267  virtual bool ShowingInterstitialPage() const OVERRIDE;
268  virtual InterstitialPage* GetInterstitialPage() const OVERRIDE;
269  virtual bool IsSavable() OVERRIDE;
270  virtual void OnSavePage() OVERRIDE;
271  virtual bool SavePage(const base::FilePath& main_file,
272                        const base::FilePath& dir_path,
273                        SavePageType save_type) OVERRIDE;
274  virtual void SaveFrame(const GURL& url,
275                         const Referrer& referrer) OVERRIDE;
276  virtual void GenerateMHTML(
277      const base::FilePath& file,
278      const base::Callback<void(int64)>& callback)
279          OVERRIDE;
280  virtual bool IsActiveEntry(int32 page_id) OVERRIDE;
281
282  virtual const std::string& GetContentsMimeType() const OVERRIDE;
283  virtual bool WillNotifyDisconnection() const OVERRIDE;
284  virtual void SetOverrideEncoding(const std::string& encoding) OVERRIDE;
285  virtual void ResetOverrideEncoding() OVERRIDE;
286  virtual RendererPreferences* GetMutableRendererPrefs() OVERRIDE;
287  virtual void Close() OVERRIDE;
288  virtual void SystemDragEnded() OVERRIDE;
289  virtual void UserGestureDone() OVERRIDE;
290  virtual void SetClosedByUserGesture(bool value) OVERRIDE;
291  virtual bool GetClosedByUserGesture() const OVERRIDE;
292  virtual double GetZoomLevel() const OVERRIDE;
293  virtual int GetZoomPercent(bool* enable_increment,
294                             bool* enable_decrement) const OVERRIDE;
295  virtual void ViewSource() OVERRIDE;
296  virtual void ViewFrameSource(const GURL& url,
297                               const PageState& page_state) OVERRIDE;
298  virtual int GetMinimumZoomPercent() const OVERRIDE;
299  virtual int GetMaximumZoomPercent() const OVERRIDE;
300  virtual gfx::Size GetPreferredSize() const OVERRIDE;
301  virtual bool GotResponseToLockMouseRequest(bool allowed) OVERRIDE;
302  virtual bool HasOpener() const OVERRIDE;
303  virtual void DidChooseColorInColorChooser(SkColor color) OVERRIDE;
304  virtual void DidEndColorChooser() OVERRIDE;
305  virtual int DownloadImage(const GURL& url,
306                            bool is_favicon,
307                            uint32_t preferred_image_size,
308                            uint32_t max_image_size,
309                            const ImageDownloadCallback& callback) OVERRIDE;
310
311  // Implementation of PageNavigator.
312  virtual WebContents* OpenURL(const OpenURLParams& params) OVERRIDE;
313
314  // Implementation of IPC::Sender.
315  virtual bool Send(IPC::Message* message) OVERRIDE;
316
317  // RenderViewHostDelegate ----------------------------------------------------
318
319  virtual RenderViewHostDelegateView* GetDelegateView() OVERRIDE;
320  virtual RenderViewHostDelegate::RendererManagement*
321      GetRendererManagementDelegate() OVERRIDE;
322  virtual bool OnMessageReceived(RenderViewHost* render_view_host,
323                                 const IPC::Message& message) OVERRIDE;
324  virtual const GURL& GetURL() const OVERRIDE;
325  virtual const GURL& GetVisibleURL() const OVERRIDE;
326  virtual const GURL& GetLastCommittedURL() const OVERRIDE;
327  virtual WebContents* GetAsWebContents() OVERRIDE;
328  virtual gfx::Rect GetRootWindowResizerRect() const OVERRIDE;
329  virtual void RenderViewCreated(RenderViewHost* render_view_host) OVERRIDE;
330  virtual void RenderViewReady(RenderViewHost* render_view_host) OVERRIDE;
331  virtual void RenderViewTerminated(RenderViewHost* render_view_host,
332                                    base::TerminationStatus status,
333                                    int error_code) OVERRIDE;
334  virtual void RenderViewDeleted(RenderViewHost* render_view_host) OVERRIDE;
335  virtual void DidStartProvisionalLoadForFrame(
336      RenderViewHost* render_view_host,
337      int64 frame_id,
338      int64 parent_frame_id,
339      bool main_frame,
340      const GURL& url) OVERRIDE;
341  virtual void DidRedirectProvisionalLoad(
342      RenderViewHost* render_view_host,
343      int32 page_id,
344      const GURL& source_url,
345      const GURL& target_url) OVERRIDE;
346  virtual void DidFailProvisionalLoadWithError(
347      RenderViewHost* render_view_host,
348      const ViewHostMsg_DidFailProvisionalLoadWithError_Params& params)
349          OVERRIDE;
350  virtual void DidNavigate(
351      RenderViewHost* render_view_host,
352      const ViewHostMsg_FrameNavigate_Params& params) OVERRIDE;
353  virtual void UpdateState(RenderViewHost* render_view_host,
354                           int32 page_id,
355                           const PageState& page_state) OVERRIDE;
356  virtual void UpdateTitle(RenderViewHost* render_view_host,
357                           int32 page_id,
358                           const string16& title,
359                           base::i18n::TextDirection title_direction) OVERRIDE;
360  virtual void UpdateEncoding(RenderViewHost* render_view_host,
361                              const std::string& encoding) OVERRIDE;
362  virtual void UpdateTargetURL(int32 page_id, const GURL& url) OVERRIDE;
363  virtual void Close(RenderViewHost* render_view_host) OVERRIDE;
364  virtual void RequestMove(const gfx::Rect& new_bounds) OVERRIDE;
365  virtual void SwappedOut(RenderViewHost* render_view_host) OVERRIDE;
366  virtual void DidStartLoading(RenderViewHost* render_view_host) OVERRIDE;
367  virtual void DidStopLoading(RenderViewHost* render_view_host) OVERRIDE;
368  virtual void DidCancelLoading() OVERRIDE;
369  virtual void DidChangeLoadProgress(double progress) OVERRIDE;
370  virtual void DidDisownOpener(RenderViewHost* rvh) OVERRIDE;
371  virtual void DidAccessInitialDocument() OVERRIDE;
372  virtual void DocumentAvailableInMainFrame(
373      RenderViewHost* render_view_host) OVERRIDE;
374  virtual void DocumentOnLoadCompletedInMainFrame(
375      RenderViewHost* render_view_host,
376      int32 page_id) OVERRIDE;
377  virtual void RequestOpenURL(RenderViewHost* rvh,
378                              const GURL& url,
379                              const Referrer& referrer,
380                              WindowOpenDisposition disposition,
381                              int64 source_frame_id,
382                              bool should_replace_current_entry,
383                              bool user_gesture) OVERRIDE;
384  virtual void RequestTransferURL(
385      const GURL& url,
386      const Referrer& referrer,
387      WindowOpenDisposition disposition,
388      int64 source_frame_id,
389      const GlobalRequestID& transferred_global_request_id,
390      bool should_replace_current_entry,
391      bool user_gesture) OVERRIDE;
392  virtual void RouteCloseEvent(RenderViewHost* rvh) OVERRIDE;
393  virtual void RouteMessageEvent(
394      RenderViewHost* rvh,
395      const ViewMsg_PostMessage_Params& params) OVERRIDE;
396  virtual void RunJavaScriptMessage(RenderViewHost* rvh,
397                                    const string16& message,
398                                    const string16& default_prompt,
399                                    const GURL& frame_url,
400                                    JavaScriptMessageType type,
401                                    bool user_gesture,
402                                    IPC::Message* reply_msg,
403                                    bool* did_suppress_message) OVERRIDE;
404  virtual void RunBeforeUnloadConfirm(RenderViewHost* rvh,
405                                      const string16& message,
406                                      bool is_reload,
407                                      IPC::Message* reply_msg) OVERRIDE;
408  virtual bool AddMessageToConsole(int32 level,
409                                   const string16& message,
410                                   int32 line_no,
411                                   const string16& source_id,
412                                   const string16& stack_trace) OVERRIDE;
413  virtual RendererPreferences GetRendererPrefs(
414      BrowserContext* browser_context) const OVERRIDE;
415  virtual WebPreferences GetWebkitPrefs() OVERRIDE;
416  virtual void OnUserGesture() OVERRIDE;
417  virtual void OnIgnoredUIEvent() OVERRIDE;
418  virtual void RendererUnresponsive(RenderViewHost* render_view_host,
419                                    bool is_during_beforeunload,
420                                    bool is_during_unload) OVERRIDE;
421  virtual void RendererResponsive(RenderViewHost* render_view_host) OVERRIDE;
422  virtual void LoadStateChanged(const GURL& url,
423                                const net::LoadStateWithParam& load_state,
424                                uint64 upload_position,
425                                uint64 upload_size) OVERRIDE;
426  virtual void WorkerCrashed() OVERRIDE;
427  virtual void Activate() OVERRIDE;
428  virtual void Deactivate() OVERRIDE;
429  virtual void LostCapture() OVERRIDE;
430  virtual void HandleMouseDown() OVERRIDE;
431  virtual void HandleMouseUp() OVERRIDE;
432  virtual void HandlePointerActivate() OVERRIDE;
433  virtual void HandleGestureBegin() OVERRIDE;
434  virtual void HandleGestureEnd() OVERRIDE;
435  virtual void RunFileChooser(
436      RenderViewHost* render_view_host,
437      const FileChooserParams& params) OVERRIDE;
438  virtual void ToggleFullscreenMode(bool enter_fullscreen) OVERRIDE;
439  virtual bool IsFullscreenForCurrentTab() const OVERRIDE;
440  virtual void UpdatePreferredSize(const gfx::Size& pref_size) OVERRIDE;
441  virtual void ResizeDueToAutoResize(const gfx::Size& new_size) OVERRIDE;
442  virtual void RequestToLockMouse(bool user_gesture,
443                                  bool last_unlocked_by_target) OVERRIDE;
444  virtual void LostMouseLock() OVERRIDE;
445  virtual void CreateNewWindow(
446      int route_id,
447      int main_frame_route_id,
448      const ViewHostMsg_CreateWindow_Params& params,
449      SessionStorageNamespace* session_storage_namespace) OVERRIDE;
450  virtual void CreateNewWidget(int route_id,
451                               WebKit::WebPopupType popup_type) OVERRIDE;
452  virtual void CreateNewFullscreenWidget(int route_id) OVERRIDE;
453  virtual void ShowCreatedWindow(int route_id,
454                                 WindowOpenDisposition disposition,
455                                 const gfx::Rect& initial_pos,
456                                 bool user_gesture) OVERRIDE;
457  virtual void ShowCreatedWidget(int route_id,
458                                 const gfx::Rect& initial_pos) OVERRIDE;
459  virtual void ShowCreatedFullscreenWidget(int route_id) OVERRIDE;
460  virtual void ShowContextMenu(const ContextMenuParams& params) OVERRIDE;
461  virtual void RequestMediaAccessPermission(
462      const MediaStreamRequest& request,
463      const MediaResponseCallback& callback) OVERRIDE;
464  virtual SessionStorageNamespace* GetSessionStorageNamespace(
465      SiteInstance* instance) OVERRIDE;
466
467  // RenderWidgetHostDelegate --------------------------------------------------
468
469  virtual void RenderWidgetDeleted(
470      RenderWidgetHostImpl* render_widget_host) OVERRIDE;
471  virtual bool PreHandleKeyboardEvent(
472      const NativeWebKeyboardEvent& event,
473      bool* is_keyboard_shortcut) OVERRIDE;
474  virtual void HandleKeyboardEvent(
475      const NativeWebKeyboardEvent& event) OVERRIDE;
476  virtual bool PreHandleWheelEvent(
477      const WebKit::WebMouseWheelEvent& event) OVERRIDE;
478  virtual void DidSendScreenRects(RenderWidgetHostImpl* rwh) OVERRIDE;
479#if defined(OS_WIN) && defined(USE_AURA)
480  virtual gfx::NativeViewAccessible GetParentNativeViewAccessible() OVERRIDE;
481#endif
482
483  // RenderViewHostManager::Delegate -------------------------------------------
484
485  virtual bool CreateRenderViewForRenderManager(
486      RenderViewHost* render_view_host, int opener_route_id) OVERRIDE;
487  virtual void BeforeUnloadFiredFromRenderManager(
488      bool proceed, const base::TimeTicks& proceed_time,
489      bool* proceed_to_fire_unload) OVERRIDE;
490  virtual void RenderProcessGoneFromRenderManager(
491      RenderViewHost* render_view_host) OVERRIDE;
492  virtual void UpdateRenderViewSizeForRenderManager() OVERRIDE;
493  virtual void NotifySwappedFromRenderManager(
494      RenderViewHost* old_render_view_host) OVERRIDE;
495  virtual int CreateOpenerRenderViewsForRenderManager(
496      SiteInstance* instance) OVERRIDE;
497  virtual NavigationControllerImpl&
498      GetControllerForRenderManager() OVERRIDE;
499  virtual WebUIImpl* CreateWebUIForRenderManager(const GURL& url) OVERRIDE;
500  virtual NavigationEntry*
501      GetLastCommittedNavigationEntryForRenderManager() OVERRIDE;
502  virtual bool FocusLocationBarByDefault() OVERRIDE;
503  virtual void SetFocusToLocationBar(bool select_all) OVERRIDE;
504  virtual void CreateViewAndSetSizeForRVH(RenderViewHost* rvh) OVERRIDE;
505  virtual bool IsHidden() OVERRIDE;
506
507  // NotificationObserver ------------------------------------------------------
508
509  virtual void Observe(int type,
510                       const NotificationSource& source,
511                       const NotificationDetails& details) OVERRIDE;
512
513
514 private:
515  friend class NavigationControllerImpl;
516  friend class WebContentsObserver;
517  friend class WebContents;  // To implement factory methods.
518
519  FRIEND_TEST_ALL_PREFIXES(WebContentsImplTest, NoJSMessageOnInterstitials);
520  FRIEND_TEST_ALL_PREFIXES(WebContentsImplTest, UpdateTitle);
521  FRIEND_TEST_ALL_PREFIXES(WebContentsImplTest, FindOpenerRVHWhenPending);
522  FRIEND_TEST_ALL_PREFIXES(WebContentsImplTest,
523                           CrossSiteCantPreemptAfterUnload);
524  FRIEND_TEST_ALL_PREFIXES(WebContentsImplTest, PendingContents);
525  FRIEND_TEST_ALL_PREFIXES(WebContentsImplTest, FrameTreeShape);
526  FRIEND_TEST_ALL_PREFIXES(FormStructureBrowserTest, HTMLFiles);
527  FRIEND_TEST_ALL_PREFIXES(NavigationControllerTest, HistoryNavigate);
528  FRIEND_TEST_ALL_PREFIXES(RenderViewHostManagerTest, PageDoesBackAndReload);
529
530  // So InterstitialPageImpl can access SetIsLoading.
531  friend class InterstitialPageImpl;
532
533  // TODO(brettw) TestWebContents shouldn't exist!
534  friend class TestWebContents;
535
536  class DestructionObserver;
537
538  // See WebContents::Create for a description of these parameters.
539  WebContentsImpl(BrowserContext* browser_context,
540                  WebContentsImpl* opener);
541
542  // Add and remove observers for page navigation notifications. Adding or
543  // removing multiple times has no effect. The order in which notifications
544  // are sent to observers is undefined. Clients must be sure to remove the
545  // observer before they go away.
546  void AddObserver(WebContentsObserver* observer);
547  void RemoveObserver(WebContentsObserver* observer);
548
549  // Clears this tab's opener if it has been closed.
550  void OnWebContentsDestroyed(WebContentsImpl* web_contents);
551
552  // Creates and adds to the map a destruction observer watching |web_contents|.
553  // No-op if such an observer already exists.
554  void AddDestructionObserver(WebContentsImpl* web_contents);
555
556  // Deletes and removes from the map a destruction observer
557  // watching |web_contents|. No-op if there is no such observer.
558  void RemoveDestructionObserver(WebContentsImpl* web_contents);
559
560  // Callback function when showing JS dialogs.
561  void OnDialogClosed(RenderViewHost* rvh,
562                      IPC::Message* reply_msg,
563                      bool success,
564                      const string16& user_input);
565
566  // Callback function when requesting permission to access the PPAPI broker.
567  // |result| is true if permission was granted.
568  void OnPpapiBrokerPermissionResult(int routing_id, bool result);
569
570  // IPC message handlers.
571  void OnDidLoadResourceFromMemoryCache(const GURL& url,
572                                        const std::string& security_info,
573                                        const std::string& http_request,
574                                        const std::string& mime_type,
575                                        ResourceType::Type resource_type);
576  void OnDidDisplayInsecureContent();
577  void OnDidRunInsecureContent(const std::string& security_origin,
578                               const GURL& target_url);
579  void OnDocumentLoadedInFrame(int64 frame_id);
580  void OnDidFinishLoad(int64 frame_id,
581                       const GURL& url,
582                       bool is_main_frame);
583  void OnDidFailLoadWithError(int64 frame_id,
584                              const GURL& url,
585                              bool is_main_frame,
586                              int error_code,
587                              const string16& error_description);
588  void OnGoToEntryAtOffset(int offset);
589  void OnUpdateZoomLimits(int minimum_percent,
590                          int maximum_percent,
591                          bool remember);
592  void OnEnumerateDirectory(int request_id, const base::FilePath& path);
593  void OnJSOutOfMemory();
594
595  void OnRegisterProtocolHandler(const std::string& protocol,
596                                 const GURL& url,
597                                 const string16& title,
598                                 bool user_gesture);
599  void OnFindReply(int request_id,
600                   int number_of_matches,
601                   const gfx::Rect& selection_rect,
602                   int active_match_ordinal,
603                   bool final_update);
604  void OnDidProgrammaticallyScroll(const gfx::Vector2d& scroll_point);
605#if defined(OS_ANDROID)
606  void OnFindMatchRectsReply(int version,
607                             const std::vector<gfx::RectF>& rects,
608                             const gfx::RectF& active_rect);
609
610  void OnOpenDateTimeDialog(
611      const ViewHostMsg_DateTimeDialogValue_Params& value);
612#endif
613  void OnCrashedPlugin(const base::FilePath& plugin_path,
614                       base::ProcessId plugin_pid);
615  void OnAppCacheAccessed(const GURL& manifest_url, bool blocked_by_policy);
616  void OnOpenColorChooser(int color_chooser_id, SkColor color);
617  void OnEndColorChooser(int color_chooser_id);
618  void OnSetSelectedColorInColorChooser(int color_chooser_id, SkColor color);
619  void OnPepperPluginHung(int plugin_child_id,
620                          const base::FilePath& path,
621                          bool is_hung);
622  void OnWebUISend(const GURL& source_url,
623                   const std::string& name,
624                   const base::ListValue& args);
625  void OnRequestPpapiBrokerPermission(int routing_id,
626                                      const GURL& url,
627                                      const base::FilePath& plugin_path);
628  void OnBrowserPluginMessage(const IPC::Message& message);
629  void OnDidDownloadImage(int id,
630                          int http_status_code,
631                          const GURL& image_url,
632                          int requested_size,
633                          const std::vector<SkBitmap>& bitmaps);
634  void OnUpdateFaviconURL(int32 page_id,
635                          const std::vector<FaviconURL>& candidates);
636  void OnFrameAttached(int64 parent_frame_id,
637                       int64 frame_id,
638                       const std::string& frame_name);
639  void OnFrameDetached(int64 parent_frame_id, int64 frame_id);
640
641  void OnMediaNotification(int64 player_cookie,
642                           bool has_video,
643                           bool has_audio,
644                           bool is_playing);
645
646  // Changes the IsLoading state and notifies delegate as needed
647  // |details| is used to provide details on the load that just finished
648  // (but can be null if not applicable). Can be overridden.
649  void SetIsLoading(bool is_loading,
650                    LoadNotificationDetails* details);
651
652  // Called by derived classes to indicate that we're no longer waiting for a
653  // response. This won't actually update the throbber, but it will get picked
654  // up at the next animation step if the throbber is going.
655  void SetNotWaitingForResponse() { waiting_for_response_ = false; }
656
657  // Navigation helpers --------------------------------------------------------
658  //
659  // These functions are helpers for Navigate() and DidNavigate().
660
661  // Handles post-navigation tasks in DidNavigate AFTER the entry has been
662  // committed to the navigation controller. Note that the navigation entry is
663  // not provided since it may be invalid/changed after being committed. The
664  // current navigation entry is in the NavigationController at this point.
665  void DidNavigateMainFramePostCommit(
666      const LoadCommittedDetails& details,
667      const ViewHostMsg_FrameNavigate_Params& params);
668  void DidNavigateAnyFramePostCommit(
669      RenderViewHost* render_view_host,
670      const LoadCommittedDetails& details,
671      const ViewHostMsg_FrameNavigate_Params& params);
672
673  // Specifies whether the passed in URL should be assigned as the site of the
674  // current SiteInstance, if it does not yet have a site.
675  bool ShouldAssignSiteForURL(const GURL& url);
676
677  // If our controller was restored, update the max page ID associated with the
678  // given RenderViewHost to be larger than the number of restored entries.
679  // This is called in CreateRenderView before any navigations in the RenderView
680  // have begun, to prevent any races in updating RenderView::next_page_id.
681  void UpdateMaxPageIDIfNecessary(RenderViewHost* rvh);
682
683  // Saves the given title to the navigation entry and does associated work. It
684  // will update history and the view for the new title, and also synthesize
685  // titles for file URLs that have none (so we require that the URL of the
686  // entry already be set).
687  //
688  // This is used as the backend for state updates, which include a new title,
689  // or the dedicated set title message. It returns true if the new title is
690  // different and was therefore updated.
691  bool UpdateTitleForEntry(NavigationEntryImpl* entry,
692                           const string16& title);
693
694  // Causes the WebContentsImpl to navigate in the right renderer to |entry|,
695  // which must be already part of the entries in the navigation controller.
696  // This does not change the NavigationController state.
697  bool NavigateToEntry(const NavigationEntryImpl& entry,
698                       NavigationController::ReloadType reload_type);
699
700  // Sets the history for this WebContentsImpl to |history_length| entries, and
701  // moves the current page_id to the last entry in the list if it's valid.
702  // This is mainly used when a prerendered page is swapped into the current
703  // tab. The method is virtual for testing.
704  virtual void SetHistoryLengthAndPrune(
705      const SiteInstance* site_instance,
706      int merge_history_length,
707      int32 minimum_page_id);
708
709  // Recursively creates swapped out RenderViews for this tab's opener chain
710  // (including this tab) in the given SiteInstance, allowing other tabs to send
711  // cross-process JavaScript calls to their opener(s).  Returns the route ID of
712  // this tab's RenderView for |instance|.
713  int CreateOpenerRenderViews(SiteInstance* instance);
714
715  // Helper for CreateNewWidget/CreateNewFullscreenWidget.
716  void CreateNewWidget(int route_id,
717                       bool is_fullscreen,
718                       WebKit::WebPopupType popup_type);
719
720  // Helper for ShowCreatedWidget/ShowCreatedFullscreenWidget.
721  void ShowCreatedWidget(int route_id,
722                         bool is_fullscreen,
723                         const gfx::Rect& initial_pos);
724
725  // Finds the new RenderWidgetHost and returns it. Note that this can only be
726  // called once as this call also removes it from the internal map.
727  RenderWidgetHostView* GetCreatedWidget(int route_id);
728
729  // Finds the new WebContentsImpl by route_id, initializes it for
730  // renderer-initiated creation, and returns it. Note that this can only be
731  // called once as this call also removes it from the internal map.
732  WebContentsImpl* GetCreatedWindow(int route_id);
733
734  // Returns the RenderWidgetHostView that is associated with a native window
735  // and can be used in showing created widgets.
736  // If this WebContents belongs to a browser plugin guest, there is no native
737  // window 'view' associated with this WebContents. This method returns the
738  // 'view' of the embedder instead.
739  RenderWidgetHostViewPort* GetRenderWidgetHostViewPort() const;
740
741  // Misc non-view stuff -------------------------------------------------------
742
743  // Helper functions for sending notifications.
744  void NotifySwapped(RenderViewHost* old_render_view_host);
745  void NotifyConnected();
746  void NotifyDisconnected();
747  void NotifyNavigationEntryCommitted(const LoadCommittedDetails& load_details);
748
749  void SetEncoding(const std::string& encoding);
750
751  RenderViewHostImpl* GetRenderViewHostImpl();
752
753  FrameTreeNode* FindFrameTreeNodeByID(int64 frame_id);
754
755  // Removes browser plugin embedder if there is one.
756  void RemoveBrowserPluginEmbedder();
757
758  // Clear |render_view_host|'s PowerSaveBlockers.
759  void ClearPowerSaveBlockers(RenderViewHost* render_view_host);
760
761  // Clear all PowerSaveBlockers, leave power_save_blocker_ empty.
762  void ClearAllPowerSaveBlockers();
763
764  // Helper function to invoke WebContentsDelegate::GetSizeForNewRenderView().
765  gfx::Size GetSizeForNewRenderView() const;
766
767  // Data for core operation ---------------------------------------------------
768
769  // Delegate for notifying our owner about stuff. Not owned by us.
770  WebContentsDelegate* delegate_;
771
772  // Handles the back/forward list and loading.
773  NavigationControllerImpl controller_;
774
775  // The corresponding view.
776  scoped_ptr<WebContentsViewPort> view_;
777
778  // The view of the RVHD. Usually this is our WebContentsView implementation,
779  // but if an embedder uses a different WebContentsView, they'll need to
780  // provide this.
781  RenderViewHostDelegateView* render_view_host_delegate_view_;
782
783  // Tracks created WebContentsImpl objects that have not been shown yet. They
784  // are identified by the route ID passed to CreateNewWindow.
785  typedef std::map<int, WebContentsImpl*> PendingContents;
786  PendingContents pending_contents_;
787
788  // These maps hold on to the widgets that we created on behalf of the renderer
789  // that haven't shown yet.
790  typedef std::map<int, RenderWidgetHostView*> PendingWidgetViews;
791  PendingWidgetViews pending_widget_views_;
792
793  typedef std::map<WebContentsImpl*, DestructionObserver*> DestructionObservers;
794  DestructionObservers destruction_observers_;
795
796  // A list of observers notified when page state changes. Weak references.
797  // This MUST be listed above render_manager_ since at destruction time the
798  // latter might cause RenderViewHost's destructor to call us and we might use
799  // the observer list then.
800  ObserverList<WebContentsObserver> observers_;
801
802  // The tab that opened this tab, if any.  Will be set to null if the opener
803  // is closed.
804  WebContentsImpl* opener_;
805
806#if defined(OS_WIN) && defined(USE_AURA)
807  gfx::NativeViewAccessible accessible_parent_;
808#endif
809
810  // Helper classes ------------------------------------------------------------
811
812  // Maps the RenderViewHost to its media_player_cookie and PowerSaveBlocker
813  // pairs. Key is the RenderViewHost, value is the map which maps player_cookie
814  // on to PowerSaveBlocker.
815  typedef std::map<RenderViewHost*, std::map<int64, PowerSaveBlocker*> >
816      PowerSaveBlockerMap;
817  PowerSaveBlockerMap power_save_blockers_;
818
819  // Manages creation and swapping of render views.
820  RenderViewHostManager render_manager_;
821
822#if defined(OS_ANDROID)
823  // Manages injecting Java objects into all RenderViewHosts associated with
824  // this WebContentsImpl.
825  scoped_ptr<JavaBridgeDispatcherHostManager>
826      java_bridge_dispatcher_host_manager_;
827#endif
828
829  // SavePackage, lazily created.
830  scoped_refptr<SavePackage> save_package_;
831
832  // Data for loading state ----------------------------------------------------
833
834  // Indicates whether we're currently loading a resource.
835  bool is_loading_;
836
837  // Indicates if the tab is considered crashed.
838  base::TerminationStatus crashed_status_;
839  int crashed_error_code_;
840
841  // Whether this WebContents is waiting for a first-response for the
842  // main resource of the page. This controls whether the throbber state is
843  // "waiting" or "loading."
844  bool waiting_for_response_;
845
846  // Map of SiteInstance ID to max page ID for this tab. A page ID is specific
847  // to a given tab and SiteInstance, and must be valid for the lifetime of the
848  // WebContentsImpl.
849  std::map<int32, int32> max_page_ids_;
850
851  // System time at which the current load was started.
852  base::TimeTicks current_load_start_;
853
854  // The current load state and the URL associated with it.
855  net::LoadStateWithParam load_state_;
856  string16 load_state_host_;
857  // Upload progress, for displaying in the status bar.
858  // Set to zero when there is no significant upload happening.
859  uint64 upload_size_;
860  uint64 upload_position_;
861
862  // Data for current page -----------------------------------------------------
863
864  // When a title cannot be taken from any entry, this title will be used.
865  string16 page_title_when_no_navigation_entry_;
866
867  // When a navigation occurs, we record its contents MIME type. It can be
868  // used to check whether we can do something for some special contents.
869  std::string contents_mime_type_;
870
871  // Character encoding.
872  std::string encoding_;
873
874  // True if this is a secure page which displayed insecure content.
875  bool displayed_insecure_content_;
876
877  // The frame tree structure of the current page.
878  scoped_ptr<FrameTreeNode> frame_tree_root_;
879
880  // Data for misc internal state ----------------------------------------------
881
882  // When > 0, the WebContents is currently being captured (e.g., for
883  // screenshots or mirroring); and the underlying RenderWidgetHost should not
884  // be told it is hidden.
885  int capturer_count_;
886
887  // Tracks whether RWHV should be visible once capturer_count_ becomes zero.
888  bool should_normally_be_visible_;
889
890  // See getter above.
891  bool is_being_destroyed_;
892
893  // Indicates whether we should notify about disconnection of this
894  // WebContentsImpl. This is used to ensure disconnection notifications only
895  // happen if a connection notification has happened and that they happen only
896  // once.
897  bool notify_disconnection_;
898
899  // Pointer to the JavaScript dialog manager, lazily assigned. Used because the
900  // delegate of this WebContentsImpl is nulled before its destructor is called.
901  JavaScriptDialogManager* dialog_manager_;
902
903  // Set to true when there is an active "before unload" dialog.  When true,
904  // we've forced the throbber to start in Navigate, and we need to remember to
905  // turn it off in OnJavaScriptMessageBoxClosed if the navigation is canceled.
906  bool is_showing_before_unload_dialog_;
907
908  // Settings that get passed to the renderer process.
909  RendererPreferences renderer_preferences_;
910
911  // The time that this tab was last selected.
912  base::TimeTicks last_selected_time_;
913
914  // See description above setter.
915  bool closed_by_user_gesture_;
916
917  // Minimum/maximum zoom percent.
918  int minimum_zoom_percent_;
919  int maximum_zoom_percent_;
920  // If true, the default zoom limits have been overriden for this tab, in which
921  // case we don't want saved settings to apply to it and we don't want to
922  // remember it.
923  bool temporary_zoom_settings_;
924
925  // The intrinsic size of the page.
926  gfx::Size preferred_size_;
927
928#if defined(OS_ANDROID)
929  // Date time chooser opened by this tab.
930  // Only used in Android since all other platforms use a multi field UI.
931  scoped_ptr<DateTimeChooserAndroid> date_time_chooser_;
932#endif
933
934  // Color chooser that was opened by this tab.
935  scoped_ptr<ColorChooser> color_chooser_;
936
937  // A unique identifier for the current color chooser.  Identifiers are unique
938  // across a renderer process.  This avoids race conditions in synchronizing
939  // the browser and renderer processes.  For example, if a renderer closes one
940  // chooser and opens another, and simultaneously the user picks a color in the
941  // first chooser, the IDs can be used to drop the "chose a color" message
942  // rather than erroneously tell the renderer that the user picked a color in
943  // the second chooser.
944  int color_chooser_identifier_;
945
946  // Manages the embedder state for browser plugins, if this WebContents is an
947  // embedder; NULL otherwise.
948  scoped_ptr<BrowserPluginEmbedder> browser_plugin_embedder_;
949  // Manages the guest state for browser plugin, if this WebContents is a guest;
950  // NULL otherwise.
951  scoped_ptr<BrowserPluginGuest> browser_plugin_guest_;
952
953  // This must be at the end, or else we might get notifications and use other
954  // member variables that are gone.
955  NotificationRegistrar registrar_;
956
957  // Used during IPC message dispatching so that the handlers can get a pointer
958  // to the RVH through which the message was received.
959  RenderViewHost* message_source_;
960
961  // All live RenderWidgetHostImpls that are created by this object and may
962  // outlive it.
963  std::set<RenderWidgetHostImpl*> created_widgets_;
964
965  // Routing id of the shown fullscreen widget or MSG_ROUTING_NONE otherwise.
966  int fullscreen_widget_routing_id_;
967
968  // Maps the ids of pending image downloads to their callbacks
969  typedef std::map<int, ImageDownloadCallback> ImageDownloadMap;
970  ImageDownloadMap image_download_map_;
971
972  DISALLOW_COPY_AND_ASSIGN(WebContentsImpl);
973};
974
975}  // namespace content
976
977#endif  // CONTENT_BROWSER_WEB_CONTENTS_WEB_CONTENTS_IMPL_H_
978