Upload upstream chromium 108.0.5359.1
[platform/framework/web/chromium-efl.git] / content / public / browser / web_contents_delegate.h
1 // Copyright 2012 The Chromium Authors
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 <stdint.h>
9
10 #include <memory>
11 #include <set>
12 #include <string>
13 #include <vector>
14
15 #include "base/callback.h"
16 #include "base/memory/scoped_refptr.h"
17 #include "build/build_config.h"
18 #include "content/common/content_export.h"
19 #include "content/public/browser/eye_dropper.h"
20 #include "content/public/browser/invalidate_type.h"
21 #include "content/public/browser/media_stream_request.h"
22 #include "content/public/browser/serial_chooser.h"
23 #include "content/public/browser/web_contents.h"
24 #include "content/public/common/window_container_type.mojom-forward.h"
25 #include "third_party/blink/public/common/mediastream/media_stream_request.h"
26 #include "third_party/blink/public/common/page/drag_operation.h"
27 #include "third_party/blink/public/mojom/choosers/color_chooser.mojom-forward.h"
28 #include "third_party/blink/public/mojom/frame/blocked_navigation_types.mojom.h"
29 #include "third_party/blink/public/mojom/frame/fullscreen.mojom-forward.h"
30 #include "third_party/blink/public/mojom/manifest/display_mode.mojom.h"
31 #include "third_party/skia/include/core/SkColor.h"
32 #include "ui/base/window_open_disposition.h"
33 #include "ui/gfx/geometry/rect_f.h"
34 #include "ui/gfx/native_widget_types.h"
35
36 #if BUILDFLAG(IS_ANDROID)
37 #include "base/android/scoped_java_ref.h"
38 #endif
39
40 class GURL;
41
42 namespace base {
43 class FilePath;
44 template <typename T>
45 class WeakPtr;
46 }
47
48 namespace blink {
49 namespace mojom {
50 class FileChooserParams;
51 class WindowFeatures;
52 }
53 }  // namespace blink
54
55 namespace content {
56 class ColorChooser;
57 class EyeDropperListener;
58 class FileSelectListener;
59 class JavaScriptDialogManager;
60 class RenderFrameHost;
61 class RenderWidgetHost;
62 class SessionStorageNamespace;
63 class SiteInstance;
64 struct ContextMenuParams;
65 struct DropData;
66 struct MediaPlayerWatchTime;
67 struct NativeWebKeyboardEvent;
68 struct Referrer;
69 }  // namespace content
70
71 namespace device {
72 namespace mojom {
73 class GeolocationContext;
74 }
75 }  // namespace device
76
77 namespace gfx {
78 class Rect;
79 class Size;
80 }
81
82 namespace url {
83 class Origin;
84 }
85
86 namespace blink {
87 class WebGestureEvent;
88 enum class ProtocolHandlerSecurityLevel;
89 }
90
91 namespace content {
92
93 class AudioStreamBrokerFactory;
94 struct OpenURLParams;
95
96 enum class KeyboardEventProcessingResult;
97
98 // Result of an EnterPictureInPicture request.
99 enum class PictureInPictureResult {
100   // The request was successful.
101   kSuccess,
102
103   // Picture-in-Picture is not supported by the embedder.
104   kNotSupported,
105 };
106
107 // Objects implement this interface to get notified about changes in the
108 // WebContents and to provide necessary functionality. If a method doesn't
109 // change state, e.g. has no return value, then it can move to
110 // WebContentsObserver if many places want to observe the change. If the
111 // implementation of one of the methods below would be shared by many or all of
112 // WebContentsDelegate implementations then it can go on ContentBrowserClient.
113 class CONTENT_EXPORT WebContentsDelegate {
114  public:
115   WebContentsDelegate();
116
117   // Opens a new URL inside the passed in WebContents (if source is 0 open
118   // in the current front-most tab), unless |disposition| indicates the url
119   // should be opened in a new tab or window.
120   //
121   // A nullptr source indicates the current tab (callers should probably use
122   // OpenURL() for these cases which does it for you).
123
124   // Returns the WebContents the URL is opened in, or nullptr if the URL wasn't
125   // opened immediately.
126   virtual WebContents* OpenURLFromTab(WebContents* source,
127                                       const OpenURLParams& params);
128
129   // Allows the delegate to optionally cancel navigations that attempt to
130   // transfer to a different process between the start of the network load and
131   // commit.  Defaults to true.
132   virtual bool ShouldAllowRendererInitiatedCrossProcessNavigation(
133       bool is_outermost_main_frame_navigation);
134
135   // Called to inform the delegate that the WebContents's navigation state
136   // changed. The |changed_flags| indicates the parts of the navigation state
137   // that have been updated.
138   virtual void NavigationStateChanged(WebContents* source,
139                                       InvalidateTypes changed_flags) {}
140
141   // Called to inform the delegate that the WebContent's visible
142   // security state changed and that security UI should be updated.
143   virtual void VisibleSecurityStateChanged(WebContents* source) {}
144
145   // Creates a new tab with the already-created WebContents `new_contents`.
146   // The window for the added contents should be reparented correctly when this
147   // method returns. `target_url` is set to the value provided when
148   // `new_contents` was created. If `disposition` is NEW_POPUP,
149   // `window_features` should hold the initial position, size and other
150   // properties of the window. If `was_blocked` is non-nullptr, then
151   // `*was_blocked` will be set to true if the popup gets blocked, and left
152   // unchanged otherwise.
153   virtual void AddNewContents(
154       WebContents* source,
155       std::unique_ptr<WebContents> new_contents,
156       const GURL& target_url,
157       WindowOpenDisposition disposition,
158       const blink::mojom::WindowFeatures& window_features,
159       bool user_gesture,
160       bool* was_blocked) {}
161
162   // Selects the specified contents, bringing its container to the front.
163   virtual void ActivateContents(WebContents* contents) {}
164
165   // Notifies the delegate that this contents is starting or is done loading
166   // some resource. The delegate should use this notification to represent
167   // loading feedback. See WebContents::IsLoading()
168   // |should_show_loading_ui| indicates whether a load start should be visible
169   // in UI elements. It is generally true for different-document navigations and
170   // false for most same-document navigations (because same-documents are
171   // typically instantaneous so there's no point in flickering the UI). The
172   // exception is the navigation API's intercept(), which is the sole type
173   // of same-document navigation that is asynchronous, and therefore a UI change
174   // is sensible.
175   virtual void LoadingStateChanged(WebContents* source,
176                                    bool should_show_loading_ui) {}
177
178   // Request the delegate to close this web contents, and do whatever cleanup
179   // it needs to do.
180   virtual void CloseContents(WebContents* source) {}
181
182   // Request the delegate to resize this WebContents to the specified size in
183   // screen coordinates. The embedder is free to ignore the request.
184   virtual void SetContentsBounds(WebContents* source, const gfx::Rect& bounds) {
185   }
186
187   // Notification that the target URL has changed.
188   virtual void UpdateTargetURL(WebContents* source,
189                                const GURL& url) {}
190
191   // Notification that there was a mouse event, along with the type of event.
192   // If |motion| is true, this is a normal motion event. If |exited| is true,
193   // the pointer left the contents area.
194   virtual void ContentsMouseEvent(WebContents* source,
195                                   bool motion,
196                                   bool exited) {}
197
198   // Request the delegate to change the zoom level of the current tab.
199   virtual void ContentsZoomChange(bool zoom_in) {}
200
201   // Called to determine if the WebContents can be overscrolled with touch/wheel
202   // gestures.
203   virtual bool CanOverscrollContent();
204
205   // Returns true if javascript dialogs and unload alerts are suppressed.
206   // Default is false.
207   virtual bool ShouldSuppressDialogs(WebContents* source);
208
209   // Returns whether pending NavigationEntries for aborted browser-initiated
210   // navigations should be preserved (and thus returned from GetVisibleURL).
211   // Defaults to false.
212   virtual bool ShouldPreserveAbortedURLs(WebContents* source);
213
214   // A message was added to the console of a frame of the page. Returning true
215   // indicates that the delegate handled the message. If false is returned the
216   // default logging mechanism will be used for the message.
217   // NOTE: If you only need to monitor messages added to the console, rather
218   // than change the behavior when they are added, prefer using
219   // WebContentsObserver::OnDidAddMessageToConsole().
220   virtual bool DidAddMessageToConsole(
221       WebContents* source,
222       blink::mojom::ConsoleMessageLevel log_level,
223       const std::u16string& message,
224       int32_t line_no,
225       const std::u16string& source_id);
226
227   // Tells us that we've finished firing this tab's beforeunload event.
228   // The proceed bool tells us whether the user chose to proceed closing the
229   // tab. Returns true if the tab can continue on firing its unload event.
230   // If we're closing the entire browser, then we'll want to delay firing
231   // unload events until all the beforeunload events have fired.
232   virtual void BeforeUnloadFired(WebContents* tab,
233                                  bool proceed,
234                                  bool* proceed_to_fire_unload);
235
236   // Returns true if the location bar should be focused by default rather than
237   // the page contents. NOTE: this is only used if WebContents can't determine
238   // for itself whether the location bar should be focused by default. For a
239   // complete check, you should use WebContents::FocusLocationBarByDefault().
240   virtual bool ShouldFocusLocationBarByDefault(WebContents* source);
241
242   // Sets focus to the location bar or some other place that is appropriate.
243   // This is called when the tab wants to encourage user input, like for the
244   // new tab page.
245   virtual void SetFocusToLocationBar() {}
246
247   // Returns whether the page should be focused when transitioning from crashed
248   // to live. Default is true.
249   virtual bool ShouldFocusPageAfterCrash();
250
251   // Returns whether the page should resume accepting requests for the new
252   // window. This is used when window creation is asynchronous
253   // and the navigations need to be delayed. Default is true.
254   virtual bool ShouldResumeRequestsForCreatedWindow();
255
256   // This is called when WebKit tells us that it is done tabbing through
257   // controls on the page. Provides a way for WebContentsDelegates to handle
258   // this. Returns true if the delegate successfully handled it.
259   virtual bool TakeFocus(WebContents* source,
260                          bool reverse);
261
262   // Asks the delegate if the given tab can download.
263   // Invoking the |callback| synchronously is OK.
264   virtual void CanDownload(const GURL& url,
265                            const std::string& request_method,
266                            base::OnceCallback<void(bool)> callback);
267
268   // Asks the delegate to open/show the context menu based on `params`.
269   //
270   // The `render_frame_host` represents the frame that requests the context menu
271   // (typically this frame is focused, but this is not necessarily the case -
272   // see https://crbug.com/1257907#c14).
273   //
274   // Returns true if the context menu operation was handled by the delegate.
275   virtual bool HandleContextMenu(RenderFrameHost& render_frame_host,
276                                  const ContextMenuParams& params);
277
278   // Allows delegates to handle keyboard events before sending to the renderer.
279   // See enum for description of return values.
280   virtual KeyboardEventProcessingResult PreHandleKeyboardEvent(
281       WebContents* source,
282       const NativeWebKeyboardEvent& event);
283
284   // Allows delegates to handle unhandled keyboard messages coming back from
285   // the renderer. Returns true if the event was handled, false otherwise. A
286   // true value means no more processing should happen on the event. The default
287   // return value is false
288   virtual bool HandleKeyboardEvent(WebContents* source,
289                                    const NativeWebKeyboardEvent& event);
290
291   // Allows delegates to handle gesture events before sending to the renderer.
292   // Returns true if the |event| was handled and thus shouldn't be processed
293   // by the renderer's event handler. Note that the touch events that create
294   // the gesture are always passed to the renderer since the gesture is created
295   // and dispatched after the touches return without being "preventDefault()"ed.
296   virtual bool PreHandleGestureEvent(
297       WebContents* source,
298       const blink::WebGestureEvent& event);
299
300   // Called when an external drag event enters the web contents window. Return
301   // true to allow dragging and dropping on the web contents window or false to
302   // cancel the operation. This method is used by Chromium Embedded Framework.
303   virtual bool CanDragEnter(WebContents* source,
304                             const DropData& data,
305                             blink::DragOperationsMask operations_allowed);
306
307   // Shows the repost form confirmation dialog box.
308   virtual void ShowRepostFormWarningDialog(WebContents* source) {}
309
310   // Allows delegate to override navigation to the history entries.
311   // Returns true to allow WebContents to continue with the default processing.
312   virtual bool OnGoToEntryOffset(int offset);
313
314   // Allows delegate to control whether a new WebContents can be created by
315   // the WebContents itself.
316   //
317   // If an delegate returns true, it can optionally also override
318   // CreateCustomWebContents() below to provide their own WebContents.
319   virtual bool IsWebContentsCreationOverridden(
320       SiteInstance* source_site_instance,
321       content::mojom::WindowContainerType window_container_type,
322       const GURL& opener_url,
323       const std::string& frame_name,
324       const GURL& target_url);
325
326   // Allow delegate to creates a custom WebContents when
327   // WebContents::CreateNewWindow() is called. This function is only called
328   // when IsWebContentsCreationOverridden() returns true.
329   //
330   // In general, a delegate should return a pointer to a created WebContents
331   // so that the opener can be given a references to it as appropriate.
332   // Returning nullptr also makes sense if the delegate wishes to suppress
333   // all window creation, or if the delegate wants to ensure the opener
334   // cannot get a reference effectively creating a new browsing instance.
335   virtual WebContents* CreateCustomWebContents(
336       RenderFrameHost* opener,
337       SiteInstance* source_site_instance,
338       bool is_new_browsing_instance,
339       const GURL& opener_url,
340       const std::string& frame_name,
341       const GURL& target_url,
342       const StoragePartitionConfig& partition_config,
343       SessionStorageNamespace* session_storage_namespace);
344
345   // Notifies the delegate about the creation of a new WebContents. This
346   // typically happens when popups are created.
347   virtual void WebContentsCreated(WebContents* source_contents,
348                                   int opener_render_process_id,
349                                   int opener_render_frame_id,
350                                   const std::string& frame_name,
351                                   const GURL& target_url,
352                                   WebContents* new_contents) {}
353
354   // Notifies the embedder that a new WebContents has been created to contain
355   // the contents of a portal.
356   virtual void PortalWebContentsCreated(WebContents* portal_web_contents) {}
357
358   // Notifies the embedder that an existing WebContents that it manages (e.g., a
359   // browser tab) has become the contents of a portal.
360   //
361   // During portal activation, WebContentsDelegate::ActivatePortalWebContents
362   // will be called to release the delegate's management of a WebContents.
363   // Shortly afterward, the portal will assume ownership of the contents and
364   // call this function to indicate that this is complete, passing the
365   // swapped-out contents as |portal_web_contents|.
366   //
367   // Implementations will likely want to apply changes analogous to those they
368   // would apply to a new WebContents in PortalWebContentsCreated.
369   virtual void WebContentsBecamePortal(WebContents* portal_web_contents) {}
370
371   // Notification that one of the frames in the WebContents is hung. |source| is
372   // the WebContents that is hung, and |render_widget_host| is the
373   // RenderWidgetHost that, while routing events to it, discovered the hang.
374   //
375   // |hang_monitor_restarter| can be used to restart the timer used to
376   // detect the hang.  The timer is typically restarted when the renderer has
377   // become active, the tab got hidden, or the user has chosen to wait some
378   // more.
379   //
380   // Useful member functions on |render_widget_host|:
381   // - Getting the hung render process: GetProcess()
382   // - Querying whether the process is still hung: IsCurrentlyUnresponsive()
383   virtual void RendererUnresponsive(
384       WebContents* source,
385       RenderWidgetHost* render_widget_host,
386       base::RepeatingClosure hang_monitor_restarter) {}
387
388   // Notification that a process in the WebContents is no longer hung. |source|
389   // is the WebContents that was hung, and |render_widget_host| is the
390   // RenderWidgetHost that was passed in an earlier call to
391   // RendererUnresponsive().
392   virtual void RendererResponsive(WebContents* source,
393                                   RenderWidgetHost* render_widget_host) {}
394
395   // Invoked when a primary main frame navigation occurs.
396   virtual void DidNavigatePrimaryMainFramePostCommit(WebContents* source) {}
397
398   // Returns a pointer to a service to manage JavaScript dialogs. May return
399   // nullptr in which case dialogs aren't shown.
400   virtual JavaScriptDialogManager* GetJavaScriptDialogManager(
401       WebContents* source);
402
403 #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC) || defined(USE_EFL)
404   // Called when color chooser should open. Returns the opened color chooser.
405   // Returns nullptr if we failed to open the color chooser. The color chooser
406   // is only supported/required for Android.
407   virtual std::unique_ptr<ColorChooser> OpenColorChooser(
408       WebContents* web_contents,
409       SkColor color,
410       const std::vector<blink::mojom::ColorSuggestionPtr>& suggestions);
411 #endif  // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
412
413   // Called when an eye dropper should open. Returns the eye dropper window.
414   // The eye dropper is responsible for calling listener->ColorSelected() or
415   // listener->ColorSelectionCanceled().
416   // The ownership of the returned pointer is transferred to the caller.
417   virtual std::unique_ptr<EyeDropper> OpenEyeDropper(
418       RenderFrameHost* frame,
419       EyeDropperListener* listener);
420
421   // Called when a file selection is to be done.
422   // This function is responsible for calling listener->FileSelected() or
423   // listener->FileSelectionCanceled().
424   virtual void RunFileChooser(RenderFrameHost* render_frame_host,
425                               scoped_refptr<FileSelectListener> listener,
426                               const blink::mojom::FileChooserParams& params);
427
428   // Request to enumerate a directory.  This is equivalent to running the file
429   // chooser in directory-enumeration mode and having the user select the given
430   // directory.
431   // This function is responsible for calling listener->FileSelected() or
432   // listener->FileSelectionCanceled().
433   virtual void EnumerateDirectory(WebContents* web_contents,
434                                   scoped_refptr<FileSelectListener> listener,
435                                   const base::FilePath& path);
436
437   // Creates an info bar for the user to control the receiving of the SMS.
438   virtual void CreateSmsPrompt(RenderFrameHost*,
439                                const std::vector<url::Origin>&,
440                                const std::string& one_time_code,
441                                base::OnceCallback<void()> on_confirm,
442                                base::OnceCallback<void()> on_cancel);
443
444   // Returns whether entering fullscreen with |EnterFullscreenModeForTab()| is
445   // allowed.
446   virtual bool CanEnterFullscreenModeForTab(
447       RenderFrameHost* requesting_frame,
448       const blink::mojom::FullscreenOptions& options);
449
450   // Called when the renderer puts a tab into fullscreen mode.
451   // |requesting_frame| is the specific content frame requesting fullscreen.
452   // |CanEnterFullscreenModeForTab()| must return true on entry.
453   virtual void EnterFullscreenModeForTab(
454       RenderFrameHost* requesting_frame,
455       const blink::mojom::FullscreenOptions& options) {}
456
457   virtual void FullscreenStateChangedForTab(
458       RenderFrameHost* requesting_frame,
459       const blink::mojom::FullscreenOptions& options) {}
460
461   // Called when the renderer puts a tab out of fullscreen mode.
462   virtual void ExitFullscreenModeForTab(WebContents*) {}
463
464   // Returns true if the given `web_contents` is, or is transitioning to
465   // tab-fullscreen.
466   virtual bool IsFullscreenForTabOrPending(const WebContents* web_contents);
467
468   // Overload of IsFullscreenForTabOrPending which also outputs the current or
469   // target display of the fullscreen tab. If the function returns true and
470   // `display_id` is not nullptr, the target display ID of the tab will be
471   // written to `display_id`.
472   virtual bool IsFullscreenForTabOrPending(const WebContents* web_contents,
473                                            int64_t* display_id);
474
475   // Returns the actual display mode of the top-level browsing context.
476   // For example, it should return 'blink::mojom::DisplayModeFullscreen'
477   // whenever the browser window is put to fullscreen mode (either by the end
478   // user, or HTML API or from a web manifest setting). See
479   // http://w3c.github.io/manifest/#dfn-display-mode
480   virtual blink::mojom::DisplayMode GetDisplayMode(
481       const WebContents* web_contents);
482
483   // Returns the security level to use for Navigator.RegisterProtocolHandler().
484   virtual blink::ProtocolHandlerSecurityLevel GetProtocolHandlerSecurityLevel(
485       RenderFrameHost* requesting_frame);
486
487   // Register a new handler for URL requests with the given scheme.
488   // |user_gesture| is true if the registration is made in the context of a user
489   // gesture.
490   virtual void RegisterProtocolHandler(RenderFrameHost* requesting_frame,
491                                        const std::string& protocol,
492                                        const GURL& url,
493                                        bool user_gesture) {}
494
495   // Unregister the registered handler for URL requests with the given scheme.
496   // |user_gesture| is true if the registration is made in the context of a user
497   // gesture.
498   virtual void UnregisterProtocolHandler(RenderFrameHost* requesting_frame,
499                                          const std::string& protocol,
500                                          const GURL& url,
501                                          bool user_gesture) {}
502
503   // Result of string search in the page. This includes the number of matches
504   // found and the selection rect (in screen coordinates) for the string found.
505   // If |final_update| is false, it indicates that more results follow.
506   virtual void FindReply(WebContents* web_contents,
507                          int request_id,
508                          int number_of_matches,
509                          const gfx::Rect& selection_rect,
510                          int active_match_ordinal,
511                          bool final_update) {}
512
513 #if defined(USE_EFL)
514   virtual void DidRenderFrame() {}
515 #endif
516
517 #if BUILDFLAG(IS_ANDROID)
518   // Provides the rects of the current find-in-page matches.
519   // Sent as a reply to RequestFindMatchRects.
520   virtual void FindMatchRectsReply(WebContents* web_contents,
521                                    int version,
522                                    const std::vector<gfx::RectF>& rects,
523                                    const gfx::RectF& active_rect) {}
524 #endif
525
526   // Invoked when the preferred size of the contents has been changed.
527   virtual void UpdatePreferredSize(WebContents* web_contents,
528                                    const gfx::Size& pref_size) {}
529
530   // Invoked when the contents auto-resized and the container should match it.
531   virtual void ResizeDueToAutoResize(WebContents* web_contents,
532                                      const gfx::Size& new_size) {}
533
534   // Requests to lock the mouse. Once the request is approved or rejected,
535   // GotResponseToLockMouseRequest() will be called on the requesting tab
536   // contents.
537   virtual void RequestToLockMouse(WebContents* web_contents,
538                                   bool user_gesture,
539                                   bool last_unlocked_by_target);
540
541   // Notification that the page has lost the mouse lock.
542   virtual void LostMouseLock() {}
543
544   // Requests keyboard lock. Once the request is approved or rejected,
545   // GotResponseToKeyboardLockRequest() will be called on |web_contents|.
546   virtual void RequestKeyboardLock(WebContents* web_contents,
547                                    bool esc_key_locked);
548
549   // Notification that the keyboard lock request has been canceled.
550   virtual void CancelKeyboardLockRequest(WebContents* web_contents) {}
551
552   // Asks permission to use the camera and/or microphone. If permission is
553   // granted, a call should be made to |callback| with the devices. If the
554   // request is denied, a call should be made to |callback| with an empty list
555   // of devices. |request| has the details of the request (e.g. which of audio
556   // and/or video devices are requested, and lists of available devices).
557   virtual void RequestMediaAccessPermission(
558       WebContents* web_contents,
559       const MediaStreamRequest& request,
560       content::MediaResponseCallback callback);
561
562   // Checks if we have permission to access the microphone or camera. Note that
563   // this does not query the user. |type| must be MEDIA_DEVICE_AUDIO_CAPTURE
564   // or MEDIA_DEVICE_VIDEO_CAPTURE.
565   virtual bool CheckMediaAccessPermission(RenderFrameHost* render_frame_host,
566                                           const GURL& security_origin,
567                                           blink::mojom::MediaStreamType type);
568
569   // Returns the ID of the default device for the given media device |type|.
570   // If the returned value is an empty string, it means that there is no
571   // default device for the given |type|.
572   virtual std::string GetDefaultMediaDeviceID(
573       WebContents* web_contents,
574       blink::mojom::MediaStreamType type);
575
576   // Returns the human-readable name for title in Media Controls.
577   // If the returned value is an empty string, it means that there is no
578   // human-readable name.
579   // For example, this returns an extension name for title instead of extension
580   // url.
581   virtual std::string GetTitleForMediaControls(WebContents* web_contents);
582
583   // Returns AudioStreamBrokerFactory to use to create AudioStreamBroker when
584   // creating audio I/O streams. Returned `AudioStreamBrokerFactory` is used and
585   // deleted on the IO thread.
586   virtual std::unique_ptr<AudioStreamBrokerFactory>
587   CreateAudioStreamBrokerFactory(WebContents* web_contents);
588
589 #if BUILDFLAG(IS_ANDROID)
590   // Returns true if the given media should be blocked to load.
591   virtual bool ShouldBlockMediaRequest(const GURL& url);
592
593   // Tells the delegate to enter overlay mode.
594   // Overlay mode means that we are currently using AndroidOverlays to display
595   // video, and that the compositor's surface should support alpha and not be
596   // marked as opaque. See media/base/android/android_overlay.h.
597   virtual void SetOverlayMode(bool use_overlay_mode) {}
598 #endif
599
600   // Returns the size for the new render view created for the pending entry in
601   // |web_contents|; if there's no size, returns an empty size.
602   // This is optional for implementations of WebContentsDelegate; if the
603   // delegate doesn't provide a size, the current WebContentsView's size will be
604   // used.
605   virtual gfx::Size GetSizeForNewRenderView(WebContents* web_contents);
606
607   // Returns true if the WebContents is never user-visible, thus the renderer
608   // never needs to produce pixels for display.
609   virtual bool IsNeverComposited(WebContents* web_contents);
610
611   // Askss |guest_web_contents| to perform the same. If this returns true, the
612   // default behavior is suppressed.
613   virtual bool GuestSaveFrame(WebContents* guest_web_contents);
614
615   // Called in response to a request to save a frame. If this returns true, the
616   // default behavior is suppressed.
617   virtual bool SaveFrame(const GURL& url,
618                          const Referrer& referrer,
619                          content::RenderFrameHost* rfh);
620
621   // Called when a suspicious navigation of the main frame has been blocked.
622   // Allows the delegate to provide some UI to let the user know about the
623   // blocked navigation and give them the option to recover from it.
624   // |blocked_url| is the blocked navigation target, |initiator_url| is the URL
625   // of the frame initiating the navigation, |reason| specifies why the
626   // navigation was blocked.
627   virtual void OnDidBlockNavigation(
628       WebContents* web_contents,
629       const GURL& blocked_url,
630       const GURL& initiator_url,
631       blink::mojom::NavigationBlockedReason reason) {}
632
633   // Reports that passive mixed content was found at the specified url.
634   virtual void PassiveInsecureContentFound(const GURL& resource_url) {}
635
636   // Checks if running of active mixed content is allowed for the specified
637   // WebContents/tab.
638   virtual bool ShouldAllowRunningInsecureContent(WebContents* web_contents,
639                                                  bool allowed_per_prefs,
640                                                  const url::Origin& origin,
641                                                  const GURL& resource_url);
642
643   virtual void SetTopControlsShownRatio(WebContents* web_contents,
644                                         float ratio) {}
645
646   // Requests to get browser controls info such as the height/min height of the
647   // top/bottom controls, and whether to animate these changes to height or
648   // whether they will shrink the Blink's view size. Note that they are not
649   // complete in the sense that there is no API to tell content to poll these
650   // values again, except part of resize. But this is not needed by embedder
651   // because it's always accompanied by view size change.
652   virtual int GetTopControlsHeight();
653   virtual int GetTopControlsMinHeight();
654   virtual int GetBottomControlsHeight();
655   virtual int GetBottomControlsMinHeight();
656   virtual bool ShouldAnimateBrowserControlsHeightChanges();
657   virtual bool DoBrowserControlsShrinkRendererSize(WebContents* web_contents);
658   // Returns true if the top controls should only expand at the top of the page,
659   // so they'll only be visible if the page is scrolled to the top.
660   virtual bool OnlyExpandTopControlsAtPageTop();
661
662   // Propagates to the browser that gesture scrolling has changed state. This is
663   // used by the browser to assist in controlling the behavior of sliding the
664   // top controls as a result of page gesture scrolling while in tablet mode.
665   virtual void SetTopControlsGestureScrollInProgress(bool in_progress) {}
666
667   // Requests to print an out-of-process subframe for the specified WebContents.
668   // |rect| is the rectangular area where its content resides in its parent
669   // frame. |document_cookie| is a unique id for a printed document associated
670   // with a print job. |subframe_host| is the render frame host of the subframe
671   // to be printed.
672   virtual void PrintCrossProcessSubframe(WebContents* web_contents,
673                                          const gfx::Rect& rect,
674                                          int document_cookie,
675                                          RenderFrameHost* subframe_host) const {
676   }
677
678   // Requests to capture a paint preview of a subframe for the specified
679   // WebContents. |rect| is the rectangular area where its content resides in
680   // its parent frame. |guid| is a globally unique identitier for an entire
681   // paint preview. |render_frame_host| is the render frame host of the subframe
682   // to be captured.
683   virtual void CapturePaintPreviewOfSubframe(
684       WebContents* web_contents,
685       const gfx::Rect& rect,
686       const base::UnguessableToken& guid,
687       RenderFrameHost* render_frame_host) {}
688
689   // Notifies the Picture-in-Picture controller that there is a new player
690   // entering Picture-in-Picture.
691   // Returns the result of the enter request.
692   virtual PictureInPictureResult EnterPictureInPicture(
693       WebContents* web_contents);
694
695   // Updates the Picture-in-Picture controller with a signal that
696   // Picture-in-Picture mode has ended.
697   virtual void ExitPictureInPicture() {}
698
699 #if BUILDFLAG(IS_ANDROID)
700   // Updates information to determine whether a user gesture should carryover to
701   // future navigations. This is needed so navigations within a certain
702   // timeframe of a request initiated by a gesture will be treated as if they
703   // were initiated by a gesture too, otherwise the navigation may be blocked.
704   virtual void UpdateUserGestureCarryoverInfo(WebContents* web_contents) {}
705 #endif
706
707   // Returns true if lazy loading of images and frames should be enabled.
708   virtual bool ShouldAllowLazyLoad();
709
710   // Return true if the back forward cache is supported. This is not an
711   // indication that the cache will be used.
712   virtual bool IsBackForwardCacheSupported();
713
714   // Returns true if Prerender2 (see
715   // content/browser/preloading/prerender/README.md for details) is supported.
716   virtual bool IsPrerender2Supported(WebContents& web_contents);
717
718   // Requests the delegate to replace |predecessor_contents| with
719   // |portal_contents| in the container that holds |predecessor_contents|. If
720   // the delegate successfully replaces |predecessor_contents|, the return
721   // parameter passes ownership of |predecessor_contents|. Otherwise,
722   // |portal_contents| is returned.
723   virtual std::unique_ptr<WebContents> ActivatePortalWebContents(
724       WebContents* predecessor_contents,
725       std::unique_ptr<WebContents> portal_contents);
726
727   // If |old_contents| is being inspected by a DevTools window, it updates the
728   // window to inspect |new_contents| instead and calls |callback| after it
729   // finishes asynchronously. If no window is present, or no update is
730   // necessary, |callback| is run synchronously (immediately on the same stack).
731   virtual void UpdateInspectedWebContentsIfNecessary(
732       WebContents* old_contents,
733       WebContents* new_contents,
734       base::OnceCallback<void()> callback);
735
736   // Returns true if the widget's frame content needs to be stored before
737   // eviction and displayed until a new frame is generated. If false, a white
738   // solid color is displayed instead.
739   virtual bool ShouldShowStaleContentOnEviction(WebContents* source);
740
741   // Returns the user-visible WebContents that is responsible for the activity
742   // in the provided WebContents. For example, this delegate may be aware that
743   // the contents is embedded in some other contents, or hosts background
744   // activity on behalf of a user-visible tab which should be used to display
745   // dialogs and similar affordances to the user.
746   //
747   // This may be distinct from the outer web contents (for example, the
748   // responsible contents may logically "own" a contents but not currently embed
749   // it for rendering).
750   //
751   // For most delegates (where the WebContents is a tab, window or other
752   // directly user-visible feature), simply returning the contents is
753   // appropriate.
754   virtual WebContents* GetResponsibleWebContents(WebContents* web_contents);
755
756   // Invoked when media playback is interrupted or completed.
757   virtual void MediaWatchTimeChanged(const MediaPlayerWatchTime& watch_time) {}
758
759   // Returns a  InstalledWebappGeolocationContext if this web content is running
760   // in a installed webapp and geolocation should be deleagted from the
761   // installed webapp; otherwise returns nullptr.
762   virtual device::mojom::GeolocationContext*
763   GetInstalledWebappGeolocationContext();
764
765   // Returns a weak ptr to the web contents delegate.
766   virtual base::WeakPtr<WebContentsDelegate> GetDelegateWeakPtr();
767
768   // Whether the WebContents is privileged.
769   // It's used to prevent drag and drop between privileged and non-privileged
770   // WebContents.
771   virtual bool IsPrivileged();
772
773  protected:
774   virtual ~WebContentsDelegate();
775
776  private:
777   friend class WebContentsImpl;
778
779   // Called when |this| becomes the WebContentsDelegate for |source|.
780   void Attach(WebContents* source);
781
782   // Called when |this| is no longer the WebContentsDelegate for |source|.
783   void Detach(WebContents* source);
784
785   // The WebContents that this is currently a delegate for.
786   std::set<WebContents*> attached_contents_;
787 };
788
789 }  // namespace content
790
791 #endif  // CONTENT_PUBLIC_BROWSER_WEB_CONTENTS_DELEGATE_H_