• 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 WebGestureEvent;
59 class WebLayer;
60 struct WebWindowFeatures;
61 }
62 
63 namespace content {
64 
65 struct OpenURLParams;
66 
67 // Objects implement this interface to get notified about changes in the
68 // WebContents and to provide necessary functionality.
69 class CONTENT_EXPORT WebContentsDelegate {
70  public:
71   WebContentsDelegate();
72 
73   // Opens a new URL inside the passed in WebContents (if source is 0 open
74   // in the current front-most tab), unless |disposition| indicates the url
75   // should be opened in a new tab or window.
76   //
77   // A NULL source indicates the current tab (callers should probably use
78   // OpenURL() for these cases which does it for you).
79 
80   // Returns the WebContents the URL is opened in, or NULL if the URL wasn't
81   // opened immediately.
82   virtual WebContents* OpenURLFromTab(WebContents* source,
83                                       const OpenURLParams& params);
84 
85   // Called to inform the delegate that the WebContents's navigation state
86   // changed. The |changed_flags| indicates the parts of the navigation state
87   // that have been updated, and is any combination of the
88   // |WebContents::InvalidateTypes| bits.
NavigationStateChanged(const WebContents * source,unsigned changed_flags)89   virtual void NavigationStateChanged(const WebContents* source,
90                                       unsigned changed_flags) {}
91 
92   // Called to inform the delegate that the WebContent's visible SSL state (as
93   // defined by SSLStatus) changed.
VisibleSSLStateChanged(const WebContents * source)94   virtual void VisibleSSLStateChanged(const WebContents* source) {}
95 
96   // Creates a new tab with the already-created WebContents 'new_contents'.
97   // The window for the added contents should be reparented correctly when this
98   // method returns.  If |disposition| is NEW_POPUP, |initial_pos| should hold
99   // the initial position. If |was_blocked| is non-NULL, then |*was_blocked|
100   // will be set to true if the popup gets blocked, and left unchanged
101   // otherwise.
AddNewContents(WebContents * source,WebContents * new_contents,WindowOpenDisposition disposition,const gfx::Rect & initial_pos,bool user_gesture,bool * was_blocked)102   virtual void AddNewContents(WebContents* source,
103                               WebContents* new_contents,
104                               WindowOpenDisposition disposition,
105                               const gfx::Rect& initial_pos,
106                               bool user_gesture,
107                               bool* was_blocked) {}
108 
109   // Selects the specified contents, bringing its container to the front.
ActivateContents(WebContents * contents)110   virtual void ActivateContents(WebContents* contents) {}
111 
112   // Deactivates the specified contents by deactivating its container and
113   // potentialy moving it to the back of the Z order.
DeactivateContents(WebContents * contents)114   virtual void DeactivateContents(WebContents* contents) {}
115 
116   // Notifies the delegate that this contents is starting or is done loading
117   // some resource. The delegate should use this notification to represent
118   // loading feedback. See WebContents::IsLoading()
119   // |to_different_document| will be true unless the load is a fragment
120   // navigation, or triggered by history.pushState/replaceState.
LoadingStateChanged(WebContents * source,bool to_different_document)121   virtual void LoadingStateChanged(WebContents* source,
122                                    bool to_different_document) {}
123 
124   // Notifies the delegate that the page has made some progress loading.
125   // |progress| is a value between 0.0 (nothing loaded) to 1.0 (page fully
126   // loaded).
LoadProgressChanged(WebContents * source,double progress)127   virtual void LoadProgressChanged(WebContents* source,
128                                    double progress) {}
129 
130   // Request the delegate to close this web contents, and do whatever cleanup
131   // it needs to do.
CloseContents(WebContents * source)132   virtual void CloseContents(WebContents* source) {}
133 
134   // Informs the delegate that the underlying RenderViewHost has been swapped
135   // out so it can perform any cleanup necessary.
SwappedOut(WebContents * source)136   virtual void SwappedOut(WebContents* source) {}
137 
138   // Request the delegate to move this WebContents to the specified position
139   // in screen coordinates.
MoveContents(WebContents * source,const gfx::Rect & pos)140   virtual void MoveContents(WebContents* source, const gfx::Rect& pos) {}
141 
142   // Called to determine if the WebContents is contained in a popup window
143   // or a panel window.
144   virtual bool IsPopupOrPanel(const WebContents* source) const;
145 
146   // Notification that the target URL has changed.
UpdateTargetURL(WebContents * source,int32 page_id,const GURL & url)147   virtual void UpdateTargetURL(WebContents* source,
148                                int32 page_id,
149                                const GURL& url) {}
150 
151   // Notification that there was a mouse event, along with the absolute
152   // coordinates of the mouse pointer and whether it was a normal motion event
153   // (otherwise, the pointer left the contents area).
ContentsMouseEvent(WebContents * source,const gfx::Point & location,bool motion)154   virtual void ContentsMouseEvent(WebContents* source,
155                                   const gfx::Point& location,
156                                   bool motion) {}
157 
158   // Request the delegate to change the zoom level of the current tab.
ContentsZoomChange(bool zoom_in)159   virtual void ContentsZoomChange(bool zoom_in) {}
160 
161   // Called to determine if the WebContents can be overscrolled with touch/wheel
162   // gestures.
163   virtual bool CanOverscrollContent() const;
164 
165   // Callback that allows vertical overscroll activies to be communicated to the
166   // delegate.
OverscrollUpdate(int delta_y)167   virtual void OverscrollUpdate(int delta_y) {}
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   // Returns whether pending NavigationEntries for aborted browser-initiated
181   // navigations should be preserved (and thus returned from GetVisibleURL).
182   // Defaults to false.
183   virtual bool ShouldPreserveAbortedURLs(WebContents* source);
184 
185   // Add a message to the console. Returning true indicates that the delegate
186   // handled the message. If false is returned the default logging mechanism
187   // will be used for the message.
188   virtual bool AddMessageToConsole(WebContents* source,
189                                    int32 level,
190                                    const base::string16& message,
191                                    int32 line_no,
192                                    const base::string16& source_id);
193 
194   // Tells us that we've finished firing this tab's beforeunload event.
195   // The proceed bool tells us whether the user chose to proceed closing the
196   // tab. Returns true if the tab can continue on firing its unload event.
197   // If we're closing the entire browser, then we'll want to delay firing
198   // unload events until all the beforeunload events have fired.
199   virtual void BeforeUnloadFired(WebContents* tab,
200                                  bool proceed,
201                                  bool* proceed_to_fire_unload);
202 
203   // Returns true if the location bar should be focused by default rather than
204   // the page contents. NOTE: this is only used if WebContents can't determine
205   // for itself whether the location bar should be focused by default. For a
206   // complete check, you should use WebContents::FocusLocationBarByDefault().
207   virtual bool ShouldFocusLocationBarByDefault(WebContents* source);
208 
209   // Sets focus to the location bar or some other place that is appropriate.
210   // This is called when the tab wants to encourage user input, like for the
211   // new tab page.
SetFocusToLocationBar(bool select_all)212   virtual void SetFocusToLocationBar(bool select_all) {}
213 
214   // Returns whether the page should be focused when transitioning from crashed
215   // to live. Default is true.
216   virtual bool ShouldFocusPageAfterCrash();
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                            const GURL& url,
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 
274   // Allows delegates to handle gesture events before sending to the renderer.
275   // Returns true if the |event| was handled and thus shouldn't be processed
276   // by the renderer's event handler. Note that the touch events that create
277   // the gesture are always passed to the renderer since the gesture is created
278   // and dispatched after the touches return without being "preventDefault()"ed.
279   virtual bool PreHandleGestureEvent(
280       WebContents* source,
281       const blink::WebGestureEvent& event);
282 
HandleGestureBegin()283   virtual void HandleGestureBegin() {}
HandleGestureEnd()284   virtual void HandleGestureEnd() {}
285 
286   // Called when an external drag event enters the web contents window. Return
287   // true to allow dragging and dropping on the web contents window or false to
288   // cancel the operation. This method is used by Chromium Embedded Framework.
289   virtual bool CanDragEnter(WebContents* source,
290                             const DropData& data,
291                             blink::WebDragOperationsMask operations_allowed);
292 
293   // Render view drag n drop ended.
DragEnded()294   virtual void DragEnded() {}
295 
296   // Shows the repost form confirmation dialog box.
ShowRepostFormWarningDialog(WebContents * source)297   virtual void ShowRepostFormWarningDialog(WebContents* source) {}
298 
299   // Allows delegate to override navigation to the history entries.
300   // Returns true to allow WebContents to continue with the default processing.
301   virtual bool OnGoToEntryOffset(int offset);
302 
303   // Allows delegate to control whether a WebContents will be created. Returns
304   // true to allow the creation. Default is to allow it. In cases where the
305   // delegate handles the creation/navigation itself, it will use |target_url|.
306   // The embedder has to synchronously adopt |route_id| or else the view will
307   // be destroyed.
308   virtual bool ShouldCreateWebContents(
309       WebContents* web_contents,
310       int route_id,
311       WindowContainerType window_container_type,
312       const base::string16& frame_name,
313       const GURL& target_url,
314       const std::string& partition_id,
315       SessionStorageNamespace* session_storage_namespace);
316 
317   // Notifies the delegate about the creation of a new WebContents. This
318   // typically happens when popups are created.
WebContentsCreated(WebContents * source_contents,int opener_render_frame_id,const base::string16 & frame_name,const GURL & target_url,WebContents * new_contents)319   virtual void WebContentsCreated(WebContents* source_contents,
320                                   int opener_render_frame_id,
321                                   const base::string16& frame_name,
322                                   const GURL& target_url,
323                                   WebContents* new_contents) {}
324 
325   // Notification that the tab is hung.
RendererUnresponsive(WebContents * source)326   virtual void RendererUnresponsive(WebContents* source) {}
327 
328   // Notification that the tab is no longer hung.
RendererResponsive(WebContents * source)329   virtual void RendererResponsive(WebContents* source) {}
330 
331   // Notification that a worker associated with this tab has crashed.
WorkerCrashed(WebContents * source)332   virtual void WorkerCrashed(WebContents* source) {}
333 
334   // Invoked when a main fram navigation occurs.
DidNavigateMainFramePostCommit(WebContents * source)335   virtual void DidNavigateMainFramePostCommit(WebContents* source) {}
336 
337   // Invoked when navigating to a pending entry. When invoked the
338   // NavigationController has configured its pending entry, but it has not yet
339   // been committed.
DidNavigateToPendingEntry(WebContents * source)340   virtual void DidNavigateToPendingEntry(WebContents* source) {}
341 
342   // Returns a pointer to a service to manage JavaScript dialogs. May return
343   // NULL in which case dialogs aren't shown.
344   virtual JavaScriptDialogManager* GetJavaScriptDialogManager();
345 
346   // Called when color chooser should open. Returns the opened color chooser.
347   // Returns NULL if we failed to open the color chooser (e.g. when there is a
348   // ColorChooserDialog already open on Windows). Ownership of the returned
349   // pointer is transferred to the caller.
350   virtual ColorChooser* OpenColorChooser(
351       WebContents* web_contents,
352       SkColor color,
353       const std::vector<ColorSuggestion>& suggestions);
354 
355   // Called when a file selection is to be done.
RunFileChooser(WebContents * web_contents,const FileChooserParams & params)356   virtual void RunFileChooser(WebContents* web_contents,
357                               const FileChooserParams& params) {}
358 
359   // Request to enumerate a directory.  This is equivalent to running the file
360   // chooser in directory-enumeration mode and having the user select the given
361   // directory.
EnumerateDirectory(WebContents * web_contents,int request_id,const base::FilePath & path)362   virtual void EnumerateDirectory(WebContents* web_contents,
363                                   int request_id,
364                                   const base::FilePath& path) {}
365 
366   // Returns true if the delegate will embed a WebContents-owned fullscreen
367   // render widget.  In this case, the delegate may access the widget by calling
368   // WebContents::GetFullscreenRenderWidgetHostView().  If false is returned,
369   // WebContents will be responsible for showing the fullscreen widget.
370   virtual bool EmbedsFullscreenWidget() const;
371 
372   // Called when the renderer puts a tab into or out of fullscreen mode.
ToggleFullscreenModeForTab(WebContents * web_contents,bool enter_fullscreen)373   virtual void ToggleFullscreenModeForTab(WebContents* web_contents,
374                                           bool enter_fullscreen) {}
375   virtual bool IsFullscreenForTabOrPending(
376       const WebContents* web_contents) const;
377 
378   // Register a new handler for URL requests with the given scheme.
379   // |user_gesture| is true if the registration is made in the context of a user
380   // gesture.
RegisterProtocolHandler(WebContents * web_contents,const std::string & protocol,const GURL & url,bool user_gesture)381   virtual void RegisterProtocolHandler(WebContents* web_contents,
382                                        const std::string& protocol,
383                                        const GURL& url,
384                                        bool user_gesture) {}
385 
386   // Result of string search in the page. This includes the number of matches
387   // found and the selection rect (in screen coordinates) for the string found.
388   // 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)389   virtual void FindReply(WebContents* web_contents,
390                          int request_id,
391                          int number_of_matches,
392                          const gfx::Rect& selection_rect,
393                          int active_match_ordinal,
394                          bool final_update) {}
395 
396 #if defined(OS_ANDROID)
397   // Provides the rects of the current find-in-page matches.
398   // Sent as a reply to RequestFindMatchRects.
FindMatchRectsReply(WebContents * web_contents,int version,const std::vector<gfx::RectF> & rects,const gfx::RectF & active_rect)399   virtual void FindMatchRectsReply(WebContents* web_contents,
400                                    int version,
401                                    const std::vector<gfx::RectF>& rects,
402                                    const gfx::RectF& active_rect) {}
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(WebContents* web_contents) const;
454 
455   // Notification that validation of a form displayed by the |web_contents|
456   // 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 base::string16 & main_text,const base::string16 & sub_text)457   virtual void ShowValidationMessage(WebContents* web_contents,
458                                      const gfx::Rect& anchor_in_root_view,
459                                      const base::string16& main_text,
460                                      const base::string16& sub_text) {}
461 
462   // Notification that the delegate should hide any showing form validation
463   // message.
HideValidationMessage(WebContents * web_contents)464   virtual void HideValidationMessage(WebContents* web_contents) {}
465 
466   // Notification that the form element that triggered the validation failure
467   // has moved.
MoveValidationMessage(WebContents * web_contents,const gfx::Rect & anchor_in_root_view)468   virtual void MoveValidationMessage(WebContents* web_contents,
469                                      const gfx::Rect& anchor_in_root_view) {}
470 
471   // Returns true if the WebContents is never visible.
472   virtual bool IsNeverVisible(WebContents* web_contents);
473 
474  protected:
475   virtual ~WebContentsDelegate();
476 
477  private:
478   friend class WebContentsImpl;
479 
480   // Called when |this| becomes the WebContentsDelegate for |source|.
481   void Attach(WebContents* source);
482 
483   // Called when |this| is no longer the WebContentsDelegate for |source|.
484   void Detach(WebContents* source);
485 
486   // The WebContents that this is currently a delegate for.
487   std::set<WebContents*> attached_contents_;
488 };
489 
490 }  // namespace content
491 
492 #endif  // CONTENT_PUBLIC_BROWSER_WEB_CONTENTS_DELEGATE_H_
493