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