web_contents_delegate.h revision a1401311d1ab56c4ed0a474bd38c108f75cb0cd9
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
25class GURL;
26
27namespace base {
28class FilePath;
29class ListValue;
30}
31
32namespace content {
33class BrowserContext;
34class ColorChooser;
35class DownloadItem;
36class JavaScriptDialogManager;
37class PageState;
38class RenderViewHost;
39class SessionStorageNamespace;
40class WebContents;
41class WebContentsImpl;
42struct ColorSuggestion;
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 blink {
58class WebGestureEvent;
59class WebLayer;
60struct WebWindowFeatures;
61}
62
63namespace content {
64
65struct OpenURLParams;
66
67// Objects implement this interface to get notified about changes in the
68// WebContents and to provide necessary functionality.
69class 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.
89  virtual void NavigationStateChanged(const WebContents* source,
90                                      unsigned changed_flags) {}
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, |initial_pos| should hold
95  // the initial position. If |was_blocked| is non-NULL, then |*was_blocked|
96  // will be set to true if the popup gets blocked, and left unchanged
97  // otherwise.
98  virtual void AddNewContents(WebContents* source,
99                              WebContents* new_contents,
100                              WindowOpenDisposition disposition,
101                              const gfx::Rect& initial_pos,
102                              bool user_gesture,
103                              bool* was_blocked) {}
104
105  // Selects the specified contents, bringing its container to the front.
106  virtual void ActivateContents(WebContents* contents) {}
107
108  // Deactivates the specified contents by deactivating its container and
109  // potentialy moving it to the back of the Z order.
110  virtual void DeactivateContents(WebContents* contents) {}
111
112  // Notifies the delegate that this contents is starting or is done loading
113  // some resource. The delegate should use this notification to represent
114  // loading feedback. See WebContents::IsLoading()
115  virtual void LoadingStateChanged(WebContents* source) {}
116
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
123  // Request the delegate to close this web contents, and do whatever cleanup
124  // it needs to do.
125  virtual void CloseContents(WebContents* source) {}
126
127  // Informs the delegate that the underlying RenderViewHost has been swapped
128  // out so it can perform any cleanup necessary.
129  virtual void SwappedOut(WebContents* source) {}
130
131  // Request the delegate to move this WebContents to the specified position
132  // in screen coordinates.
133  virtual void MoveContents(WebContents* source, const gfx::Rect& pos) {}
134
135  // Called to determine if the WebContents is contained in a popup window
136  // or a panel window.
137  virtual bool IsPopupOrPanel(const WebContents* source) const;
138
139  // Notification that the target URL has changed.
140  virtual void UpdateTargetURL(WebContents* source,
141                               int32 page_id,
142                               const GURL& url) {}
143
144  // Notification that there was a mouse event, along with the absolute
145  // coordinates of the mouse pointer and whether it was a normal motion event
146  // (otherwise, the pointer left the contents area).
147  virtual void ContentsMouseEvent(WebContents* source,
148                                  const gfx::Point& location,
149                                  bool motion) {}
150
151  // Request the delegate to change the zoom level of the current tab.
152  virtual void ContentsZoomChange(bool zoom_in) {}
153
154  // Called to determine if the WebContents can be overscrolled with touch/wheel
155  // gestures.
156  virtual bool CanOverscrollContent() const;
157
158  // Callback that allows vertical overscroll activies to be communicated to the
159  // delegate.
160  virtual void OverscrollUpdate(int delta_y) {}
161
162  // Return the rect where to display the resize corner, if any, otherwise
163  // an empty rect.
164  virtual gfx::Rect GetRootWindowResizerRect() const;
165
166  // Invoked prior to showing before unload handler confirmation dialog.
167  virtual void WillRunBeforeUnloadConfirm() {}
168
169  // Returns true if javascript dialogs and unload alerts are suppressed.
170  // Default is false.
171  virtual bool ShouldSuppressDialogs();
172
173  // Add a message to the console. Returning true indicates that the delegate
174  // handled the message. If false is returned the default logging mechanism
175  // will be used for the message.
176  virtual bool AddMessageToConsole(WebContents* source,
177                                   int32 level,
178                                   const base::string16& message,
179                                   int32 line_no,
180                                   const base::string16& source_id);
181
182  // Tells us that we've finished firing this tab's beforeunload event.
183  // The proceed bool tells us whether the user chose to proceed closing the
184  // tab. Returns true if the tab can continue on firing its unload event.
185  // If we're closing the entire browser, then we'll want to delay firing
186  // unload events until all the beforeunload events have fired.
187  virtual void BeforeUnloadFired(WebContents* tab,
188                                 bool proceed,
189                                 bool* proceed_to_fire_unload);
190
191  // Returns true if the location bar should be focused by default rather than
192  // the page contents. NOTE: this is only used if WebContents can't determine
193  // for itself whether the location bar should be focused by default. For a
194  // complete check, you should use WebContents::FocusLocationBarByDefault().
195  virtual bool ShouldFocusLocationBarByDefault(WebContents* source);
196
197  // Sets focus to the location bar or some other place that is appropriate.
198  // This is called when the tab wants to encourage user input, like for the
199  // new tab page.
200  virtual void SetFocusToLocationBar(bool select_all) {}
201
202  // Returns whether the page should be focused when transitioning from crashed
203  // to live. Default is true.
204  virtual bool ShouldFocusPageAfterCrash();
205
206  // This is called when WebKit tells us that it is done tabbing through
207  // controls on the page. Provides a way for WebContentsDelegates to handle
208  // this. Returns true if the delegate successfully handled it.
209  virtual bool TakeFocus(WebContents* source,
210                         bool reverse);
211
212  // Invoked when the page loses mouse capture.
213  virtual void LostCapture() {}
214
215  // Notification that |contents| has gained focus.
216  virtual void WebContentsFocused(WebContents* contents) {}
217
218  // Asks the delegate if the given tab can download.
219  // Invoking the |callback| synchronously is OK.
220  virtual void CanDownload(RenderViewHost* render_view_host,
221                           int request_id,
222                           const std::string& request_method,
223                           const base::Callback<void(bool)>& callback);
224
225  // Return much extra vertical space should be allotted to the
226  // render view widget during various animations (e.g. infobar closing).
227  // This is used to make painting look smoother.
228  virtual int GetExtraRenderViewHeight() const;
229
230  // Returns true if the context menu operation was handled by the delegate.
231  virtual bool HandleContextMenu(const content::ContextMenuParams& params);
232
233  // Opens source view for given WebContents that is navigated to the given
234  // page url.
235  virtual void ViewSourceForTab(WebContents* source, const GURL& page_url);
236
237  // Opens source view for the given subframe.
238  virtual void ViewSourceForFrame(WebContents* source,
239                                  const GURL& url,
240                                  const PageState& page_state);
241
242  // Allows delegates to handle keyboard events before sending to the renderer.
243  // Returns true if the |event| was handled. Otherwise, if the |event| would be
244  // handled in HandleKeyboardEvent() method as a normal keyboard shortcut,
245  // |*is_keyboard_shortcut| should be set to true.
246  virtual bool PreHandleKeyboardEvent(WebContents* source,
247                                      const NativeWebKeyboardEvent& event,
248                                      bool* is_keyboard_shortcut);
249
250  // Allows delegates to handle unhandled keyboard messages coming back from
251  // the renderer.
252  virtual void HandleKeyboardEvent(WebContents* source,
253                                   const NativeWebKeyboardEvent& event) {}
254
255  virtual void HandleMouseDown() {}
256  virtual void HandleMouseUp() {}
257
258  // Handles activation resulting from a pointer event (e.g. when mouse is
259  // pressed, or a touch-gesture begins).
260  virtual void HandlePointerActivate() {}
261
262  // Allows delegates to handle gesture events before sending to the renderer.
263  // Returns true if the |event| was handled and thus shouldn't be processed
264  // by the renderer's event handler. Note that the touch events that create
265  // the gesture are always passed to the renderer since the gesture is created
266  // and dispatched after the touches return without being "preventDefault()"ed.
267  virtual bool PreHandleGestureEvent(
268      WebContents* source,
269      const blink::WebGestureEvent& event);
270
271  virtual void HandleGestureBegin() {}
272  virtual void HandleGestureEnd() {}
273
274  // Called when an external drag event enters the web contents window. Return
275  // true to allow dragging and dropping on the web contents window or false to
276  // cancel the operation. This method is used by Chromium Embedded Framework.
277  virtual bool CanDragEnter(WebContents* source,
278                            const DropData& data,
279                            blink::WebDragOperationsMask operations_allowed);
280
281  // Render view drag n drop ended.
282  virtual void DragEnded() {}
283
284  // Shows the repost form confirmation dialog box.
285  virtual void ShowRepostFormWarningDialog(WebContents* source) {}
286
287  // Allows delegate to override navigation to the history entries.
288  // Returns true to allow WebContents to continue with the default processing.
289  virtual bool OnGoToEntryOffset(int offset);
290
291  // Allows delegate to control whether a WebContents will be created. Returns
292  // true to allow the creation. Default is to allow it. In cases where the
293  // delegate handles the creation/navigation itself, it will use |target_url|.
294  // The embedder has to synchronously adopt |route_id| or else the view will
295  // be destroyed.
296  virtual bool ShouldCreateWebContents(
297      WebContents* web_contents,
298      int route_id,
299      WindowContainerType window_container_type,
300      const base::string16& frame_name,
301      const GURL& target_url,
302      const std::string& partition_id,
303      SessionStorageNamespace* session_storage_namespace);
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 base::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  // Returns NULL if we failed to open the color chooser (e.g. when there is a
336  // ColorChooserDialog already open on Windows). Ownership of the returned
337  // pointer is transferred to the caller.
338  virtual ColorChooser* OpenColorChooser(
339      WebContents* web_contents,
340      SkColor color,
341      const std::vector<ColorSuggestion>& suggestions);
342
343  // Called when a file selection is to be done.
344  virtual void RunFileChooser(WebContents* web_contents,
345                              const FileChooserParams& params) {}
346
347  // Request to enumerate a directory.  This is equivalent to running the file
348  // chooser in directory-enumeration mode and having the user select the given
349  // directory.
350  virtual void EnumerateDirectory(WebContents* web_contents,
351                                  int request_id,
352                                  const base::FilePath& path) {}
353
354  // Returns true if the delegate will embed a WebContents-owned fullscreen
355  // render widget.  In this case, the delegate may access the widget by calling
356  // WebContents::GetFullscreenRenderWidgetHostView().  If false is returned,
357  // WebContents will be responsible for showing the fullscreen widget.
358  virtual bool EmbedsFullscreenWidget() const;
359
360  // Called when the renderer puts a tab into or out of fullscreen mode.
361  virtual void ToggleFullscreenModeForTab(WebContents* web_contents,
362                                          bool enter_fullscreen) {}
363  virtual bool IsFullscreenForTabOrPending(
364      const WebContents* web_contents) const;
365
366  // Register a new handler for URL requests with the given scheme.
367  // |user_gesture| is true if the registration is made in the context of a user
368  // gesture.
369  virtual void RegisterProtocolHandler(WebContents* web_contents,
370                                       const std::string& protocol,
371                                       const GURL& url,
372                                       const base::string16& title,
373                                       bool user_gesture) {}
374
375  // Result of string search in the page. This includes the number of matches
376  // found and the selection rect (in screen coordinates) for the string found.
377  // If |final_update| is false, it indicates that more results follow.
378  virtual void FindReply(WebContents* web_contents,
379                         int request_id,
380                         int number_of_matches,
381                         const gfx::Rect& selection_rect,
382                         int active_match_ordinal,
383                         bool final_update) {}
384
385#if defined(OS_ANDROID)
386  // Provides the rects of the current find-in-page matches.
387  // Sent as a reply to RequestFindMatchRects.
388  virtual void FindMatchRectsReply(WebContents* web_contents,
389                                   int version,
390                                   const std::vector<gfx::RectF>& rects,
391                                   const gfx::RectF& active_rect) {}
392#endif
393
394  // Invoked when the preferred size of the contents has been changed.
395  virtual void UpdatePreferredSize(WebContents* web_contents,
396                                   const gfx::Size& pref_size) {}
397
398  // Invoked when the contents auto-resized and the container should match it.
399  virtual void ResizeDueToAutoResize(WebContents* web_contents,
400                                     const gfx::Size& new_size) {}
401
402  // Notification message from HTML UI.
403  virtual void WebUISend(WebContents* web_contents,
404                         const GURL& source_url,
405                         const std::string& name,
406                         const base::ListValue& args) {}
407
408  // Requests to lock the mouse. Once the request is approved or rejected,
409  // GotResponseToLockMouseRequest() will be called on the requesting tab
410  // contents.
411  virtual void RequestToLockMouse(WebContents* web_contents,
412                                  bool user_gesture,
413                                  bool last_unlocked_by_target) {}
414
415  // Notification that the page has lost the mouse lock.
416  virtual void LostMouseLock() {}
417
418  // Asks permission to use the camera and/or microphone. If permission is
419  // granted, a call should be made to |callback| with the devices. If the
420  // request is denied, a call should be made to |callback| with an empty list
421  // of devices. |request| has the details of the request (e.g. which of audio
422  // and/or video devices are requested, and lists of available devices).
423  virtual void RequestMediaAccessPermission(
424      WebContents* web_contents,
425      const MediaStreamRequest& request,
426      const MediaResponseCallback& callback);
427
428  // Requests permission to access the PPAPI broker. The delegate should return
429  // true and call the passed in |callback| with the result, or return false
430  // to indicate that it does not support asking for permission.
431  virtual bool RequestPpapiBrokerPermission(
432      WebContents* web_contents,
433      const GURL& url,
434      const base::FilePath& plugin_path,
435      const base::Callback<void(bool)>& callback);
436
437  // Returns the size for the new render view created for the pending entry in
438  // |web_contents|; if there's no size, returns an empty size.
439  // This is optional for implementations of WebContentsDelegate; if the
440  // delegate doesn't provide a size, the current WebContentsView's size will be
441  // used.
442  virtual gfx::Size GetSizeForNewRenderView(
443      const WebContents* web_contents) const;
444
445  // Notification that validation of a form displayed by the |web_contents|
446  // has failed. There can only be one message per |web_contents| at a time.
447  virtual void ShowValidationMessage(WebContents* web_contents,
448                                     const gfx::Rect& anchor_in_root_view,
449                                     const base::string16& main_text,
450                                     const base::string16& sub_text) {}
451
452  // Notification that the delegate should hide any showing form validation
453  // message.
454  virtual void HideValidationMessage(WebContents* web_contents) {}
455
456  // Notification that the form element that triggered the validation failure
457  // has moved.
458  virtual void MoveValidationMessage(WebContents* web_contents,
459                                     const gfx::Rect& anchor_in_root_view) {}
460
461 protected:
462  virtual ~WebContentsDelegate();
463
464 private:
465  friend class WebContentsImpl;
466
467  // Called when |this| becomes the WebContentsDelegate for |source|.
468  void Attach(WebContents* source);
469
470  // Called when |this| is no longer the WebContentsDelegate for |source|.
471  void Detach(WebContents* source);
472
473  // The WebContents that this is currently a delegate for.
474  std::set<WebContents*> attached_contents_;
475};
476
477}  // namespace content
478
479#endif  // CONTENT_PUBLIC_BROWSER_WEB_CONTENTS_DELEGATE_H_
480