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