web_contents.h revision 868fa2fe829687343ffae624259930155e16dbd8
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_PUBLIC_BROWSER_WEB_CONTENTS_H_
6#define CONTENT_PUBLIC_BROWSER_WEB_CONTENTS_H_
7
8#include "base/basictypes.h"
9#include "base/callback_forward.h"
10#include "base/process_util.h"
11#include "base/string16.h"
12#include "base/supports_user_data.h"
13#include "content/common/content_export.h"
14#include "content/public/browser/navigation_controller.h"
15#include "content/public/browser/page_navigator.h"
16#include "content/public/browser/save_page_type.h"
17#include "content/public/browser/web_ui.h"
18#include "ipc/ipc_sender.h"
19#include "third_party/skia/include/core/SkColor.h"
20#include "ui/base/window_open_disposition.h"
21#include "ui/gfx/native_widget_types.h"
22#include "ui/gfx/size.h"
23
24namespace base {
25class TimeTicks;
26}
27
28namespace gfx {
29class Rect;
30class Size;
31}
32
33namespace net {
34struct LoadStateWithParam;
35}
36
37namespace content {
38
39class BrowserContext;
40class InterstitialPage;
41class PageState;
42class RenderProcessHost;
43class RenderViewHost;
44class RenderWidgetHostView;
45class SiteInstance;
46class WebContentsDelegate;
47class WebContentsView;
48struct RendererPreferences;
49
50// WebContents is the core class in content/. A WebContents renders web content
51// (usually HTML) in a rectangular area.
52//
53// Instantiating one is simple:
54//   scoped_ptr<content::WebContents> web_contents(
55//       content::WebContents::Create(
56//           content::WebContents::CreateParams(browser_context)));
57//   gfx::NativeView view = web_contents->GetView()->GetNativeView();
58//   // |view| is an HWND, NSView*, GtkWidget*, etc.; insert it into the view
59//   // hierarchy wherever it needs to go.
60//
61// That's it; go to your kitchen, grab a scone, and chill. WebContents will do
62// all the multi-process stuff behind the scenes. More details are at
63// http://www.chromium.org/developers/design-documents/multi-process-architecture .
64//
65// Each WebContents has exactly one NavigationController; each
66// NavigationController belongs to one WebContents. The NavigationController can
67// be obtained from GetController(), and is used to load URLs into the
68// WebContents, navigate it backwards/forwards, etc. See navigation_controller.h
69// for more details.
70class WebContents : public PageNavigator,
71                    public IPC::Sender,
72                    public base::SupportsUserData {
73 public:
74  struct CONTENT_EXPORT CreateParams {
75    explicit CreateParams(BrowserContext* context);
76    CreateParams(BrowserContext* context, SiteInstance* site);
77
78    BrowserContext* browser_context;
79    SiteInstance* site_instance;
80    int routing_id;
81    int main_frame_routing_id;
82
83    // Initial size of the new WebContent's view. Can be (0, 0) if not needed.
84    gfx::Size initial_size;
85
86    // Used to specify the location context which display the new view should
87    // belong. This can be NULL if not needed.
88    gfx::NativeView context;
89  };
90
91  // Creates a new WebContents.
92  CONTENT_EXPORT static WebContents* Create(const CreateParams& params);
93
94  // Similar to Create() above but should be used when you need to prepopulate
95  // the SessionStorageNamespaceMap of the WebContents. This can happen if
96  // you duplicate a WebContents, try to reconstitute it from a saved state,
97  // or when you create a new WebContents based on another one (eg., when
98  // servicing a window.open() call).
99  //
100  // You do not want to call this. If you think you do, make sure you completely
101  // understand when SessionStorageNamespace objects should be cloned, why
102  // they should not be shared by multiple WebContents, and what bad things
103  // can happen if you share the object.
104  CONTENT_EXPORT static WebContents* CreateWithSessionStorage(
105      const CreateParams& params,
106      const SessionStorageNamespaceMap& session_storage_namespace_map);
107
108  // Adds/removes a callback called on creation of each new WebContents.
109  typedef base::Callback<void(WebContents*)> CreatedCallback;
110  CONTENT_EXPORT static void AddCreatedCallback(
111      const CreatedCallback& callback);
112  CONTENT_EXPORT static void RemoveCreatedCallback(
113      const CreatedCallback& callback);
114
115  // Returns a WebContents that wraps the RenderViewHost, or NULL if the
116  // render view host's delegate isn't a WebContents.
117  CONTENT_EXPORT static WebContents* FromRenderViewHost(
118      const RenderViewHost* rvh);
119
120  virtual ~WebContents() {}
121
122  // Intrinsic tab state -------------------------------------------------------
123
124  // Gets/Sets the delegate.
125  virtual WebContentsDelegate* GetDelegate() = 0;
126  virtual void SetDelegate(WebContentsDelegate* delegate) = 0;
127
128  // Gets the controller for this WebContents.
129  virtual NavigationController& GetController() = 0;
130  virtual const NavigationController& GetController() const = 0;
131
132  // Returns the user browser context associated with this WebContents (via the
133  // NavigationController).
134  virtual content::BrowserContext* GetBrowserContext() const = 0;
135
136  // Gets the URL that is currently being displayed, if there is one.
137  // This method is deprecated. DO NOT USE! Pick either |GetActiveURL| or
138  // |GetLastCommittedURL| as appropriate.
139  virtual const GURL& GetURL() const = 0;
140
141  // Gets the URL currently being displayed in the URL bar, if there is one.
142  // This URL might be a pending navigation that hasn't committed yet, so it is
143  // not guaranteed to match the current page in this WebContents. A typical
144  // example of this is interstitials, which show the URL of the new/loading
145  // page (active) but the security context is of the old page (last committed).
146  virtual const GURL& GetActiveURL() const = 0;
147
148  // Gets the last committed URL. It represents the current page that is
149  // displayed in  this WebContents. It represents the current security
150  // context.
151  virtual const GURL& GetLastCommittedURL() const = 0;
152
153  // Return the currently active RenderProcessHost and RenderViewHost. Each of
154  // these may change over time.
155  virtual RenderProcessHost* GetRenderProcessHost() const = 0;
156
157  // Gets the current RenderViewHost for this tab.
158  virtual RenderViewHost* GetRenderViewHost() const = 0;
159
160  typedef base::Callback<void(RenderViewHost* /* render_view_host */,
161                              int /* x */,
162                              int /* y */)> GetRenderViewHostCallback;
163  // Gets the RenderViewHost at coordinates (|x|, |y|) for this WebContents via
164  // |callback|.
165  // This can be different than the current RenderViewHost if there is a
166  // BrowserPlugin at the specified position.
167  virtual void GetRenderViewHostAtPosition(
168      int x,
169      int y,
170      const GetRenderViewHostCallback& callback) = 0;
171
172  // Returns the WebContents embedding this WebContents, if any.
173  // If this is a top-level WebContents then it returns NULL.
174  virtual WebContents* GetEmbedderWebContents() const = 0;
175
176  // Gets the instance ID of the current WebContents if it is embedded
177  // within a BrowserPlugin. The instance ID of a WebContents uniquely
178  // identifies it within its embedder WebContents.
179  virtual int GetEmbeddedInstanceID() const = 0;
180
181  // Gets the current RenderViewHost's routing id. Returns
182  // MSG_ROUTING_NONE when there is no RenderViewHost.
183  virtual int GetRoutingID() const = 0;
184
185  // Returns the currently active RenderWidgetHostView. This may change over
186  // time and can be NULL (during setup and teardown).
187  virtual content::RenderWidgetHostView* GetRenderWidgetHostView() const = 0;
188
189  // The WebContentsView will never change and is guaranteed non-NULL.
190  virtual WebContentsView* GetView() const = 0;
191
192  // Create a WebUI page for the given url. In most cases, this doesn't need to
193  // be called by embedders since content will create its own WebUI objects as
194  // necessary. However if the embedder wants to create its own WebUI object and
195  // keep track of it manually, it can use this.
196  virtual WebUI* CreateWebUI(const GURL& url) = 0;
197
198  // Returns the committed WebUI if one exists, otherwise the pending one.
199  virtual WebUI* GetWebUI() const = 0;
200  virtual WebUI* GetCommittedWebUI() const = 0;
201
202  // Allows overriding the user agent used for NavigationEntries it owns.
203  virtual void SetUserAgentOverride(const std::string& override) = 0;
204  virtual const std::string& GetUserAgentOverride() const = 0;
205
206#if defined(OS_WIN) && defined(USE_AURA)
207  virtual void SetParentNativeViewAccessible(
208      gfx::NativeViewAccessible accessible_parent) = 0;
209#endif
210
211  // Tab navigation state ------------------------------------------------------
212
213  // Returns the current navigation properties, which if a navigation is
214  // pending may be provisional (e.g., the navigation could result in a
215  // download, in which case the URL would revert to what it was previously).
216  virtual const string16& GetTitle() const = 0;
217
218  // The max page ID for any page that the current SiteInstance has loaded in
219  // this WebContents.  Page IDs are specific to a given SiteInstance and
220  // WebContents, corresponding to a specific RenderView in the renderer.
221  // Page IDs increase with each new page that is loaded by a tab.
222  virtual int32 GetMaxPageID() = 0;
223
224  // The max page ID for any page that the given SiteInstance has loaded in
225  // this WebContents.
226  virtual int32 GetMaxPageIDForSiteInstance(SiteInstance* site_instance) = 0;
227
228  // Returns the SiteInstance associated with the current page.
229  virtual SiteInstance* GetSiteInstance() const = 0;
230
231  // Returns the SiteInstance for the pending navigation, if any.  Otherwise
232  // returns the current SiteInstance.
233  virtual SiteInstance* GetPendingSiteInstance() const = 0;
234
235  // Return whether this WebContents is loading a resource.
236  virtual bool IsLoading() const = 0;
237
238  // Returns whether this WebContents is waiting for a first-response for the
239  // main resource of the page.
240  virtual bool IsWaitingForResponse() const = 0;
241
242  // Return the current load state and the URL associated with it.
243  virtual const net::LoadStateWithParam& GetLoadState() const = 0;
244  virtual const string16& GetLoadStateHost() const = 0;
245
246  // Return the upload progress.
247  virtual uint64 GetUploadSize() const = 0;
248  virtual uint64 GetUploadPosition() const = 0;
249
250  // Return the character encoding of the page.
251  virtual const std::string& GetEncoding() const = 0;
252
253  // True if this is a secure page which displayed insecure content.
254  virtual bool DisplayedInsecureContent() const = 0;
255
256  // Internal state ------------------------------------------------------------
257
258  // Indicates whether the WebContents is being captured (e.g., for screenshots
259  // or mirroring).  Increment calls must be balanced with an equivalent number
260  // of decrement calls.
261  virtual void IncrementCapturerCount() = 0;
262  virtual void DecrementCapturerCount() = 0;
263
264  // Indicates whether this tab should be considered crashed. The setter will
265  // also notify the delegate when the flag is changed.
266  virtual bool IsCrashed() const  = 0;
267  virtual void SetIsCrashed(base::TerminationStatus status, int error_code) = 0;
268
269  virtual base::TerminationStatus GetCrashedStatus() const = 0;
270
271  // Whether the tab is in the process of being destroyed.
272  virtual bool IsBeingDestroyed() const = 0;
273
274  // Convenience method for notifying the delegate of a navigation state
275  // change. See InvalidateType enum.
276  virtual void NotifyNavigationStateChanged(unsigned changed_flags) = 0;
277
278  // Get the last time that the WebContents was made visible with WasShown()
279  virtual base::TimeTicks GetLastSelectedTime() const = 0;
280
281  // Invoked when the WebContents becomes shown/hidden.
282  virtual void WasShown() = 0;
283  virtual void WasHidden() = 0;
284
285  // Returns true if the before unload and unload listeners need to be
286  // fired. The value of this changes over time. For example, if true and the
287  // before unload listener is executed and allows the user to exit, then this
288  // returns false.
289  virtual bool NeedToFireBeforeUnload() = 0;
290
291  // Commands ------------------------------------------------------------------
292
293  // Stop any pending navigation.
294  virtual void Stop() = 0;
295
296  // Creates a new WebContents with the same state as this one. The returned
297  // heap-allocated pointer is owned by the caller.
298  virtual WebContents* Clone() = 0;
299
300  // Views and focus -----------------------------------------------------------
301  // Focuses the first (last if |reverse| is true) element in the page.
302  // Invoked when this tab is getting the focus through tab traversal (|reverse|
303  // is true when using Shift-Tab).
304  virtual void FocusThroughTabTraversal(bool reverse) = 0;
305
306  // Interstitials -------------------------------------------------------------
307
308  // Various other systems need to know about our interstitials.
309  virtual bool ShowingInterstitialPage() const = 0;
310
311  // Returns the currently showing interstitial, NULL if no interstitial is
312  // showing.
313  virtual InterstitialPage* GetInterstitialPage() const = 0;
314
315  // Misc state & callbacks ----------------------------------------------------
316
317  // Check whether we can do the saving page operation this page given its MIME
318  // type.
319  virtual bool IsSavable() = 0;
320
321  // Prepare for saving the current web page to disk.
322  virtual void OnSavePage() = 0;
323
324  // Save page with the main HTML file path, the directory for saving resources,
325  // and the save type: HTML only or complete web page. Returns true if the
326  // saving process has been initiated successfully.
327  virtual bool SavePage(const base::FilePath& main_file,
328                        const base::FilePath& dir_path,
329                        SavePageType save_type) = 0;
330
331  // Generate an MHTML representation of the current page in the given file.
332  virtual void GenerateMHTML(
333      const base::FilePath& file,
334      const base::Callback<void(
335          const base::FilePath& /* path to the MHTML file */,
336          int64 /* size of the file */)>& callback) = 0;
337
338  // Returns true if the active NavigationEntry's page_id equals page_id.
339  virtual bool IsActiveEntry(int32 page_id) = 0;
340
341  // Returns the contents MIME type after a navigation.
342  virtual const std::string& GetContentsMimeType() const = 0;
343
344  // Returns true if this WebContents will notify about disconnection.
345  virtual bool WillNotifyDisconnection() const = 0;
346
347  // Override the encoding and reload the page by sending down
348  // ViewMsg_SetPageEncoding to the renderer. |UpdateEncoding| is kinda
349  // the opposite of this, by which 'browser' is notified of
350  // the encoding of the current tab from 'renderer' (determined by
351  // auto-detect, http header, meta, bom detection, etc).
352  virtual void SetOverrideEncoding(const std::string& encoding) = 0;
353
354  // Remove any user-defined override encoding and reload by sending down
355  // ViewMsg_ResetPageEncodingToDefault to the renderer.
356  virtual void ResetOverrideEncoding() = 0;
357
358  // Returns the settings which get passed to the renderer.
359  virtual content::RendererPreferences* GetMutableRendererPrefs() = 0;
360
361  // Set the time when we started to create the new tab page.  This time is
362  // from before we created this WebContents.
363  virtual void SetNewTabStartTime(const base::TimeTicks& time) = 0;
364  virtual base::TimeTicks GetNewTabStartTime() const = 0;
365
366  // Tells the tab to close now. The tab will take care not to close until it's
367  // out of nested message loops.
368  virtual void Close() = 0;
369
370  // Notification that tab closing has started.  This can be called multiple
371  // times, subsequent calls are ignored.
372  virtual void OnCloseStarted() = 0;
373
374  // Notification that tab closing was cancelled. This can happen when a user
375  // cancels a window close via another tab's beforeunload dialog.
376  virtual void OnCloseCanceled() = 0;
377
378  // Set the time during close when unload is started. Normally, this is set
379  // after the beforeunload dialog. However, for a window close, it is set
380  // after all the beforeunload dialogs have finished.
381  virtual void OnUnloadStarted() = 0;
382
383  // Set the time during close when the tab is no longer visible.
384  virtual void OnUnloadDetachedStarted() = 0;
385
386  // A render view-originated drag has ended. Informs the render view host and
387  // WebContentsDelegate.
388  virtual void SystemDragEnded() = 0;
389
390  // Notification the user has made a gesture while focus was on the
391  // page. This is used to avoid uninitiated user downloads (aka carpet
392  // bombing), see DownloadRequestLimiter for details.
393  virtual void UserGestureDone() = 0;
394
395  // Indicates if this tab was explicitly closed by the user (control-w, close
396  // tab menu item...). This is false for actions that indirectly close the tab,
397  // such as closing the window.  The setter is maintained by TabStripModel, and
398  // the getter only useful from within TAB_CLOSED notification
399  virtual void SetClosedByUserGesture(bool value) = 0;
400  virtual bool GetClosedByUserGesture() const = 0;
401
402  // Gets the zoom level for this tab.
403  virtual double GetZoomLevel() const = 0;
404
405  // Gets the zoom percent for this tab.
406  virtual int GetZoomPercent(bool* enable_increment,
407                             bool* enable_decrement) const = 0;
408
409  // Opens view-source tab for this contents.
410  virtual void ViewSource() = 0;
411
412  virtual void ViewFrameSource(const GURL& url,
413                               const PageState& page_state)= 0;
414
415  // Gets the minimum/maximum zoom percent.
416  virtual int GetMinimumZoomPercent() const = 0;
417  virtual int GetMaximumZoomPercent() const = 0;
418
419  // Gets the preferred size of the contents.
420  virtual gfx::Size GetPreferredSize() const = 0;
421
422  // Get the content restrictions (see content::ContentRestriction).
423  virtual int GetContentRestrictions() const = 0;
424
425  // Called when the reponse to a pending mouse lock request has arrived.
426  // Returns true if |allowed| is true and the mouse has been successfully
427  // locked.
428  virtual bool GotResponseToLockMouseRequest(bool allowed) = 0;
429
430  // Called when the user has selected a color in the color chooser.
431  virtual void DidChooseColorInColorChooser(SkColor color) = 0;
432
433  // Called when the color chooser has ended.
434  virtual void DidEndColorChooser() = 0;
435
436  // Returns true if the location bar should be focused by default rather than
437  // the page contents. The view calls this function when the tab is focused
438  // to see what it should do.
439  virtual bool FocusLocationBarByDefault() = 0;
440
441  // Does this have an opener associated with it?
442  virtual bool HasOpener() const = 0;
443
444  typedef base::Callback<void(int, /* id */
445                              int, /* HTTP status code */
446                              const GURL&, /* image_url */
447                              int,  /* requested_size */
448                              const std::vector<SkBitmap>& /* bitmaps*/)>
449      ImageDownloadCallback;
450
451  // Sends a request to download the given image |url| and returns the unique
452  // id of the download request. When the download is finished, |callback| will
453  // be called with the bitmaps received from the renderer. If |is_favicon| is
454  // true, the cookies are not sent and not accepted during download. Note that
455  // |image_size| is a hint for images with multiple sizes. The downloaded image
456  // is not resized to the given image_size. If 0 is passed, the first frame of
457  // the image is returned.
458  virtual int DownloadImage(const GURL& url,
459                            bool is_favicon,
460                            int image_size,
461                            const ImageDownloadCallback& callback) = 0;
462
463 private:
464  // This interface should only be implemented inside content.
465  friend class WebContentsImpl;
466  WebContents() {}
467};
468
469}  // namespace content
470
471#endif  // CONTENT_PUBLIC_BROWSER_WEB_CONTENTS_H_
472