web_contents_delegate.h revision d0247b1b59f9c528cb6df88b4f2b9afaf80d181e
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 SessionStorageNamespace;
41class WebContents;
42class WebContentsImpl;
43struct ContextMenuParams;
44struct DropData;
45struct FileChooserParams;
46struct NativeWebKeyboardEvent;
47struct Referrer;
48struct SSLStatus;
49}
50
51namespace gfx {
52class Point;
53class Rect;
54class Size;
55}
56
57namespace WebKit {
58class WebLayer;
59struct WebWindowFeatures;
60}
61
62namespace content {
63
64struct OpenURLParams;
65
66// Objects implement this interface to get notified about changes in the
67// WebContents and to provide necessary functionality.
68class 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.
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.
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.
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.
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.
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()
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).
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.
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  // Callback that allows vertical overscroll activies to be communicated to the
162  // delegate.
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.
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 string16& message,
186                                   int32 line_no,
187                                   const 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.
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.
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.
225  virtual void LostCapture() {}
226
227  // Notification that |contents| has gained focus.
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.
264  virtual void HandleKeyboardEvent(WebContents* source,
265                                   const NativeWebKeyboardEvent& event) {}
266
267  virtual void HandleMouseDown() {}
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).
272  virtual void HandlePointerActivate() {}
273
274  virtual void HandleGestureBegin() {}
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                            WebKit::WebDragOperationsMask operations_allowed);
283
284  // Render view drag n drop ended.
285  virtual void DragEnded() {}
286
287  // Shows the repost form confirmation dialog box.
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 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.
308  virtual void WebContentsCreated(WebContents* source_contents,
309                                  int64 source_frame_id,
310                                  const string16& frame_name,
311                                  const GURL& target_url,
312                                  WebContents* new_contents) {}
313
314  // Notification that the tab is hung.
315  virtual void RendererUnresponsive(WebContents* source) {}
316
317  // Notification that the tab is no longer hung.
318  virtual void RendererResponsive(WebContents* source) {}
319
320  // Notification that a worker associated with this tab has crashed.
321  virtual void WorkerCrashed(WebContents* source) {}
322
323  // Invoked when a main fram navigation occurs.
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.
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  // Ownership of the returned pointer is transferred to the caller.
337  virtual ColorChooser* OpenColorChooser(WebContents* web_contents,
338                                         SkColor color);
339
340  // Called when a file selection is to be done.
341  virtual void RunFileChooser(WebContents* web_contents,
342                              const FileChooserParams& params) {}
343
344  // Request to enumerate a directory.  This is equivalent to running the file
345  // chooser in directory-enumeration mode and having the user select the given
346  // directory.
347  virtual void EnumerateDirectory(WebContents* web_contents,
348                                  int request_id,
349                                  const base::FilePath& path) {}
350
351  // Returns true if the delegate will embed a WebContents-owned fullscreen
352  // render widget.  In this case, the delegate may access the widget by calling
353  // WebContents::GetFullscreenRenderWidgetHostView().  If false is returned,
354  // WebContents will be responsible for showing the fullscreen widget.
355  virtual bool EmbedsFullscreenWidget() const;
356
357  // Called when the renderer puts a tab into or out of fullscreen mode.
358  virtual void ToggleFullscreenModeForTab(WebContents* web_contents,
359                                          bool enter_fullscreen) {}
360  virtual bool IsFullscreenForTabOrPending(
361      const WebContents* web_contents) const;
362
363  // Called when the renderer has scrolled programmatically.
364  virtual void DidProgrammaticallyScroll(WebContents* web_contents,
365                                         const gfx::Vector2d& scroll_point) {}
366
367  // Called when a Javascript out of memory notification is received.
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.
373  virtual void RegisterProtocolHandler(WebContents* web_contents,
374                                       const std::string& protocol,
375                                       const GURL& url,
376                                       const 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.
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.
392  virtual void FindMatchRectsReply(WebContents* web_contents,
393                                   int version,
394                                   const std::vector<gfx::RectF>& rects,
395                                   const gfx::RectF& active_rect) {}
396#endif
397
398  // Invoked when the preferred size of the contents has been changed.
399  virtual void UpdatePreferredSize(WebContents* web_contents,
400                                   const gfx::Size& pref_size) {}
401
402  // Invoked when the contents auto-resized and the container should match it.
403  virtual void ResizeDueToAutoResize(WebContents* web_contents,
404                                     const gfx::Size& new_size) {}
405
406  // Notification message from HTML UI.
407  virtual void WebUISend(WebContents* web_contents,
408                         const GURL& source_url,
409                         const std::string& name,
410                         const base::ListValue& args) {}
411
412  // Requests to lock the mouse. Once the request is approved or rejected,
413  // GotResponseToLockMouseRequest() will be called on the requesting tab
414  // contents.
415  virtual void RequestToLockMouse(WebContents* web_contents,
416                                  bool user_gesture,
417                                  bool last_unlocked_by_target) {}
418
419  // Notification that the page has lost the mouse lock.
420  virtual void LostMouseLock() {}
421
422  // Asks permission to use the camera and/or microphone. If permission is
423  // granted, a call should be made to |callback| with the devices. If the
424  // request is denied, a call should be made to |callback| with an empty list
425  // of devices. |request| has the details of the request (e.g. which of audio
426  // and/or video devices are requested, and lists of available devices).
427  virtual void RequestMediaAccessPermission(
428      WebContents* web_contents,
429      const MediaStreamRequest& request,
430      const MediaResponseCallback& callback);
431
432  // Requests permission to access the PPAPI broker. The delegate should return
433  // true and call the passed in |callback| with the result, or return false
434  // to indicate that it does not support asking for permission.
435  virtual bool RequestPpapiBrokerPermission(
436      WebContents* web_contents,
437      const GURL& url,
438      const base::FilePath& plugin_path,
439      const base::Callback<void(bool)>& callback);
440
441  // Returns the size for the new render view created for the pending entry in
442  // |web_contents|; if there's no size, returns an empty size.
443  // This is optional for implementations of WebContentsDelegate; if the
444  // delegate doesn't provide a size, the current WebContentsView's size will be
445  // used.
446  virtual gfx::Size GetSizeForNewRenderView(
447      const WebContents* web_contents) const;
448
449 protected:
450  virtual ~WebContentsDelegate();
451
452 private:
453  friend class WebContentsImpl;
454
455  // Called when |this| becomes the WebContentsDelegate for |source|.
456  void Attach(WebContents* source);
457
458  // Called when |this| is no longer the WebContentsDelegate for |source|.
459  void Detach(WebContents* source);
460
461  // The WebContents that this is currently a delegate for.
462  std::set<WebContents*> attached_contents_;
463};
464
465}  // namespace content
466
467#endif  // CONTENT_PUBLIC_BROWSER_WEB_CONTENTS_DELEGATE_H_
468