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 "content/public/common/stop_find_action.h" 22 #include "ipc/ipc_sender.h" 23 #include "third_party/skia/include/core/SkColor.h" 24 #include "ui/base/window_open_disposition.h" 25 #include "ui/gfx/native_widget_types.h" 26 #include "ui/gfx/rect.h" 27 28 #if defined(OS_ANDROID) 29 #include "base/android/scoped_java_ref.h" 30 #endif 31 32 namespace base { 33 class DictionaryValue; 34 class TimeTicks; 35 } 36 37 namespace blink { 38 struct WebFindOptions; 39 } 40 41 namespace net { 42 struct LoadStateWithParam; 43 } 44 45 namespace content { 46 47 class BrowserContext; 48 class InterstitialPage; 49 class PageState; 50 class RenderFrameHost; 51 class RenderProcessHost; 52 class RenderViewHost; 53 class RenderWidgetHostView; 54 class SiteInstance; 55 class WebContentsDelegate; 56 struct CustomContextMenuContext; 57 struct DropData; 58 struct RendererPreferences; 59 60 // WebContents is the core class in content/. A WebContents renders web content 61 // (usually HTML) in a rectangular area. 62 // 63 // Instantiating one is simple: 64 // scoped_ptr<content::WebContents> web_contents( 65 // content::WebContents::Create( 66 // content::WebContents::CreateParams(browser_context))); 67 // gfx::NativeView view = web_contents->GetNativeView(); 68 // // |view| is an HWND, NSView*, GtkWidget*, etc.; insert it into the view 69 // // hierarchy wherever it needs to go. 70 // 71 // That's it; go to your kitchen, grab a scone, and chill. WebContents will do 72 // all the multi-process stuff behind the scenes. More details are at 73 // http://www.chromium.org/developers/design-documents/multi-process-architecture . 74 // 75 // Each WebContents has exactly one NavigationController; each 76 // NavigationController belongs to one WebContents. The NavigationController can 77 // be obtained from GetController(), and is used to load URLs into the 78 // WebContents, navigate it backwards/forwards, etc. See navigation_controller.h 79 // for more details. 80 class WebContents : public PageNavigator, 81 public IPC::Sender, 82 public base::SupportsUserData { 83 public: 84 struct CONTENT_EXPORT CreateParams { 85 explicit CreateParams(BrowserContext* context); 86 ~CreateParams(); 87 CreateParams(BrowserContext* context, SiteInstance* site); 88 89 BrowserContext* browser_context; 90 91 // Specifying a SiteInstance here is optional. It can be set to avoid an 92 // extra process swap if the first navigation is expected to require a 93 // privileged process. 94 SiteInstance* site_instance; 95 96 // The opener WebContents is the WebContents that initiated this request, 97 // if any. 98 WebContents* opener; 99 100 // If the opener is suppressed, then the new WebContents doesn't hold a 101 // reference to its opener. 102 bool opener_suppressed; 103 int routing_id; 104 int main_frame_routing_id; 105 106 // Initial size of the new WebContent's view. Can be (0, 0) if not needed. 107 gfx::Size initial_size; 108 109 // True if the contents should be initially hidden. 110 bool initially_hidden; 111 112 // If this instance ID is non-zero then it indicates that this WebContents 113 // should behave as a guest. 114 int guest_instance_id; 115 116 // TODO(fsamuel): This is temporary. Remove this once all guests are created 117 // from the content embedder. 118 scoped_ptr<base::DictionaryValue> guest_extra_params; 119 120 // Used to specify the location context which display the new view should 121 // belong. This can be NULL if not needed. 122 gfx::NativeView context; 123 }; 124 125 // Creates a new WebContents. 126 CONTENT_EXPORT static WebContents* Create(const CreateParams& params); 127 128 // Similar to Create() above but should be used when you need to prepopulate 129 // the SessionStorageNamespaceMap of the WebContents. This can happen if 130 // you duplicate a WebContents, try to reconstitute it from a saved state, 131 // or when you create a new WebContents based on another one (eg., when 132 // servicing a window.open() call). 133 // 134 // You do not want to call this. If you think you do, make sure you completely 135 // understand when SessionStorageNamespace objects should be cloned, why 136 // they should not be shared by multiple WebContents, and what bad things 137 // can happen if you share the object. 138 CONTENT_EXPORT static WebContents* CreateWithSessionStorage( 139 const CreateParams& params, 140 const SessionStorageNamespaceMap& session_storage_namespace_map); 141 142 // Returns a WebContents that wraps the RenderViewHost, or NULL if the 143 // render view host's delegate isn't a WebContents. 144 CONTENT_EXPORT static WebContents* FromRenderViewHost( 145 const RenderViewHost* rvh); 146 147 CONTENT_EXPORT static WebContents* FromRenderFrameHost(RenderFrameHost* rfh); 148 ~WebContents()149 virtual ~WebContents() {} 150 151 // Intrinsic tab state ------------------------------------------------------- 152 153 // Gets/Sets the delegate. 154 virtual WebContentsDelegate* GetDelegate() = 0; 155 virtual void SetDelegate(WebContentsDelegate* delegate) = 0; 156 157 // Gets the controller for this WebContents. 158 virtual NavigationController& GetController() = 0; 159 virtual const NavigationController& GetController() const = 0; 160 161 // Returns the user browser context associated with this WebContents (via the 162 // NavigationController). 163 virtual content::BrowserContext* GetBrowserContext() const = 0; 164 165 // Gets the URL that is currently being displayed, if there is one. 166 // This method is deprecated. DO NOT USE! Pick either |GetVisibleURL| or 167 // |GetLastCommittedURL| as appropriate. 168 virtual const GURL& GetURL() const = 0; 169 170 // Gets the URL currently being displayed in the URL bar, if there is one. 171 // This URL might be a pending navigation that hasn't committed yet, so it is 172 // not guaranteed to match the current page in this WebContents. A typical 173 // example of this is interstitials, which show the URL of the new/loading 174 // page (active) but the security context is of the old page (last committed). 175 virtual const GURL& GetVisibleURL() const = 0; 176 177 // Gets the last committed URL. It represents the current page that is 178 // displayed in this WebContents. It represents the current security 179 // context. 180 virtual const GURL& GetLastCommittedURL() const = 0; 181 182 // Return the currently active RenderProcessHost and RenderViewHost. Each of 183 // these may change over time. 184 virtual RenderProcessHost* GetRenderProcessHost() const = 0; 185 186 // Returns the main frame for the currently active view. 187 virtual RenderFrameHost* GetMainFrame() = 0; 188 189 // Returns the focused frame for the currently active view. 190 virtual RenderFrameHost* GetFocusedFrame() = 0; 191 192 // Calls |on_frame| for each frame in the currently active view. 193 virtual void ForEachFrame( 194 const base::Callback<void(RenderFrameHost*)>& on_frame) = 0; 195 196 // Sends the given IPC to all frames in the currently active view. This is a 197 // convenience method instead of calling ForEach. 198 virtual void SendToAllFrames(IPC::Message* message) = 0; 199 200 // Gets the current RenderViewHost for this tab. 201 virtual RenderViewHost* GetRenderViewHost() const = 0; 202 203 // Gets the current RenderViewHost's routing id. Returns 204 // MSG_ROUTING_NONE when there is no RenderViewHost. 205 virtual int GetRoutingID() const = 0; 206 207 // Returns the currently active RenderWidgetHostView. This may change over 208 // time and can be NULL (during setup and teardown). 209 virtual RenderWidgetHostView* GetRenderWidgetHostView() const = 0; 210 211 // Returns the currently active fullscreen widget. If there is none, returns 212 // NULL. 213 virtual RenderWidgetHostView* GetFullscreenRenderWidgetHostView() const = 0; 214 215 // Create a WebUI page for the given url. In most cases, this doesn't need to 216 // be called by embedders since content will create its own WebUI objects as 217 // necessary. However if the embedder wants to create its own WebUI object and 218 // keep track of it manually, it can use this. 219 virtual WebUI* CreateWebUI(const GURL& url) = 0; 220 221 // Returns the committed WebUI if one exists, otherwise the pending one. 222 virtual WebUI* GetWebUI() const = 0; 223 virtual WebUI* GetCommittedWebUI() const = 0; 224 225 // Allows overriding the user agent used for NavigationEntries it owns. 226 virtual void SetUserAgentOverride(const std::string& override) = 0; 227 virtual const std::string& GetUserAgentOverride() const = 0; 228 229 #if defined(OS_WIN) 230 virtual void SetParentNativeViewAccessible( 231 gfx::NativeViewAccessible accessible_parent) = 0; 232 #endif 233 234 // Tab navigation state ------------------------------------------------------ 235 236 // Returns the current navigation properties, which if a navigation is 237 // pending may be provisional (e.g., the navigation could result in a 238 // download, in which case the URL would revert to what it was previously). 239 virtual const base::string16& GetTitle() const = 0; 240 241 // The max page ID for any page that the current SiteInstance has loaded in 242 // this WebContents. Page IDs are specific to a given SiteInstance and 243 // WebContents, corresponding to a specific RenderView in the renderer. 244 // Page IDs increase with each new page that is loaded by a tab. 245 virtual int32 GetMaxPageID() = 0; 246 247 // The max page ID for any page that the given SiteInstance has loaded in 248 // this WebContents. 249 virtual int32 GetMaxPageIDForSiteInstance(SiteInstance* site_instance) = 0; 250 251 // Returns the SiteInstance associated with the current page. 252 virtual SiteInstance* GetSiteInstance() const = 0; 253 254 // Returns the SiteInstance for the pending navigation, if any. Otherwise 255 // returns the current SiteInstance. 256 virtual SiteInstance* GetPendingSiteInstance() const = 0; 257 258 // Returns whether this WebContents is loading a resource. 259 virtual bool IsLoading() const = 0; 260 261 // Returns whether this WebContents is loading and and the load is to a 262 // different top-level document (rather than being a navigation within the 263 // same document). This being true implies that IsLoading() is also true. 264 virtual bool IsLoadingToDifferentDocument() const = 0; 265 266 // Returns whether this WebContents is waiting for a first-response for the 267 // main resource of the page. 268 virtual bool IsWaitingForResponse() const = 0; 269 270 // Returns the current load state and the URL associated with it. 271 virtual const net::LoadStateWithParam& GetLoadState() const = 0; 272 virtual const base::string16& GetLoadStateHost() const = 0; 273 274 // Returns the upload progress. 275 virtual uint64 GetUploadSize() const = 0; 276 virtual uint64 GetUploadPosition() const = 0; 277 278 // Returns a set of the site URLs currently committed in this tab. 279 virtual std::set<GURL> GetSitesInTab() const = 0; 280 281 // Returns the character encoding of the page. 282 virtual const std::string& GetEncoding() const = 0; 283 284 // True if this is a secure page which displayed insecure content. 285 virtual bool DisplayedInsecureContent() const = 0; 286 287 // Internal state ------------------------------------------------------------ 288 289 // Indicates whether the WebContents is being captured (e.g., for screenshots 290 // or mirroring). Increment calls must be balanced with an equivalent number 291 // of decrement calls. |capture_size| specifies the capturer's video 292 // resolution, but can be empty to mean "unspecified." The first screen 293 // capturer that provides a non-empty |capture_size| will override the value 294 // returned by GetPreferredSize() until all captures have ended. 295 virtual void IncrementCapturerCount(const gfx::Size& capture_size) = 0; 296 virtual void DecrementCapturerCount() = 0; 297 virtual int GetCapturerCount() const = 0; 298 299 // Indicates whether this tab should be considered crashed. The setter will 300 // also notify the delegate when the flag is changed. 301 virtual bool IsCrashed() const = 0; 302 virtual void SetIsCrashed(base::TerminationStatus status, int error_code) = 0; 303 304 virtual base::TerminationStatus GetCrashedStatus() const = 0; 305 306 // Whether the tab is in the process of being destroyed. 307 virtual bool IsBeingDestroyed() const = 0; 308 309 // Convenience method for notifying the delegate of a navigation state 310 // change. See InvalidateType enum. 311 virtual void NotifyNavigationStateChanged(unsigned changed_flags) = 0; 312 313 // Get the last time that the WebContents was made active (either when it was 314 // created or shown with WasShown()). 315 virtual base::TimeTicks GetLastActiveTime() const = 0; 316 317 // Invoked when the WebContents becomes shown/hidden. 318 virtual void WasShown() = 0; 319 virtual void WasHidden() = 0; 320 321 // Returns true if the before unload and unload listeners need to be 322 // fired. The value of this changes over time. For example, if true and the 323 // before unload listener is executed and allows the user to exit, then this 324 // returns false. 325 virtual bool NeedToFireBeforeUnload() = 0; 326 327 // Runs the beforeunload handler for the main frame. See also ClosePage and 328 // SwapOut in RenderViewHost, which run the unload handler. 329 // 330 // |for_cross_site_transition| indicates whether this call is for the current 331 // frame during a cross-process navigation. False means we're closing the 332 // entire tab. 333 // 334 // TODO(creis): We should run the beforeunload handler for every frame that 335 // has one. 336 virtual void DispatchBeforeUnload(bool for_cross_site_transition) = 0; 337 338 // Commands ------------------------------------------------------------------ 339 340 // Stop any pending navigation. 341 virtual void Stop() = 0; 342 343 // Creates a new WebContents with the same state as this one. The returned 344 // heap-allocated pointer is owned by the caller. 345 virtual WebContents* Clone() = 0; 346 347 // Reloads the focused frame. 348 virtual void ReloadFocusedFrame(bool ignore_cache) = 0; 349 350 // Editing commands ---------------------------------------------------------- 351 352 virtual void Undo() = 0; 353 virtual void Redo() = 0; 354 virtual void Cut() = 0; 355 virtual void Copy() = 0; 356 virtual void CopyToFindPboard() = 0; 357 virtual void Paste() = 0; 358 virtual void PasteAndMatchStyle() = 0; 359 virtual void Delete() = 0; 360 virtual void SelectAll() = 0; 361 virtual void Unselect() = 0; 362 363 // Replaces the currently selected word or a word around the cursor. 364 virtual void Replace(const base::string16& word) = 0; 365 366 // Replaces the misspelling in the current selection. 367 virtual void ReplaceMisspelling(const base::string16& word) = 0; 368 369 // Let the renderer know that the menu has been closed. 370 virtual void NotifyContextMenuClosed( 371 const CustomContextMenuContext& context) = 0; 372 373 // Executes custom context menu action that was provided from Blink. 374 virtual void ExecuteCustomContextMenuCommand( 375 int action, const CustomContextMenuContext& context) = 0; 376 377 // Views and focus ----------------------------------------------------------- 378 379 // Returns the native widget that contains the contents of the tab. 380 virtual gfx::NativeView GetNativeView() = 0; 381 382 // Returns the native widget with the main content of the tab (i.e. the main 383 // render view host, though there may be many popups in the tab as children of 384 // the container). 385 virtual gfx::NativeView GetContentNativeView() = 0; 386 387 // Returns the outermost native view. This will be used as the parent for 388 // dialog boxes. 389 virtual gfx::NativeWindow GetTopLevelNativeWindow() = 0; 390 391 // Computes the rectangle for the native widget that contains the contents of 392 // the tab in the screen coordinate system. 393 virtual gfx::Rect GetContainerBounds() = 0; 394 395 // Get the bounds of the View, relative to the parent. 396 virtual gfx::Rect GetViewBounds() = 0; 397 398 // Returns the current drop data, if any. 399 virtual DropData* GetDropData() = 0; 400 401 // Sets focus to the native widget for this tab. 402 virtual void Focus() = 0; 403 404 // Sets focus to the appropriate element when the WebContents is shown the 405 // first time. 406 virtual void SetInitialFocus() = 0; 407 408 // Stores the currently focused view. 409 virtual void StoreFocus() = 0; 410 411 // Restores focus to the last focus view. If StoreFocus has not yet been 412 // invoked, SetInitialFocus is invoked. 413 virtual void RestoreFocus() = 0; 414 415 // Focuses the first (last if |reverse| is true) element in the page. 416 // Invoked when this tab is getting the focus through tab traversal (|reverse| 417 // is true when using Shift-Tab). 418 virtual void FocusThroughTabTraversal(bool reverse) = 0; 419 420 // Interstitials ------------------------------------------------------------- 421 422 // Various other systems need to know about our interstitials. 423 virtual bool ShowingInterstitialPage() const = 0; 424 425 // Returns the currently showing interstitial, NULL if no interstitial is 426 // showing. 427 virtual InterstitialPage* GetInterstitialPage() const = 0; 428 429 // Misc state & callbacks ---------------------------------------------------- 430 431 // Check whether we can do the saving page operation this page given its MIME 432 // type. 433 virtual bool IsSavable() = 0; 434 435 // Prepare for saving the current web page to disk. 436 virtual void OnSavePage() = 0; 437 438 // Save page with the main HTML file path, the directory for saving resources, 439 // and the save type: HTML only or complete web page. Returns true if the 440 // saving process has been initiated successfully. 441 virtual bool SavePage(const base::FilePath& main_file, 442 const base::FilePath& dir_path, 443 SavePageType save_type) = 0; 444 445 // Saves the given frame's URL to the local filesystem.. 446 virtual void SaveFrame(const GURL& url, 447 const Referrer& referrer) = 0; 448 449 // Generate an MHTML representation of the current page in the given file. 450 virtual void GenerateMHTML( 451 const base::FilePath& file, 452 const base::Callback<void( 453 int64 /* size of the file */)>& callback) = 0; 454 455 // Returns the contents MIME type after a navigation. 456 virtual const std::string& GetContentsMimeType() const = 0; 457 458 // Returns true if this WebContents will notify about disconnection. 459 virtual bool WillNotifyDisconnection() const = 0; 460 461 // Override the encoding and reload the page by sending down 462 // ViewMsg_SetPageEncoding to the renderer. |UpdateEncoding| is kinda 463 // the opposite of this, by which 'browser' is notified of 464 // the encoding of the current tab from 'renderer' (determined by 465 // auto-detect, http header, meta, bom detection, etc). 466 virtual void SetOverrideEncoding(const std::string& encoding) = 0; 467 468 // Remove any user-defined override encoding and reload by sending down 469 // ViewMsg_ResetPageEncodingToDefault to the renderer. 470 virtual void ResetOverrideEncoding() = 0; 471 472 // Returns the settings which get passed to the renderer. 473 virtual content::RendererPreferences* GetMutableRendererPrefs() = 0; 474 475 // Tells the tab to close now. The tab will take care not to close until it's 476 // out of nested message loops. 477 virtual void Close() = 0; 478 479 // A render view-originated drag has ended. Informs the render view host and 480 // WebContentsDelegate. 481 virtual void SystemDragEnded() = 0; 482 483 // Notification the user has made a gesture while focus was on the 484 // page. This is used to avoid uninitiated user downloads (aka carpet 485 // bombing), see DownloadRequestLimiter for details. 486 virtual void UserGestureDone() = 0; 487 488 // Indicates if this tab was explicitly closed by the user (control-w, close 489 // tab menu item...). This is false for actions that indirectly close the tab, 490 // such as closing the window. The setter is maintained by TabStripModel, and 491 // the getter only useful from within TAB_CLOSED notification 492 virtual void SetClosedByUserGesture(bool value) = 0; 493 virtual bool GetClosedByUserGesture() const = 0; 494 495 // Gets the zoom percent for this tab. 496 virtual int GetZoomPercent(bool* enable_increment, 497 bool* enable_decrement) const = 0; 498 499 // Opens view-source tab for this contents. 500 virtual void ViewSource() = 0; 501 502 virtual void ViewFrameSource(const GURL& url, 503 const PageState& page_state)= 0; 504 505 // Gets the minimum/maximum zoom percent. 506 virtual int GetMinimumZoomPercent() const = 0; 507 virtual int GetMaximumZoomPercent() const = 0; 508 509 // Gets the preferred size of the contents. 510 virtual gfx::Size GetPreferredSize() const = 0; 511 512 // Called when the reponse to a pending mouse lock request has arrived. 513 // Returns true if |allowed| is true and the mouse has been successfully 514 // locked. 515 virtual bool GotResponseToLockMouseRequest(bool allowed) = 0; 516 517 // Called when the user has selected a color in the color chooser. 518 virtual void DidChooseColorInColorChooser(SkColor color) = 0; 519 520 // Called when the color chooser has ended. 521 virtual void DidEndColorChooser() = 0; 522 523 // Returns true if the location bar should be focused by default rather than 524 // the page contents. The view calls this function when the tab is focused 525 // to see what it should do. 526 virtual bool FocusLocationBarByDefault() = 0; 527 528 // Does this have an opener associated with it? 529 virtual bool HasOpener() const = 0; 530 531 typedef base::Callback<void( 532 int, /* id */ 533 int, /* HTTP status code */ 534 const GURL&, /* image_url */ 535 const std::vector<SkBitmap>&, /* bitmaps */ 536 /* The sizes in pixel of the bitmaps before they were resized due to the 537 max bitmap size passed to DownloadImage(). Each entry in the bitmaps 538 vector corresponds to an entry in the sizes vector. If a bitmap was 539 resized, there should be a single returned bitmap. */ 540 const std::vector<gfx::Size>&)> 541 ImageDownloadCallback; 542 543 // Sends a request to download the given image |url| and returns the unique 544 // id of the download request. When the download is finished, |callback| will 545 // be called with the bitmaps received from the renderer. If |is_favicon| is 546 // true, the cookies are not sent and not accepted during download. 547 // Bitmaps with pixel sizes larger than |max_bitmap_size| are filtered out 548 // from the bitmap results. If there are no bitmap results <= 549 // |max_bitmap_size|, the smallest bitmap is resized to |max_bitmap_size| and 550 // is the only result. A |max_bitmap_size| of 0 means unlimited. 551 virtual int DownloadImage(const GURL& url, 552 bool is_favicon, 553 uint32_t max_bitmap_size, 554 const ImageDownloadCallback& callback) = 0; 555 556 // Returns true if the WebContents is responsible for displaying a subframe 557 // in a different process from its parent page. 558 // TODO: this doesn't really belong here. With site isolation, this should be 559 // removed since we can then embed iframes in different processes. 560 virtual bool IsSubframe() const = 0; 561 562 // Finds text on a page. 563 virtual void Find(int request_id, 564 const base::string16& search_text, 565 const blink::WebFindOptions& options) = 0; 566 567 // Notifies the renderer that the user has closed the FindInPage window 568 // (and what action to take regarding the selection). 569 virtual void StopFinding(StopFindAction action) = 0; 570 571 // Requests the renderer to insert CSS into the main frame's document. 572 virtual void InsertCSS(const std::string& css) = 0; 573 574 #if defined(OS_ANDROID) 575 CONTENT_EXPORT static WebContents* FromJavaWebContents( 576 jobject jweb_contents_android); 577 virtual base::android::ScopedJavaLocalRef<jobject> GetJavaWebContents() = 0; 578 #elif defined(OS_MACOSX) 579 // The web contents view assumes that its view will never be overlapped by 580 // another view (either partially or fully). This allows it to perform 581 // optimizations. If the view is in a view hierarchy where it might be 582 // overlapped by another view, notify the view by calling this with |true|. 583 virtual void SetAllowOverlappingViews(bool overlapping) = 0; 584 585 // Returns true if overlapping views are allowed, false otherwise. 586 virtual bool GetAllowOverlappingViews() = 0; 587 588 // To draw two overlapping web contents view, the underlaying one should 589 // know about the overlaying one. Caller must ensure that |overlay| exists 590 // until |RemoveOverlayView| is called. 591 virtual void SetOverlayView(WebContents* overlay, 592 const gfx::Point& offset) = 0; 593 594 // Removes the previously set overlay view. 595 virtual void RemoveOverlayView() = 0; 596 #endif // OS_ANDROID 597 598 private: 599 // This interface should only be implemented inside content. 600 friend class WebContentsImpl; WebContents()601 WebContents() {} 602 }; 603 604 } // namespace content 605 606 #endif // CONTENT_PUBLIC_BROWSER_WEB_CONTENTS_H_ 607