• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_DELEGATE_H_
6 #define CONTENT_PUBLIC_BROWSER_WEB_CONTENTS_DELEGATE_H_
7 
8 #include <set>
9 #include <string>
10 
11 #include "base/basictypes.h"
12 #include "base/callback.h"
13 #include "base/strings/string16.h"
14 #include "content/common/content_export.h"
15 #include "content/public/browser/navigation_type.h"
16 #include "content/public/common/media_stream_request.h"
17 #include "content/public/common/page_transition_types.h"
18 #include "content/public/common/window_container_type.h"
19 #include "third_party/WebKit/public/web/WebDragOperation.h"
20 #include "third_party/skia/include/core/SkColor.h"
21 #include "ui/base/window_open_disposition.h"
22 #include "ui/gfx/native_widget_types.h"
23 #include "ui/gfx/rect_f.h"
24 
25 class GURL;
26 
27 namespace base {
28 class FilePath;
29 class ListValue;
30 }
31 
32 namespace content {
33 class BrowserContext;
34 class ColorChooser;
35 class DownloadItem;
36 class JavaScriptDialogManager;
37 class PageState;
38 class RenderViewHost;
39 class SessionStorageNamespace;
40 class WebContents;
41 class WebContentsImpl;
42 struct ColorSuggestion;
43 struct ContextMenuParams;
44 struct DropData;
45 struct FileChooserParams;
46 struct NativeWebKeyboardEvent;
47 struct Referrer;
48 struct SSLStatus;
49 }
50 
51 namespace gfx {
52 class Point;
53 class Rect;
54 class Size;
55 }
56 
57 namespace blink {
58 class WebLayer;
59 struct WebWindowFeatures;
60 }
61 
62 namespace content {
63 
64 struct OpenURLParams;
65 
66 // Objects implement this interface to get notified about changes in the
67 // WebContents and to provide necessary functionality.
68 class CONTENT_EXPORT WebContentsDelegate {
69  public:
70   WebContentsDelegate();
71 
72   // Opens a new URL inside the passed in WebContents (if source is 0 open
73   // in the current front-most tab), unless |disposition| indicates the url
74   // should be opened in a new tab or window.
75   //
76   // A NULL source indicates the current tab (callers should probably use
77   // OpenURL() for these cases which does it for you).
78 
79   // Returns the WebContents the URL is opened in, or NULL if the URL wasn't
80   // opened immediately.
81   virtual WebContents* OpenURLFromTab(WebContents* source,
82                                       const OpenURLParams& params);
83 
84   // Called to inform the delegate that the WebContents's navigation state
85   // changed. The |changed_flags| indicates the parts of the navigation state
86   // that have been updated, and is any combination of the
87   // |WebContents::InvalidateTypes| bits.
NavigationStateChanged(const WebContents * source,unsigned changed_flags)88   virtual void NavigationStateChanged(const WebContents* source,
89                                       unsigned changed_flags) {}
90 
91   // Adds the navigation request headers to |headers|. Use
92   // net::HttpUtil::AppendHeaderIfMissing to build the set of headers.
AddNavigationHeaders(const GURL & url,std::string * headers)93   virtual void AddNavigationHeaders(const GURL& url, std::string* headers) {}
94 
95   // Creates a new tab with the already-created WebContents 'new_contents'.
96   // The window for the added contents should be reparented correctly when this
97   // method returns.  If |disposition| is NEW_POPUP, |initial_pos| should hold
98   // the initial position. If |was_blocked| is non-NULL, then |*was_blocked|
99   // will be set to true if the popup gets blocked, and left unchanged
100   // otherwise.
AddNewContents(WebContents * source,WebContents * new_contents,WindowOpenDisposition disposition,const gfx::Rect & initial_pos,bool user_gesture,bool * was_blocked)101   virtual void AddNewContents(WebContents* source,
102                               WebContents* new_contents,
103                               WindowOpenDisposition disposition,
104                               const gfx::Rect& initial_pos,
105                               bool user_gesture,
106                               bool* was_blocked) {}
107 
108   // Selects the specified contents, bringing its container to the front.
ActivateContents(WebContents * contents)109   virtual void ActivateContents(WebContents* contents) {}
110 
111   // Deactivates the specified contents by deactivating its container and
112   // potentialy moving it to the back of the Z order.
DeactivateContents(WebContents * contents)113   virtual void DeactivateContents(WebContents* contents) {}
114 
115   // Notifies the delegate that this contents is starting or is done loading
116   // some resource. The delegate should use this notification to represent
117   // loading feedback. See WebContents::IsLoading()
LoadingStateChanged(WebContents * source)118   virtual void LoadingStateChanged(WebContents* source) {}
119 
120   // Notifies the delegate that the page has made some progress loading.
121   // |progress| is a value between 0.0 (nothing loaded) to 1.0 (page fully
122   // loaded).
LoadProgressChanged(WebContents * source,double progress)123   virtual void LoadProgressChanged(WebContents* source,
124                                    double progress) {}
125 
126   // Request the delegate to close this web contents, and do whatever cleanup
127   // it needs to do.
CloseContents(WebContents * source)128   virtual void CloseContents(WebContents* source) {}
129 
130   // Informs the delegate that the underlying RenderViewHost has been swapped
131   // out so it can perform any cleanup necessary.
SwappedOut(WebContents * source)132   virtual void SwappedOut(WebContents* source) {}
133 
134   // Request the delegate to move this WebContents to the specified position
135   // in screen coordinates.
MoveContents(WebContents * source,const gfx::Rect & pos)136   virtual void MoveContents(WebContents* source, const gfx::Rect& pos) {}
137 
138   // Called to determine if the WebContents is contained in a popup window
139   // or a panel window.
140   virtual bool IsPopupOrPanel(const WebContents* source) const;
141 
142   // Notification that the target URL has changed.
UpdateTargetURL(WebContents * source,int32 page_id,const GURL & url)143   virtual void UpdateTargetURL(WebContents* source,
144                                int32 page_id,
145                                const GURL& url) {}
146 
147   // Notification that there was a mouse event, along with the absolute
148   // coordinates of the mouse pointer and whether it was a normal motion event
149   // (otherwise, the pointer left the contents area).
ContentsMouseEvent(WebContents * source,const gfx::Point & location,bool motion)150   virtual void ContentsMouseEvent(WebContents* source,
151                                   const gfx::Point& location,
152                                   bool motion) {}
153 
154   // Request the delegate to change the zoom level of the current tab.
ContentsZoomChange(bool zoom_in)155   virtual void ContentsZoomChange(bool zoom_in) {}
156 
157   // Called to determine if the WebContents can be overscrolled with touch/wheel
158   // gestures.
159   virtual bool CanOverscrollContent() const;
160 
161   // Callback that allows vertical overscroll activies to be communicated to the
162   // delegate.
OverscrollUpdate(int delta_y)163   virtual void OverscrollUpdate(int delta_y) {}
164 
165   // Check whether this contents is permitted to load data URLs in WebUI mode.
166   // This is normally disallowed for security.
167   virtual bool CanLoadDataURLsInWebUI() const;
168 
169   // Return the rect where to display the resize corner, if any, otherwise
170   // an empty rect.
171   virtual gfx::Rect GetRootWindowResizerRect() const;
172 
173   // Invoked prior to showing before unload handler confirmation dialog.
WillRunBeforeUnloadConfirm()174   virtual void WillRunBeforeUnloadConfirm() {}
175 
176   // Returns true if javascript dialogs and unload alerts are suppressed.
177   // Default is false.
178   virtual bool ShouldSuppressDialogs();
179 
180   // Add a message to the console. Returning true indicates that the delegate
181   // handled the message. If false is returned the default logging mechanism
182   // will be used for the message.
183   virtual bool AddMessageToConsole(WebContents* source,
184                                    int32 level,
185                                    const base::string16& message,
186                                    int32 line_no,
187                                    const base::string16& source_id);
188 
189   // Tells us that we've finished firing this tab's beforeunload event.
190   // The proceed bool tells us whether the user chose to proceed closing the
191   // tab. Returns true if the tab can continue on firing its unload event.
192   // If we're closing the entire browser, then we'll want to delay firing
193   // unload events until all the beforeunload events have fired.
194   virtual void BeforeUnloadFired(WebContents* tab,
195                                  bool proceed,
196                                  bool* proceed_to_fire_unload);
197 
198   // Returns true if the location bar should be focused by default rather than
199   // the page contents. NOTE: this is only used if WebContents can't determine
200   // for itself whether the location bar should be focused by default. For a
201   // complete check, you should use WebContents::FocusLocationBarByDefault().
202   virtual bool ShouldFocusLocationBarByDefault(WebContents* source);
203 
204   // Sets focus to the location bar or some other place that is appropriate.
205   // This is called when the tab wants to encourage user input, like for the
206   // new tab page.
SetFocusToLocationBar(bool select_all)207   virtual void SetFocusToLocationBar(bool select_all) {}
208 
209   // Returns whether the page should be focused when transitioning from crashed
210   // to live. Default is true.
211   virtual bool ShouldFocusPageAfterCrash();
212 
213   // Called when a popup select is about to be displayed. The delegate can use
214   // this to disable inactive rendering for the frame in the window the select
215   // is opened within if necessary.
RenderWidgetShowing()216   virtual void RenderWidgetShowing() {}
217 
218   // This is called when WebKit tells us that it is done tabbing through
219   // controls on the page. Provides a way for WebContentsDelegates to handle
220   // this. Returns true if the delegate successfully handled it.
221   virtual bool TakeFocus(WebContents* source,
222                          bool reverse);
223 
224   // Invoked when the page loses mouse capture.
LostCapture()225   virtual void LostCapture() {}
226 
227   // Notification that |contents| has gained focus.
WebContentsFocused(WebContents * contents)228   virtual void WebContentsFocused(WebContents* contents) {}
229 
230   // Asks the delegate if the given tab can download.
231   // Invoking the |callback| synchronously is OK.
232   virtual void CanDownload(RenderViewHost* render_view_host,
233                            int request_id,
234                            const std::string& request_method,
235                            const base::Callback<void(bool)>& callback);
236 
237   // Return much extra vertical space should be allotted to the
238   // render view widget during various animations (e.g. infobar closing).
239   // This is used to make painting look smoother.
240   virtual int GetExtraRenderViewHeight() const;
241 
242   // Returns true if the context menu operation was handled by the delegate.
243   virtual bool HandleContextMenu(const content::ContextMenuParams& params);
244 
245   // Opens source view for given WebContents that is navigated to the given
246   // page url.
247   virtual void ViewSourceForTab(WebContents* source, const GURL& page_url);
248 
249   // Opens source view for the given subframe.
250   virtual void ViewSourceForFrame(WebContents* source,
251                                   const GURL& url,
252                                   const PageState& page_state);
253 
254   // Allows delegates to handle keyboard events before sending to the renderer.
255   // Returns true if the |event| was handled. Otherwise, if the |event| would be
256   // handled in HandleKeyboardEvent() method as a normal keyboard shortcut,
257   // |*is_keyboard_shortcut| should be set to true.
258   virtual bool PreHandleKeyboardEvent(WebContents* source,
259                                       const NativeWebKeyboardEvent& event,
260                                       bool* is_keyboard_shortcut);
261 
262   // Allows delegates to handle unhandled keyboard messages coming back from
263   // the renderer.
HandleKeyboardEvent(WebContents * source,const NativeWebKeyboardEvent & event)264   virtual void HandleKeyboardEvent(WebContents* source,
265                                    const NativeWebKeyboardEvent& event) {}
266 
HandleMouseDown()267   virtual void HandleMouseDown() {}
HandleMouseUp()268   virtual void HandleMouseUp() {}
269 
270   // Handles activation resulting from a pointer event (e.g. when mouse is
271   // pressed, or a touch-gesture begins).
HandlePointerActivate()272   virtual void HandlePointerActivate() {}
273 
HandleGestureBegin()274   virtual void HandleGestureBegin() {}
HandleGestureEnd()275   virtual void HandleGestureEnd() {}
276 
277   // Called when an external drag event enters the web contents window. Return
278   // true to allow dragging and dropping on the web contents window or false to
279   // cancel the operation. This method is used by Chromium Embedded Framework.
280   virtual bool CanDragEnter(WebContents* source,
281                             const DropData& data,
282                             blink::WebDragOperationsMask operations_allowed);
283 
284   // Render view drag n drop ended.
DragEnded()285   virtual void DragEnded() {}
286 
287   // Shows the repost form confirmation dialog box.
ShowRepostFormWarningDialog(WebContents * source)288   virtual void ShowRepostFormWarningDialog(WebContents* source) {}
289 
290   // Allows delegate to override navigation to the history entries.
291   // Returns true to allow WebContents to continue with the default processing.
292   virtual bool OnGoToEntryOffset(int offset);
293 
294   // Allows delegate to control whether a WebContents will be created. Returns
295   // true to allow the creation. Default is to allow it. In cases where the
296   // delegate handles the creation/navigation itself, it will use |target_url|.
297   virtual bool ShouldCreateWebContents(
298       WebContents* web_contents,
299       int route_id,
300       WindowContainerType window_container_type,
301       const base::string16& frame_name,
302       const GURL& target_url,
303       const std::string& partition_id,
304       SessionStorageNamespace* session_storage_namespace);
305 
306   // Notifies the delegate about the creation of a new WebContents. This
307   // typically happens when popups are created.
WebContentsCreated(WebContents * source_contents,int64 source_frame_id,const base::string16 & frame_name,const GURL & target_url,WebContents * new_contents)308   virtual void WebContentsCreated(WebContents* source_contents,
309                                   int64 source_frame_id,
310                                   const base::string16& frame_name,
311                                   const GURL& target_url,
312                                   WebContents* new_contents) {}
313 
314   // Notification that the tab is hung.
RendererUnresponsive(WebContents * source)315   virtual void RendererUnresponsive(WebContents* source) {}
316 
317   // Notification that the tab is no longer hung.
RendererResponsive(WebContents * source)318   virtual void RendererResponsive(WebContents* source) {}
319 
320   // Notification that a worker associated with this tab has crashed.
WorkerCrashed(WebContents * source)321   virtual void WorkerCrashed(WebContents* source) {}
322 
323   // Invoked when a main fram navigation occurs.
DidNavigateMainFramePostCommit(WebContents * source)324   virtual void DidNavigateMainFramePostCommit(WebContents* source) {}
325 
326   // Invoked when navigating to a pending entry. When invoked the
327   // NavigationController has configured its pending entry, but it has not yet
328   // been committed.
DidNavigateToPendingEntry(WebContents * source)329   virtual void DidNavigateToPendingEntry(WebContents* source) {}
330 
331   // Returns a pointer to a service to manage JavaScript dialogs. May return
332   // NULL in which case dialogs aren't shown.
333   virtual JavaScriptDialogManager* GetJavaScriptDialogManager();
334 
335   // Called when color chooser should open. Returns the opened color chooser.
336   // Returns NULL if we failed to open the color chooser (e.g. when there is a
337   // ColorChooserDialog already open on Windows). Ownership of the returned
338   // pointer is transferred to the caller.
339   virtual ColorChooser* OpenColorChooser(
340       WebContents* web_contents,
341       SkColor color,
342       const std::vector<ColorSuggestion>& suggestions);
343 
344   // Called when a file selection is to be done.
RunFileChooser(WebContents * web_contents,const FileChooserParams & params)345   virtual void RunFileChooser(WebContents* web_contents,
346                               const FileChooserParams& params) {}
347 
348   // Request to enumerate a directory.  This is equivalent to running the file
349   // chooser in directory-enumeration mode and having the user select the given
350   // directory.
EnumerateDirectory(WebContents * web_contents,int request_id,const base::FilePath & path)351   virtual void EnumerateDirectory(WebContents* web_contents,
352                                   int request_id,
353                                   const base::FilePath& path) {}
354 
355   // Returns true if the delegate will embed a WebContents-owned fullscreen
356   // render widget.  In this case, the delegate may access the widget by calling
357   // WebContents::GetFullscreenRenderWidgetHostView().  If false is returned,
358   // WebContents will be responsible for showing the fullscreen widget.
359   virtual bool EmbedsFullscreenWidget() const;
360 
361   // Called when the renderer puts a tab into or out of fullscreen mode.
ToggleFullscreenModeForTab(WebContents * web_contents,bool enter_fullscreen)362   virtual void ToggleFullscreenModeForTab(WebContents* web_contents,
363                                           bool enter_fullscreen) {}
364   virtual bool IsFullscreenForTabOrPending(
365       const WebContents* web_contents) const;
366 
367   // Called when a Javascript out of memory notification is received.
JSOutOfMemory(WebContents * web_contents)368   virtual void JSOutOfMemory(WebContents* web_contents) {}
369 
370   // Register a new handler for URL requests with the given scheme.
371   // |user_gesture| is true if the registration is made in the context of a user
372   // gesture.
RegisterProtocolHandler(WebContents * web_contents,const std::string & protocol,const GURL & url,const base::string16 & title,bool user_gesture)373   virtual void RegisterProtocolHandler(WebContents* web_contents,
374                                        const std::string& protocol,
375                                        const GURL& url,
376                                        const base::string16& title,
377                                        bool user_gesture) {}
378 
379   // Result of string search in the page. This includes the number of matches
380   // found and the selection rect (in screen coordinates) for the string found.
381   // If |final_update| is false, it indicates that more results follow.
FindReply(WebContents * web_contents,int request_id,int number_of_matches,const gfx::Rect & selection_rect,int active_match_ordinal,bool final_update)382   virtual void FindReply(WebContents* web_contents,
383                          int request_id,
384                          int number_of_matches,
385                          const gfx::Rect& selection_rect,
386                          int active_match_ordinal,
387                          bool final_update) {}
388 
389 #if defined(OS_ANDROID)
390   // Provides the rects of the current find-in-page matches.
391   // Sent as a reply to RequestFindMatchRects.
FindMatchRectsReply(WebContents * web_contents,int version,const std::vector<gfx::RectF> & rects,const gfx::RectF & active_rect)392   virtual void FindMatchRectsReply(WebContents* web_contents,
393                                    int version,
394                                    const std::vector<gfx::RectF>& rects,
395                                    const gfx::RectF& active_rect) {}
396 
397   // Request permission to access protected media identifier. The callback will
398   // tell whether it's allowed.
RequestProtectedMediaIdentifierPermission(const WebContents * web_contents,const GURL & frame_url,const base::Callback<void (bool)> & callback)399   virtual void RequestProtectedMediaIdentifierPermission(
400       const WebContents* web_contents,
401       const GURL& frame_url,
402       const base::Callback<void(bool)>& callback) {}
403 #endif
404 
405   // Invoked when the preferred size of the contents has been changed.
UpdatePreferredSize(WebContents * web_contents,const gfx::Size & pref_size)406   virtual void UpdatePreferredSize(WebContents* web_contents,
407                                    const gfx::Size& pref_size) {}
408 
409   // Invoked when the contents auto-resized and the container should match it.
ResizeDueToAutoResize(WebContents * web_contents,const gfx::Size & new_size)410   virtual void ResizeDueToAutoResize(WebContents* web_contents,
411                                      const gfx::Size& new_size) {}
412 
413   // Notification message from HTML UI.
WebUISend(WebContents * web_contents,const GURL & source_url,const std::string & name,const base::ListValue & args)414   virtual void WebUISend(WebContents* web_contents,
415                          const GURL& source_url,
416                          const std::string& name,
417                          const base::ListValue& args) {}
418 
419   // Requests to lock the mouse. Once the request is approved or rejected,
420   // GotResponseToLockMouseRequest() will be called on the requesting tab
421   // contents.
RequestToLockMouse(WebContents * web_contents,bool user_gesture,bool last_unlocked_by_target)422   virtual void RequestToLockMouse(WebContents* web_contents,
423                                   bool user_gesture,
424                                   bool last_unlocked_by_target) {}
425 
426   // Notification that the page has lost the mouse lock.
LostMouseLock()427   virtual void LostMouseLock() {}
428 
429   // Asks permission to use the camera and/or microphone. If permission is
430   // granted, a call should be made to |callback| with the devices. If the
431   // request is denied, a call should be made to |callback| with an empty list
432   // of devices. |request| has the details of the request (e.g. which of audio
433   // and/or video devices are requested, and lists of available devices).
434   virtual void RequestMediaAccessPermission(
435       WebContents* web_contents,
436       const MediaStreamRequest& request,
437       const MediaResponseCallback& callback);
438 
439   // Requests permission to access the PPAPI broker. The delegate should return
440   // true and call the passed in |callback| with the result, or return false
441   // to indicate that it does not support asking for permission.
442   virtual bool RequestPpapiBrokerPermission(
443       WebContents* web_contents,
444       const GURL& url,
445       const base::FilePath& plugin_path,
446       const base::Callback<void(bool)>& callback);
447 
448   // Returns the size for the new render view created for the pending entry in
449   // |web_contents|; if there's no size, returns an empty size.
450   // This is optional for implementations of WebContentsDelegate; if the
451   // delegate doesn't provide a size, the current WebContentsView's size will be
452   // used.
453   virtual gfx::Size GetSizeForNewRenderView(
454       const WebContents* web_contents) const;
455 
456   // Notification that validation of a form displayed by the |web_contents|
457   // has failed. There can only be one message per |web_contents| at a time.
ShowValidationMessage(WebContents * web_contents,const gfx::Rect & anchor_in_root_view,const string16 & main_text,const string16 & sub_text)458   virtual void ShowValidationMessage(WebContents* web_contents,
459                                      const gfx::Rect& anchor_in_root_view,
460                                      const string16& main_text,
461                                      const string16& sub_text) {}
462 
463   // Notification that the delegate should hide any showing form validation
464   // message.
HideValidationMessage(WebContents * web_contents)465   virtual void HideValidationMessage(WebContents* web_contents) {}
466 
467   // Notification that the form element that triggered the validation failure
468   // has moved.
MoveValidationMessage(WebContents * web_contents,const gfx::Rect & anchor_in_root_view)469   virtual void MoveValidationMessage(WebContents* web_contents,
470                                      const gfx::Rect& anchor_in_root_view) {}
471 
472  protected:
473   virtual ~WebContentsDelegate();
474 
475  private:
476   friend class WebContentsImpl;
477 
478   // Called when |this| becomes the WebContentsDelegate for |source|.
479   void Attach(WebContents* source);
480 
481   // Called when |this| is no longer the WebContentsDelegate for |source|.
482   void Detach(WebContents* source);
483 
484   // The WebContents that this is currently a delegate for.
485   std::set<WebContents*> attached_contents_;
486 };
487 
488 }  // namespace content
489 
490 #endif  // CONTENT_PUBLIC_BROWSER_WEB_CONTENTS_DELEGATE_H_
491