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