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