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