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