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