Enable IME support for Ozone Efl
[platform/framework/web/chromium-efl.git] / content / browser / web_contents / web_contents_impl.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_BROWSER_WEB_CONTENTS_WEB_CONTENTS_IMPL_H_
6 #define CONTENT_BROWSER_WEB_CONTENTS_WEB_CONTENTS_IMPL_H_
7
8 #include <stdint.h>
9
10 #include <functional>
11 #include <map>
12 #include <memory>
13 #include <set>
14 #include <string>
15 #include <utility>
16 #include <vector>
17
18 #include "base/callback_helpers.h"
19 #include "base/callback_list.h"
20 #include "base/containers/flat_map.h"
21 #include "base/functional/function_ref.h"
22 #include "base/gtest_prod_util.h"
23 #include "base/memory/raw_ptr.h"
24 #include "base/memory/safe_ref.h"
25 #include "base/observer_list.h"
26 #include "base/process/kill.h"
27 #include "base/scoped_observation.h"
28 #include "base/time/time.h"
29 #include "build/build_config.h"
30 #include "components/download/public/common/download_url_parameters.h"
31 #include "content/browser/media/audio_stream_monitor.h"
32 #include "content/browser/media/forwarding_audio_stream_factory.h"
33 #include "content/browser/preloading/prerender/prerender_handle_impl.h"
34 #include "content/browser/renderer_host/frame_tree.h"
35 #include "content/browser/renderer_host/frame_tree_node.h"
36 #include "content/browser/renderer_host/navigation_controller_delegate.h"
37 #include "content/browser/renderer_host/navigation_controller_impl.h"
38 #include "content/browser/renderer_host/navigator_delegate.h"
39 #include "content/browser/renderer_host/page_delegate.h"
40 #include "content/browser/renderer_host/page_impl.h"
41 #include "content/browser/renderer_host/render_frame_host_delegate.h"
42 #include "content/browser/renderer_host/render_frame_host_manager.h"
43 #include "content/browser/renderer_host/render_view_host_delegate.h"
44 #include "content/browser/renderer_host/render_view_host_impl.h"
45 #include "content/browser/renderer_host/render_widget_host_delegate.h"
46 #include "content/browser/renderer_host/visible_time_request_trigger.h"
47 #include "content/browser/starscan_load_observer.h"
48 #include "content/browser/web_contents/file_chooser_impl.h"
49 #include "content/common/content_export.h"
50 #include "content/public/browser/global_routing_id.h"
51 #include "content/public/browser/media_stream_request.h"
52 #include "content/public/browser/mhtml_generation_result.h"
53 #include "content/public/browser/web_contents.h"
54 #include "content/public/browser/web_contents_observer.h"
55 #include "mojo/public/cpp/bindings/pending_associated_receiver.h"
56 #include "mojo/public/cpp/bindings/pending_receiver.h"
57 #include "mojo/public/cpp/bindings/pending_remote.h"
58 #include "mojo/public/cpp/bindings/remote.h"
59 #include "net/base/load_states.h"
60 #include "ppapi/buildflags/buildflags.h"
61 #include "services/device/public/mojom/geolocation_context.mojom.h"
62 #include "services/network/public/mojom/fetch_api.mojom-forward.h"
63 #include "third_party/abseil-cpp/absl/types/optional.h"
64 #include "third_party/blink/public/common/frame/transient_allow_fullscreen.h"
65 #include "third_party/blink/public/common/renderer_preferences/renderer_preferences.h"
66 #include "third_party/blink/public/common/web_preferences/web_preferences.h"
67 #include "third_party/blink/public/mojom/choosers/color_chooser.mojom.h"
68 #include "third_party/blink/public/mojom/choosers/popup_menu.mojom-forward.h"
69 #include "third_party/blink/public/mojom/frame/blocked_navigation_types.mojom-shared.h"
70 #include "third_party/blink/public/mojom/frame/frame.mojom-forward.h"
71 #include "third_party/blink/public/mojom/frame/text_autosizer_page_info.mojom.h"
72 #include "third_party/blink/public/mojom/loader/resource_load_info.mojom-forward.h"
73 #include "third_party/blink/public/mojom/media/capture_handle_config.mojom.h"
74 #include "third_party/blink/public/mojom/page/display_cutout.mojom-shared.h"
75 #include "third_party/blink/public/mojom/page/page_visibility_state.mojom-shared.h"
76 #include "ui/accessibility/ax_mode.h"
77 #include "ui/accessibility/platform/inspect/ax_event_recorder.h"
78 #include "ui/base/dragdrop/mojom/drag_drop_types.mojom-forward.h"
79 #include "ui/base/ime/mojom/virtual_keyboard_types.mojom.h"
80 #include "ui/color/color_provider_source_observer.h"
81 #include "ui/gfx/geometry/size.h"
82 #include "ui/native_theme/native_theme.h"
83 #include "ui/native_theme/native_theme_observer.h"
84
85 #if BUILDFLAG(IS_ANDROID)
86 #include "content/public/browser/android/child_process_importance.h"
87 #endif
88
89 #if defined(USE_EFL)
90 #include <Evas.h>
91 #endif
92
93 namespace base {
94 class FilePath;
95 }  // namespace base
96
97 namespace device {
98 namespace mojom {
99 class WakeLock;
100 }
101 }  // namespace device
102
103 namespace power_scheduler {
104 class PowerModeVoter;
105 }
106
107 namespace service_manager {
108 class InterfaceProvider;
109 }  // namespace service_manager
110
111 namespace content {
112 namespace {
113 class JavaScriptDialogDismissNotifier;
114 }
115 enum class PictureInPictureResult;
116 class BeforeUnloadBlockingDelegate;  // content_browser_test_utils_internal.h
117 class BrowserPluginEmbedder;
118 class BrowserPluginGuest;
119 class DisplayCutoutHostImpl;
120 class FindRequestManager;
121 class JavaScriptDialogManager;
122 class MediaWebContentsObserver;
123 class NFCHost;
124 class Portal;
125 class RenderFrameHost;
126 class RenderFrameHostImpl;
127 class RenderViewHost;
128 class RenderViewHostDelegateView;
129 class RenderWidgetHostImpl;
130 class RenderWidgetHostInputEventRouter;
131 class SavePackage;
132 class ScreenChangeMonitor;
133 class ScreenOrientationProvider;
134 class SiteInstanceGroup;
135 // For web_contents_impl_browsertest.cc
136 class TestWCDelegateForDialogsAndFullscreen;
137 class TestWebContents;
138 class TextInputManager;
139 class WakeLockContextHost;
140 class WebContentsDelegate;
141 class WebContentsImpl;
142 class WebContentsView;
143 struct AXEventNotificationDetails;
144 struct LoadNotificationDetails;
145 struct MHTMLGenerationParams;
146 class PreloadingAttempt;
147
148 namespace mojom {
149 class CreateNewWindowParams;
150 }  // namespace mojom
151
152 #if BUILDFLAG(IS_ANDROID)
153 class WebContentsAndroid;
154 #endif
155
156 #if BUILDFLAG(ENABLE_PPAPI)
157 class PepperPlaybackObserver;
158 #endif
159
160 #if defined(USE_EFL)
161 class WebContentsImplEfl;
162 #endif
163
164 // CreatedWindow holds the WebContentsImpl and target url between IPC calls to
165 // CreateNewWindow and ShowCreatedWindow.
166 struct CONTENT_EXPORT CreatedWindow {
167   CreatedWindow();
168   CreatedWindow(std::unique_ptr<WebContentsImpl> contents, GURL target_url);
169   CreatedWindow(CreatedWindow&&);
170   CreatedWindow(const CreatedWindow&) = delete;
171   CreatedWindow& operator=(CreatedWindow&&);
172   CreatedWindow& operator=(const CreatedWindow&) = delete;
173   ~CreatedWindow();
174
175   std::unique_ptr<WebContentsImpl> contents;
176   GURL target_url;
177 };
178
179 using PageVisibilityState = blink::mojom::PageVisibilityState;
180
181 class CONTENT_EXPORT WebContentsImpl : public WebContents,
182                                        public FrameTree::Delegate,
183                                        public RenderFrameHostDelegate,
184                                        public RenderViewHostDelegate,
185                                        public RenderWidgetHostDelegate,
186                                        public RenderFrameHostManager::Delegate,
187                                        public PageDelegate,
188                                        public blink::mojom::ColorChooserFactory,
189                                        public NavigationControllerDelegate,
190                                        public NavigatorDelegate,
191                                        public ui::NativeThemeObserver,
192                                        public ui::ColorProviderSourceObserver {
193  public:
194   class FriendWrapper;
195
196   WebContentsImpl(const WebContentsImpl&) = delete;
197   WebContentsImpl& operator=(const WebContentsImpl&) = delete;
198
199   ~WebContentsImpl() override;
200
201   static std::unique_ptr<WebContentsImpl> CreateWithOpener(
202       const WebContents::CreateParams& params,
203       RenderFrameHostImpl* opener_rfh);
204
205   static std::vector<WebContentsImpl*> GetAllWebContents();
206
207   static WebContentsImpl* FromFrameTreeNode(
208       const FrameTreeNode* frame_tree_node);
209   static WebContents* FromRenderFrameHostID(
210       GlobalRenderFrameHostId render_frame_host_id);
211   static WebContents* FromRenderFrameHostID(int render_process_host_id,
212                                             int render_frame_host_id);
213   static WebContents* FromFrameTreeNodeId(int frame_tree_node_id);
214   static WebContentsImpl* FromOuterFrameTreeNode(
215       const FrameTreeNode* frame_tree_node);
216   static WebContentsImpl* FromRenderWidgetHostImpl(RenderWidgetHostImpl* rwh);
217   static WebContentsImpl* FromRenderFrameHostImpl(RenderFrameHostImpl* rfh);
218
219   // Complex initialization here. Specifically needed to avoid having
220   // members call back into our virtual functions in the constructor.
221   // The primary main frame policy might be passed down as it is inherited from
222   // the opener when WebContents is created with an opener.
223   virtual void Init(const WebContents::CreateParams& params,
224                     blink::FramePolicy primary_main_frame_policy);
225
226 #if defined(USE_EFL)
227   void CreateEflNativeView();
228   Evas_Object* GetEflNativeView() const { return efl_native_view_; }
229   void set_ewk_view(void* ewk_view) { ewk_view_ = ewk_view; }
230   void* ewk_view() const { return ewk_view_; }
231 #endif
232
233   // Returns the SavePackage which manages the page saving job. May be NULL.
234   SavePackage* save_package() const { return save_package_.get(); }
235
236   // Expose the render manager for testing.
237   // TODO(creis): Remove this now that we can get to it via FrameTreeNode.
238   RenderFrameHostManager* GetRenderManagerForTesting();
239
240   // Sets a BrowserPluginGuest object for this WebContents. If this WebContents
241   // has a BrowserPluginGuest then that implies that it is being hosted by
242   // a BrowserPlugin object in an embedder renderer process.
243   void SetBrowserPluginGuest(std::unique_ptr<BrowserPluginGuest> guest);
244
245   // Returns embedder browser plugin object, or NULL if this WebContents is not
246   // an embedder.
247   BrowserPluginEmbedder* GetBrowserPluginEmbedder() const;
248
249   // Returns guest browser plugin object, or nullptr if this WebContents is not
250   // for guest.
251   BrowserPluginGuest* GetBrowserPluginGuest() const;
252
253   // Creates a BrowserPluginEmbedder object for this WebContents if one doesn't
254   // already exist.
255   void CreateBrowserPluginEmbedderIfNecessary();
256
257   // Cancels modal dialogs in this WebContents, as well as in any browser
258   // plugins it is hosting.
259   void CancelActiveAndPendingDialogs();
260
261   // Informs the render view host and the BrowserPluginEmbedder, if present, of
262   // a Drag Source End.
263   void DragSourceEndedAt(float client_x,
264                          float client_y,
265                          float screen_x,
266                          float screen_y,
267                          ui::mojom::DragOperation operation,
268                          RenderWidgetHost* source_rwh);
269
270   // Notification that the RenderViewHost's load state changed.
271   void LoadStateChanged(network::mojom::LoadInfoPtr load_info);
272
273   // Updates the visibility and notifies observers. Note that this is
274   // distinct from UpdateWebContentsVisibility which may also update the
275   // visibility of renderer-side objects.
276   void SetVisibilityAndNotifyObservers(Visibility visibility);
277
278   // Notify observers that the web contents has been focused.
279   void NotifyWebContentsFocused(RenderWidgetHost* render_widget_host);
280
281   // Notify observers that the web contents has lost focus.
282   void NotifyWebContentsLostFocus(RenderWidgetHost* render_widget_host);
283
284   WebContentsView* GetView() const;
285
286   // Called on screen information changes; |is_multi_screen_changed| is true iff
287   // the plurality of connected screens changed (e.g. 1 screen <-> 2 screens).
288   void OnScreensChange(bool is_multi_screen_changed);
289
290   void OnScreenOrientationChange();
291
292   ScreenOrientationProvider* GetScreenOrientationProviderForTesting() const {
293     return screen_orientation_provider_.get();
294   }
295
296   // Adds the given accessibility mode to the current accessibility mode
297   // bitmap.
298   void AddAccessibilityMode(ui::AXMode mode);
299
300   // Sets the zoom level for frames associated with this WebContents.
301   void UpdateZoom();
302
303   // Sets the zoom level for frames associated with this WebContents if it
304   // matches |host| and (if non-empty) |scheme|. Matching is done on the
305   // last committed entry.
306   void UpdateZoomIfNecessary(const std::string& scheme,
307                              const std::string& host);
308
309   // Returns the focused WebContents.
310   // If there are multiple inner/outer WebContents (when embedding <webview>,
311   // <guestview>, ...) returns the single one containing the currently focused
312   // frame. Otherwise, returns this WebContents.
313   WebContentsImpl* GetFocusedWebContents();
314
315   // Returns the focused FrameTree. For MPArch we may return a different
316   // focused frame tree even though the focused WebContents is the same.
317   FrameTree* GetFocusedFrameTree();
318
319   // TODO(lukasza): Maybe this method can be removed altogether (so that the
320   // focus of the location bar is only set in the //chrome layer).
321   void SetFocusToLocationBar();
322
323   // Returns a vector containing this WebContents and all inner WebContents
324   // within it (recursively).
325   std::vector<WebContentsImpl*> GetWebContentsAndAllInner();
326
327   // Returns the primary FrameTree for this WebContents (as opposed to the
328   // ones held by MPArch features like Prerender or Fenced Frame).
329   FrameTree& GetPrimaryFrameTree() { return primary_frame_tree_; }
330
331   // Whether the initial empty page of this view has been accessed by another
332   // page, making it unsafe to show the pending URL. Always false after the
333   // first commit.
334   // TODO(https://crbug.com/1170277): Rename to HasAccessedInitialMainDocument
335   bool HasAccessedInitialDocument();
336
337 #if BUILDFLAG(IS_ANDROID)
338   void SetPrimaryMainFrameImportance(ChildProcessImportance importance);
339 #endif
340
341   // Returns the human-readable name for title in Media Controls.
342   // If the returned value is an empty string, it means that there is no
343   // human-readable name.
344   std::string GetTitleForMediaControls();
345
346   // Returns true if this WebContents is in fullscreen (or pending fullscreen)
347   // on the specified display ID.
348   bool IsFullscreenOnDisplay(int64_t display_id) const;
349
350   // WebContents ------------------------------------------------------
351   WebContentsDelegate* GetDelegate() override;
352   void SetDelegate(WebContentsDelegate* delegate) override;
353   NavigationControllerImpl& GetController() override;
354   BrowserContext* GetBrowserContext() override;
355   base::WeakPtr<WebContents> GetWeakPtr() override;
356   const GURL& GetURL() override;
357   const GURL& GetVisibleURL() override;
358   const GURL& GetLastCommittedURL() override;
359   RenderFrameHostImpl* GetPrimaryMainFrame() override;
360   PageImpl& GetPrimaryPage() override;
361   RenderFrameHostImpl* GetFocusedFrame() override;
362   bool IsPrerenderedFrame(int frame_tree_node_id) override;
363   RenderFrameHostImpl* UnsafeFindFrameByFrameTreeNodeId(
364       int frame_tree_node_id) override;
365   void ForEachRenderFrameHostWithAction(
366       base::FunctionRef<FrameIterationAction(RenderFrameHost*)> on_frame)
367       override;
368   void ForEachRenderFrameHost(
369       base::FunctionRef<void(RenderFrameHost*)> on_frame) override;
370   RenderViewHostImpl* GetRenderViewHost() override;
371   RenderWidgetHostView* GetRenderWidgetHostView() override;
372   RenderWidgetHostView* GetTopLevelRenderWidgetHostView() override;
373   void ClosePage() override;
374   absl::optional<SkColor> GetThemeColor() override;
375   absl::optional<SkColor> GetBackgroundColor() override;
376   void SetPageBaseBackgroundColor(absl::optional<SkColor> color) override;
377   void SetColorProviderSource(ui::ColorProviderSource* source) override;
378   WebUI* GetWebUI() override;
379   void SetUserAgentOverride(const blink::UserAgentOverride& ua_override,
380                             bool override_in_new_tabs) override;
381   void SetRendererInitiatedUserAgentOverrideOption(
382       NavigationController::UserAgentOverrideOption option) override;
383   const blink::UserAgentOverride& GetUserAgentOverride() override;
384   bool ShouldOverrideUserAgentForRendererInitiatedNavigation() override;
385   void EnableWebContentsOnlyAccessibilityMode() override;
386   bool IsWebContentsOnlyAccessibilityModeForTesting() override;
387   bool IsFullAccessibilityModeForTesting() override;
388   const std::u16string& GetTitle() override;
389   void UpdateTitleForEntry(NavigationEntry* entry,
390                            const std::u16string& title) override;
391   SiteInstanceImpl* GetSiteInstance() override;
392   bool IsLoading() override;
393   double GetLoadProgress() override;
394   bool ShouldShowLoadingUI() override;
395   bool IsDocumentOnLoadCompletedInPrimaryMainFrame() override;
396   bool IsWaitingForResponse() override;
397   const net::LoadStateWithParam& GetLoadState() override;
398   const std::u16string& GetLoadStateHost() override;
399   void RequestAXTreeSnapshot(AXTreeSnapshotCallback callback,
400                              ui::AXMode ax_mode,
401                              bool exclude_offscreen,
402                              size_t max_nodes,
403                              base::TimeDelta timeout) override;
404   uint64_t GetUploadSize() override;
405   uint64_t GetUploadPosition() override;
406   const std::string& GetEncoding() override;
407   bool WasDiscarded() override;
408   void SetWasDiscarded(bool was_discarded) override;
409   [[nodiscard]] base::ScopedClosureRunner IncrementCapturerCount(
410       const gfx::Size& capture_size,
411       bool stay_hidden,
412       bool stay_awake,
413       bool is_activity = true) override;
414   const blink::mojom::CaptureHandleConfig& GetCaptureHandleConfig() override;
415   bool IsBeingCaptured() override;
416   bool IsBeingVisiblyCaptured() override;
417   bool IsAudioMuted() override;
418   void SetAudioMuted(bool mute) override;
419   bool IsCurrentlyAudible() override;
420   bool IsConnectedToBluetoothDevice() override;
421   bool IsScanningForBluetoothDevices() override;
422   bool IsConnectedToSerialPort() override;
423   bool IsConnectedToHidDevice() override;
424   bool IsConnectedToUsbDevice() override;
425   bool HasFileSystemAccessHandles() override;
426   bool HasPictureInPictureVideo() override;
427   bool HasPictureInPictureDocument() override;
428   bool IsCrashed() override;
429   base::TerminationStatus GetCrashedStatus() override;
430   int GetCrashedErrorCode() override;
431   bool IsBeingDestroyed() override;
432   void NotifyNavigationStateChanged(InvalidateTypes changed_flags) override;
433   void OnAudioStateChanged() override;
434   base::TimeTicks GetLastActiveTime() override;
435   void WasShown() override;
436   void WasHidden() override;
437   void WasOccluded() override;
438   Visibility GetVisibility() override;
439   bool NeedToFireBeforeUnloadOrUnloadEvents() override;
440   void DispatchBeforeUnload(bool auto_cancel) override;
441   void AttachInnerWebContents(
442       std::unique_ptr<WebContents> inner_web_contents,
443       RenderFrameHost* render_frame_host,
444       mojo::PendingAssociatedRemote<blink::mojom::RemoteFrame> remote_frame,
445       mojo::PendingAssociatedReceiver<blink::mojom::RemoteFrameHost>
446           remote_frame_host_receiver,
447       bool is_full_page) override;
448   bool IsInnerWebContentsForGuest() override;
449   bool IsPortal() override;
450   WebContentsImpl* GetPortalHostWebContents() override;
451   RenderFrameHostImpl* GetOuterWebContentsFrame() override;
452   WebContentsImpl* GetOuterWebContents() override;
453   WebContentsImpl* GetOutermostWebContents() override;
454   std::vector<WebContents*> GetInnerWebContents() override;
455   WebContentsImpl* GetResponsibleWebContents() override;
456   void DidChangeVisibleSecurityState() override;
457   void SyncRendererPrefs() override;
458   void Stop() override;
459   void SetPageFrozen(bool frozen) override;
460   std::unique_ptr<WebContents> Clone() override;
461   void ReloadFocusedFrame() override;
462   void Undo() override;
463   void Redo() override;
464   void Cut() override;
465   void Copy() override;
466   void CopyToFindPboard() override;
467   void Paste() override;
468   void PasteAndMatchStyle() override;
469   void Delete() override;
470   void SelectAll() override;
471   void CollapseSelection() override;
472   void ScrollToTopOfDocument() override;
473   void ScrollToBottomOfDocument() override;
474   void Replace(const std::u16string& word) override;
475   void ReplaceMisspelling(const std::u16string& word) override;
476   void NotifyContextMenuClosed(const GURL& link_followed) override;
477   void ExecuteCustomContextMenuCommand(int action,
478                                        const GURL& link_followed) override;
479   gfx::NativeView GetNativeView() override;
480   gfx::NativeView GetContentNativeView() override;
481   gfx::NativeWindow GetTopLevelNativeWindow() override;
482   gfx::Rect GetContainerBounds() override;
483   gfx::Rect GetViewBounds() override;
484   DropData* GetDropData() override;
485   void Focus() override;
486   void SetInitialFocus() override;
487   void StoreFocus() override;
488   void RestoreFocus() override;
489   void FocusThroughTabTraversal(bool reverse) override;
490   bool IsSavable() override;
491   void OnSavePage() override;
492   bool SavePage(const base::FilePath& main_file,
493                 const base::FilePath& dir_path,
494                 SavePageType save_type) override;
495   void SaveFrame(const GURL& url,
496                  const Referrer& referrer,
497                  RenderFrameHost* rfh) override;
498   void SaveFrameWithHeaders(const GURL& url,
499                             const Referrer& referrer,
500                             const std::string& headers,
501                             const std::u16string& suggested_filename,
502                             RenderFrameHost* rfh) override;
503   void GenerateMHTML(const MHTMLGenerationParams& params,
504                      base::OnceCallback<void(int64_t)> callback) override;
505   void GenerateMHTMLWithResult(
506       const MHTMLGenerationParams& params,
507       MHTMLGenerationResult::GenerateMHTMLCallback callback) override;
508   void GenerateWebBundle(
509       const base::FilePath& file_path,
510       base::OnceCallback<void(uint64_t, data_decoder::mojom::WebBundlerError)>
511           callback) override;
512   const std::string& GetContentsMimeType() override;
513   blink::RendererPreferences* GetMutableRendererPrefs() override;
514   void Close() override;
515   void SetClosedByUserGesture(bool value) override;
516   bool GetClosedByUserGesture() override;
517   int GetMinimumZoomPercent() override;
518   int GetMaximumZoomPercent() override;
519   void SetPageScale(float page_scale_factor) override;
520   gfx::Size GetPreferredSize() override;
521   bool GotResponseToLockMouseRequest(
522       blink::mojom::PointerLockResult result) override;
523   void GotLockMousePermissionResponse(bool allowed) override;
524   void DropMouseLockForTesting() override;
525   bool GotResponseToKeyboardLockRequest(bool allowed) override;
526   bool HasOpener() override;
527   RenderFrameHostImpl* GetOpener() override;
528   bool HasLiveOriginalOpenerChain() override;
529   WebContents* GetFirstWebContentsInLiveOriginalOpenerChain() override;
530 #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
531   void DidChooseColorInColorChooser(SkColor color) override;
532   void DidEndColorChooser() override;
533 #endif  // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
534   int DownloadImage(const GURL& url,
535                     bool is_favicon,
536                     const gfx::Size& preferred_size,
537                     uint32_t max_bitmap_size,
538                     bool bypass_cache,
539                     ImageDownloadCallback callback) override;
540   int DownloadImageInFrame(
541       const GlobalRenderFrameHostId& initiator_frame_routing_id,
542       const GURL& url,
543       bool is_favicon,
544       const gfx::Size& preferred_size,
545       uint32_t max_bitmap_size,
546       bool bypass_cache,
547       WebContents::ImageDownloadCallback callback) override;
548   void Find(int request_id,
549             const std::u16string& search_text,
550             blink::mojom::FindOptionsPtr options,
551             bool skip_delay = false) override;
552   void StopFinding(StopFindAction action) override;
553   bool WasEverAudible() override;
554   bool IsFullscreen() override;
555   bool ShouldShowStaleContentOnEviction() override;
556   void ExitFullscreen(bool will_cause_resize) override;
557   [[nodiscard]] base::ScopedClosureRunner ForSecurityDropFullscreen(
558       int64_t display_id = display::kInvalidDisplayId) override;
559   void ResumeLoadingCreatedWebContents() override;
560   void SetIsOverlayContent(bool is_overlay_content) override;
561   bool IsFocusedElementEditable() override;
562   void ClearFocusedElement() override;
563   bool IsShowingContextMenu() override;
564   void SetShowingContextMenu(bool showing) override;
565   base::UnguessableToken GetAudioGroupId() override;
566   bool CompletedFirstVisuallyNonEmptyPaint() override;
567   void UpdateFaviconURL(
568       RenderFrameHostImpl* source,
569       const std::vector<blink::mojom::FaviconURLPtr>& candidates) override;
570   const std::vector<blink::mojom::FaviconURLPtr>& GetFaviconURLs() override;
571   void Resize(const gfx::Rect& new_bounds) override;
572   gfx::Size GetSize() override;
573   void UpdateWindowControlsOverlay(const gfx::Rect& bounding_rect) override;
574 #if BUILDFLAG(IS_ANDROID)
575   base::android::ScopedJavaLocalRef<jobject> GetJavaWebContents() override;
576   WebContentsAndroid* GetWebContentsAndroid();
577   void ClearWebContentsAndroid();
578   void ActivateNearestFindResult(float x, float y) override;
579   void RequestFindMatchRects(int current_version) override;
580   service_manager::InterfaceProvider* GetJavaInterfaces() override;
581 #endif
582   bool HasRecentInteractiveInputEvent() override;
583   void SetIgnoreInputEvents(bool ignore_input_events) override;
584   bool HasActiveEffectivelyFullscreenVideo() override;
585   void WriteIntoTrace(perfetto::TracedValue context) override;
586   const base::Location& GetCreatorLocation() override;
587   float GetPictureInPictureInitialAspectRatio() override;
588   bool GetPictureInPictureLockAspectRatio() override;
589   void UpdateBrowserControlsState(cc::BrowserControlsState constraints,
590                                   cc::BrowserControlsState current,
591                                   bool animate) override;
592   void SetTabSwitchStartTime(base::TimeTicks start_time,
593                              bool destination_is_loaded) override;
594
595   // Implementation of PageNavigator.
596   WebContents* OpenURL(const OpenURLParams& params) override;
597
598   const blink::web_pref::WebPreferences& GetOrCreateWebPreferences() override;
599   void NotifyPreferencesChanged() override;
600   void SetWebPreferences(const blink::web_pref::WebPreferences& prefs) override;
601   void OnWebPreferencesChanged() override;
602
603   void DisablePrerender2() override;
604   void ResetPrerender2Disabled() override;
605   // Resets the bit to explicitly disable Prerender2 for this WebContents. Note
606   // that this may not equate to the feature being enabled.
607   bool IsPrerender2Disabled();
608
609   // RenderFrameHostDelegate ---------------------------------------------------
610   bool OnMessageReceived(RenderFrameHostImpl* render_frame_host,
611                          const IPC::Message& message) override;
612   void OnDidBlockNavigation(
613       const GURL& blocked_url,
614       const GURL& initiator_url,
615       blink::mojom::NavigationBlockedReason reason) override;
616   void OnDidFinishLoad(RenderFrameHostImpl* render_frame_host,
617                        const GURL& url) override;
618   void OnManifestUrlChanged(PageImpl& page) override;
619   void RenderFrameCreated(RenderFrameHostImpl* render_frame_host) override;
620   void RenderFrameDeleted(RenderFrameHostImpl* render_frame_host) override;
621   void ShowContextMenu(
622       RenderFrameHost& render_frame_host,
623       mojo::PendingAssociatedRemote<blink::mojom::ContextMenuClient>
624           context_menu_client,
625       const ContextMenuParams& params) override;
626   void RunJavaScriptDialog(RenderFrameHostImpl* render_frame_host,
627                            const std::u16string& message,
628                            const std::u16string& default_prompt,
629                            JavaScriptDialogType dialog_type,
630                            bool disable_third_party_subframe_suppresion,
631                            JavaScriptDialogCallback response_callback) override;
632   void RunBeforeUnloadConfirm(
633       RenderFrameHostImpl* render_frame_host,
634       bool is_reload,
635       JavaScriptDialogCallback response_callback) override;
636   void DidChangeName(RenderFrameHostImpl* render_frame_host,
637                      const std::string& name) override;
638   void DidReceiveUserActivation(
639       RenderFrameHostImpl* render_frame_host) override;
640   void BindDisplayCutoutHost(
641       RenderFrameHostImpl* render_frame_host,
642       mojo::PendingAssociatedReceiver<blink::mojom::DisplayCutoutHost> receiver)
643       override;
644   void DidChangeDisplayState(RenderFrameHostImpl* render_frame_host,
645                              bool is_display_none) override;
646   void FrameSizeChanged(RenderFrameHostImpl* render_frame_host,
647                         const gfx::Size& frame_size) override;
648   void DOMContentLoaded(RenderFrameHostImpl* render_frame_host) override;
649   void DocumentOnLoadCompleted(RenderFrameHostImpl* render_frame_host) override;
650   void UpdateTitle(RenderFrameHostImpl* render_frame_host,
651                    const std::u16string& title,
652                    base::i18n::TextDirection title_direction) override;
653   void UpdateTargetURL(RenderFrameHostImpl* render_frame_host,
654                        const GURL& url) override;
655   bool IsNeverComposited() override;
656   void SetCaptureHandleConfig(
657       blink::mojom::CaptureHandleConfigPtr config) override;
658   ui::AXMode GetAccessibilityMode() override;
659   // Broadcasts the mode change to all frames.
660   void SetAccessibilityMode(ui::AXMode mode) override;
661   void AXTreeIDForMainFrameHasChanged() override;
662   void AccessibilityEventReceived(
663       const AXEventNotificationDetails& details) override;
664   void AccessibilityLocationChangesReceived(
665       const std::vector<AXLocationChangeNotificationDetails>& details) override;
666   std::string DumpAccessibilityTree(
667       bool internal,
668       std::vector<ui::AXPropertyFilter> property_filters) override;
669   void RecordAccessibilityEvents(
670       bool start_recording,
671       absl::optional<ui::AXEventCallback> callback) override;
672   device::mojom::GeolocationContext* GetGeolocationContext() override;
673   device::mojom::WakeLockContext* GetWakeLockContext() override;
674 #if BUILDFLAG(IS_ANDROID)
675   void GetNFC(RenderFrameHost*,
676               mojo::PendingReceiver<device::mojom::NFC>) override;
677 #endif
678   bool CanEnterFullscreenMode(
679       RenderFrameHostImpl* requesting_frame,
680       const blink::mojom::FullscreenOptions& options) override;
681   void EnterFullscreenMode(
682       RenderFrameHostImpl* requesting_frame,
683       const blink::mojom::FullscreenOptions& options) override;
684   void ExitFullscreenMode(bool will_cause_resize) override;
685   void FullscreenStateChanged(
686       RenderFrameHostImpl* rfh,
687       bool is_fullscreen,
688       blink::mojom::FullscreenOptionsPtr options) override;
689 #if BUILDFLAG(IS_ANDROID)
690   void UpdateUserGestureCarryoverInfo() override;
691 #endif
692   bool ShouldRouteMessageEvent(RenderFrameHostImpl* target_rfh) const override;
693   void EnsureOpenerProxiesExist(RenderFrameHostImpl* source_rfh) override;
694   std::unique_ptr<WebUIImpl> CreateWebUIForRenderFrameHost(
695       RenderFrameHostImpl* frame_host,
696       const GURL& url) override;
697   void SetFocusedFrame(FrameTreeNode* node, SiteInstanceGroup* source) override;
698   void DidCallFocus() override;
699   void OnFocusedElementChangedInFrame(
700       RenderFrameHostImpl* frame,
701       const gfx::Rect& bounds_in_root_view,
702       blink::mojom::FocusType focus_type) override;
703   void OnAdvanceFocus(RenderFrameHostImpl* source_rfh) override;
704   FrameTree* CreateNewWindow(
705       RenderFrameHostImpl* opener,
706       const mojom::CreateNewWindowParams& params,
707       bool is_new_browsing_instance,
708       bool has_user_gesture,
709       SessionStorageNamespace* session_storage_namespace) override;
710   void ShowCreatedWindow(RenderFrameHostImpl* opener,
711                          int main_frame_widget_route_id,
712                          WindowOpenDisposition disposition,
713                          const blink::mojom::WindowFeatures& window_features,
714                          bool user_gesture) override;
715   void PrimaryMainDocumentElementAvailable() override;
716   void PassiveInsecureContentFound(const GURL& resource_url) override;
717   bool ShouldAllowRunningInsecureContent(bool allowed_per_prefs,
718                                          const url::Origin& origin,
719                                          const GURL& resource_url) override;
720   void ViewSource(RenderFrameHostImpl* frame) override;
721   void PrintCrossProcessSubframe(
722       const gfx::Rect& rect,
723       int document_cookie,
724       RenderFrameHostImpl* render_frame_host) override;
725   void CapturePaintPreviewOfCrossProcessSubframe(
726       const gfx::Rect& rect,
727       const base::UnguessableToken& guid,
728       RenderFrameHostImpl* render_frame_host) override;
729 #if BUILDFLAG(IS_ANDROID)
730   base::android::ScopedJavaLocalRef<jobject> GetJavaRenderFrameHostDelegate()
731       override;
732 #endif
733   void ResourceLoadComplete(
734       RenderFrameHostImpl* render_frame_host,
735       const GlobalRequestID& request_id,
736       blink::mojom::ResourceLoadInfoPtr resource_load_information) override;
737   void OnCookiesAccessed(RenderFrameHostImpl*,
738                          const CookieAccessDetails& details) override;
739
740   // Called when WebAudio starts or stops playing audible audio in an
741   // AudioContext.
742   void AudioContextPlaybackStarted(RenderFrameHostImpl* host,
743                                    int context_id) override;
744   void AudioContextPlaybackStopped(RenderFrameHostImpl* host,
745                                    int context_id) override;
746   void OnFrameAudioStateChanged(RenderFrameHostImpl* host,
747                                 bool is_audible) override;
748   media::MediaMetricsProvider::RecordAggregateWatchTimeCallback
749   GetRecordAggregateWatchTimeCallback(
750       const GURL& page_main_frame_last_committed_url) override;
751   std::vector<FrameTreeNode*> GetUnattachedOwnedNodes(
752       RenderFrameHostImpl* owner) override;
753   void RegisterProtocolHandler(RenderFrameHostImpl* source,
754                                const std::string& protocol,
755                                const GURL& url,
756                                bool user_gesture) override;
757   void UnregisterProtocolHandler(RenderFrameHostImpl* source,
758                                  const std::string& protocol,
759                                  const GURL& url,
760                                  bool user_gesture) override;
761   bool IsAllowedToGoToEntryAtOffset(int32_t offset) override;
762   void IsClipboardPasteContentAllowed(
763       const GURL& url,
764       const ui::ClipboardFormatType& data_type,
765       const std::string& data,
766       IsClipboardPasteContentAllowedCallback callback) override;
767   void IsClipboardPasteContentAllowedWrapperCallback(
768       IsClipboardPasteContentAllowedCallback callback,
769       ClipboardPasteContentAllowed allowed);
770   void OnPageScaleFactorChanged(PageImpl& source) override;
771   void BindScreenOrientation(
772       RenderFrameHost* rfh,
773       mojo::PendingAssociatedReceiver<device::mojom::ScreenOrientation>
774           receiver) override;
775   bool HasSeenRecentScreenOrientationChange() override;
776   bool IsTransientAllowFullscreenActive() const override;
777   bool IsBackForwardCacheSupported() override;
778   RenderWidgetHostImpl* CreateNewPopupWidget(
779       base::SafeRef<SiteInstanceGroup> site_instance_group,
780       int32_t route_id,
781       mojo::PendingAssociatedReceiver<blink::mojom::PopupWidgetHost>
782           blink_popup_widget_host,
783       mojo::PendingAssociatedReceiver<blink::mojom::WidgetHost>
784           blink_widget_host,
785       mojo::PendingAssociatedRemote<blink::mojom::Widget> blink_widget)
786       override;
787   bool ShowPopupMenu(
788       RenderFrameHostImpl* render_frame_host,
789       mojo::PendingRemote<blink::mojom::PopupMenuClient>* popup_client,
790       const gfx::Rect& bounds,
791       int32_t item_height,
792       double font_size,
793       int32_t selected_item,
794       std::vector<blink::mojom::MenuItemPtr>* menu_items,
795       bool right_aligned,
796       bool allow_multiple_selection) override;
797   void DidLoadResourceFromMemoryCache(
798       RenderFrameHostImpl* source,
799       const GURL& url,
800       const std::string& http_request,
801       const std::string& mime_type,
802       network::mojom::RequestDestination request_destination,
803       bool include_credentials) override;
804   void DomOperationResponse(RenderFrameHost* render_frame_host,
805                             const std::string& json_string) override;
806   void SavableResourceLinksResponse(
807       RenderFrameHostImpl* source,
808       const std::vector<GURL>& resources_list,
809       blink::mojom::ReferrerPtr referrer,
810       const std::vector<blink::mojom::SavableSubframePtr>& subframes) override;
811   void SavableResourceLinksError(RenderFrameHostImpl* source) override;
812   void RenderFrameHostStateChanged(
813       RenderFrameHost* render_frame_host,
814       RenderFrameHost::LifecycleState old_state,
815       RenderFrameHost::LifecycleState new_state) override;
816   void SetWindowRect(const gfx::Rect& new_bounds) override;
817   void UpdateWindowPreferredSize(const gfx::Size& pref_size) override;
818   std::vector<RenderFrameHostImpl*>
819   GetActiveTopLevelDocumentsInBrowsingContextGroup(
820       RenderFrameHostImpl* render_frame_host) override;
821   PrerenderHostRegistry* GetPrerenderHostRegistry() override;
822 #if BUILDFLAG(ENABLE_PPAPI)
823   void OnPepperInstanceCreated(RenderFrameHostImpl* source,
824                                int32_t pp_instance) override;
825   void OnPepperInstanceDeleted(RenderFrameHostImpl* source,
826                                int32_t pp_instance) override;
827   void OnPepperStartsPlayback(RenderFrameHostImpl* source,
828                               int32_t pp_instance) override;
829   void OnPepperStopsPlayback(RenderFrameHostImpl* source,
830                              int32_t pp_instance) override;
831   void OnPepperPluginCrashed(RenderFrameHostImpl* source,
832                              const base::FilePath& plugin_path,
833                              base::ProcessId plugin_pid) override;
834   void OnPepperPluginHung(RenderFrameHostImpl* source,
835                           int plugin_child_id,
836                           const base::FilePath& path,
837                           bool is_hung) override;
838 #endif  // BUILDFLAG(ENABLE_PPAPI)
839   void DidChangeLoadProgressForPrimaryMainFrame() override;
840
841   // RenderViewHostDelegate ----------------------------------------------------
842   RenderViewHostDelegateView* GetDelegateView() override;
843   void RenderViewReady(RenderViewHost* render_view_host) override;
844   void RenderViewTerminated(RenderViewHost* render_view_host,
845                             base::TerminationStatus status,
846                             int error_code) override;
847   void RenderViewDeleted(RenderViewHost* render_view_host) override;
848   void Close(RenderViewHost* render_view_host) override;
849   bool DidAddMessageToConsole(
850       RenderFrameHostImpl* source_frame,
851       blink::mojom::ConsoleMessageLevel log_level,
852       const std::u16string& message,
853       int32_t line_no,
854       const std::u16string& source_id,
855       const absl::optional<std::u16string>& untrusted_stack_trace) override;
856   const blink::RendererPreferences& GetRendererPrefs() const override;
857   void DidReceiveInputEvent(RenderWidgetHostImpl* render_widget_host,
858                             const blink::WebInputEvent& event) override;
859   bool ShouldIgnoreInputEvents() override;
860   void OnIgnoredUIEvent() override;
861   void Activate() override;
862   void ShowCreatedWidget(int process_id,
863                          int widget_route_id,
864                          const gfx::Rect& initial_rect,
865                          const gfx::Rect& initial_anchor_rect) override;
866   void CreateMediaPlayerHostForRenderFrameHost(
867       RenderFrameHostImpl* frame_host,
868       mojo::PendingAssociatedReceiver<media::mojom::MediaPlayerHost> receiver)
869       override;
870   void RequestMediaAccessPermission(const MediaStreamRequest& request,
871                                     MediaResponseCallback callback) override;
872   bool CheckMediaAccessPermission(RenderFrameHostImpl* render_frame_host,
873                                   const url::Origin& security_origin,
874                                   blink::mojom::MediaStreamType type) override;
875   std::string GetDefaultMediaDeviceID(
876       blink::mojom::MediaStreamType type) override;
877   bool IsJavaScriptDialogShowing() const override;
878   bool ShouldIgnoreUnresponsiveRenderer() override;
879   bool IsGuest() override;
880   void RecomputeWebPreferencesSlow() override;
881   absl::optional<SkColor> GetBaseBackgroundColor() override;
882   std::unique_ptr<PrerenderHandle> StartPrerendering(
883       const GURL& prerendering_url,
884       PrerenderTriggerType trigger_type,
885       const std::string& embedder_histogram_suffix,
886       ui::PageTransition page_transition,
887       PreloadingAttempt* preloading_attempt,
888       absl::optional<base::RepeatingCallback<bool(const GURL&)>>
889           url_match_predicate = absl::nullopt) override;
890
891   // NavigatorDelegate ---------------------------------------------------------
892
893   void DidStartNavigation(NavigationHandle* navigation_handle) override;
894   void DidRedirectNavigation(NavigationHandle* navigation_handle) override;
895   void ReadyToCommitNavigation(NavigationHandle* navigation_handle) override;
896   void DidFinishNavigation(NavigationHandle* navigation_handle) override;
897   void DidFailLoadWithError(RenderFrameHostImpl* render_frame_host,
898                             const GURL& url,
899                             int error_code) override;
900   void DidNavigateMainFramePreCommit(FrameTreeNode* frame_tree_node,
901                                      bool navigation_is_within_page) override;
902   void DidNavigateMainFramePostCommit(
903       RenderFrameHostImpl* render_frame_host,
904       const LoadCommittedDetails& details) override;
905   void DidNavigateAnyFramePostCommit(
906       RenderFrameHostImpl* render_frame_host,
907       const LoadCommittedDetails& details) override;
908   void NotifyChangedNavigationState(InvalidateTypes changed_flags) override;
909   bool ShouldAllowRendererInitiatedCrossProcessNavigation(
910       bool is_outermost_main_frame_navigation) override;
911   std::vector<std::unique_ptr<NavigationThrottle>> CreateThrottlesForNavigation(
912       NavigationHandle* navigation_handle) override;
913   std::vector<std::unique_ptr<CommitDeferringCondition>>
914   CreateDeferringConditionsForNavigationCommit(
915       NavigationHandle& navigation_handle,
916       CommitDeferringCondition::NavigationType type) override;
917   std::unique_ptr<NavigationUIData> GetNavigationUIData(
918       NavigationHandle* navigation_handle) override;
919   void OnServiceWorkerAccessed(NavigationHandle* navigation,
920                                const GURL& scope,
921                                AllowServiceWorkerResult allowed) override;
922   void OnCookiesAccessed(NavigationHandle*,
923                          const CookieAccessDetails& details) override;
924   void RegisterExistingOriginAsHavingDefaultIsolation(
925       const url::Origin& origin,
926       NavigationRequest* navigation_request_to_exclude) override;
927
928   // RenderWidgetHostDelegate --------------------------------------------------
929
930   void SetTopControlsShownRatio(RenderWidgetHostImpl* render_widget_host,
931                                 float ratio) override;
932   void SetTopControlsGestureScrollInProgress(bool in_progress) override;
933   void RenderWidgetCreated(RenderWidgetHostImpl* render_widget_host) override;
934   void RenderWidgetDeleted(RenderWidgetHostImpl* render_widget_host) override;
935   void RenderWidgetWasResized(RenderWidgetHostImpl* render_widget_host,
936                               bool width_changed) override;
937   void ResizeDueToAutoResize(RenderWidgetHostImpl* render_widget_host,
938                              const gfx::Size& new_size) override;
939   void OnVerticalScrollDirectionChanged(
940       viz::VerticalScrollDirection scroll_direction) override;
941
942   double GetPendingPageZoomLevel() override;
943
944   KeyboardEventProcessingResult PreHandleKeyboardEvent(
945       const NativeWebKeyboardEvent& event) override;
946   bool HandleMouseEvent(const blink::WebMouseEvent& event) override;
947   bool HandleKeyboardEvent(const NativeWebKeyboardEvent& event) override;
948   bool HandleWheelEvent(const blink::WebMouseWheelEvent& event) override;
949   bool PreHandleGestureEvent(const blink::WebGestureEvent& event) override;
950   BrowserAccessibilityManager* GetRootBrowserAccessibilityManager() override;
951   BrowserAccessibilityManager* GetOrCreateRootBrowserAccessibilityManager()
952       override;
953   // The following 4 functions are already listed under WebContents overrides:
954   // void Cut() override;
955   // void Copy() override;
956   // void Paste() override;
957   // void SelectAll() override;
958   void ExecuteEditCommand(const std::string& command,
959                           const absl::optional<std::u16string>& value) override;
960   void MoveRangeSelectionExtent(const gfx::Point& extent) override;
961   void SelectRange(const gfx::Point& base, const gfx::Point& extent) override;
962   void MoveCaret(const gfx::Point& extent) override;
963   void AdjustSelectionByCharacterOffset(int start_adjust,
964                                         int end_adjust,
965                                         bool show_selection_menu) override;
966   RenderWidgetHostInputEventRouter* GetInputEventRouter() override;
967   RenderWidgetHostImpl* GetFocusedRenderWidgetHost(
968       RenderWidgetHostImpl* receiving_widget) override;
969   RenderWidgetHostImpl* GetRenderWidgetHostWithPageFocus() override;
970   void FocusOwningWebContents(
971       RenderWidgetHostImpl* render_widget_host) override;
972   void RendererUnresponsive(
973       RenderWidgetHostImpl* render_widget_host,
974       base::RepeatingClosure hang_monitor_restarter) override;
975   void RendererResponsive(RenderWidgetHostImpl* render_widget_host) override;
976   void RequestToLockMouse(RenderWidgetHostImpl* render_widget_host,
977                           bool user_gesture,
978                           bool last_unlocked_by_target,
979                           bool privileged) override;
980   bool RequestKeyboardLock(RenderWidgetHostImpl* render_widget_host,
981                            bool esc_key_locked) override;
982   void CancelKeyboardLock(RenderWidgetHostImpl* render_widget_host) override;
983   RenderWidgetHostImpl* GetKeyboardLockWidget() override;
984   // The following function is already listed under WebContents overrides:
985   // bool IsFullscreen() const override;
986   blink::mojom::DisplayMode GetDisplayMode() const override;
987   void LostMouseLock(RenderWidgetHostImpl* render_widget_host) override;
988   bool HasMouseLock(RenderWidgetHostImpl* render_widget_host) override;
989   RenderWidgetHostImpl* GetMouseLockWidget() override;
990   bool OnRenderFrameProxyVisibilityChanged(
991       RenderFrameProxyHost* render_frame_proxy_host,
992       blink::mojom::FrameVisibility visibility) override;
993   void SendScreenRects() override;
994   void SendActiveState(bool active) override;
995   TextInputManager* GetTextInputManager() override;
996   bool IsWidgetForPrimaryMainFrame(
997       RenderWidgetHostImpl* render_widget_host) override;
998   bool IsShowingContextMenuOnPage() const override;
999   void DidChangeScreenOrientation() override;
1000   gfx::Rect GetWindowsControlsOverlayRect() const override;
1001   VisibleTimeRequestTrigger* GetVisibleTimeRequestTrigger() final;
1002
1003   // RenderFrameHostManager::Delegate ------------------------------------------
1004
1005   bool CreateRenderViewForRenderManager(
1006       RenderViewHost* render_view_host,
1007       const absl::optional<blink::FrameToken>& opener_frame_token,
1008       RenderFrameProxyHost* proxy_host) override;
1009   void ReattachOuterDelegateIfNeeded() override;
1010   void CreateRenderWidgetHostViewForRenderManager(
1011       RenderViewHost* render_view_host) override;
1012   void BeforeUnloadFiredFromRenderManager(
1013       bool proceed,
1014       const base::TimeTicks& proceed_time,
1015       bool* proceed_to_fire_unload) override;
1016   void CancelModalDialogsForRenderManager() override;
1017   void NotifySwappedFromRenderManager(RenderFrameHostImpl* old_frame,
1018                                       RenderFrameHostImpl* new_frame) override;
1019   void NotifySwappedFromRenderManagerWithoutFallbackContent(
1020       RenderFrameHostImpl* new_frame) override;
1021   void NotifyMainFrameSwappedFromRenderManager(
1022       RenderFrameHostImpl* old_frame,
1023       RenderFrameHostImpl* new_frame) override;
1024   bool FocusLocationBarByDefault() override;
1025   void OnFrameTreeNodeDestroyed(FrameTreeNode* node) override;
1026
1027   // PageDelegate -------------------------------------------------------------
1028
1029   void OnFirstVisuallyNonEmptyPaint(PageImpl& page) override;
1030
1031   // These both check that the color has in fact changed before notifying
1032   // observers.
1033   void OnThemeColorChanged(PageImpl& page) override;
1034   void OnBackgroundColorChanged(PageImpl& page) override;
1035   void DidInferColorScheme(PageImpl& page) override;
1036   void OnVirtualKeyboardModeChanged(PageImpl& page) override;
1037
1038   // blink::mojom::ColorChooserFactory ---------------------------------------
1039   void OnColorChooserFactoryReceiver(
1040       mojo::PendingReceiver<blink::mojom::ColorChooserFactory> receiver);
1041 #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
1042   void OpenColorChooser(
1043       mojo::PendingReceiver<blink::mojom::ColorChooser> chooser,
1044       mojo::PendingRemote<blink::mojom::ColorChooserClient> client,
1045       SkColor color,
1046       std::vector<blink::mojom::ColorSuggestionPtr> suggestions) override;
1047 #endif  // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
1048
1049   // FrameTree::Delegate -------------------------------------------------------
1050
1051   void DidStartLoading(FrameTreeNode* frame_tree_node,
1052                        bool should_show_loading_ui) override;
1053   void DidStopLoading() override;
1054   bool IsHidden() override;
1055   void NotifyPageChanged(PageImpl& page) override;
1056   int GetOuterDelegateFrameTreeNodeId() override;
1057   FrameTree* LoadingTree() override;
1058
1059   // NavigationControllerDelegate ----------------------------------------------
1060
1061   WebContents* DeprecatedGetWebContents() override;
1062   void NotifyNavigationEntryCommitted(
1063       const LoadCommittedDetails& load_details) override;
1064   void NotifyNavigationEntryChanged(
1065       const EntryChangedDetails& change_details) override;
1066   void NotifyNavigationListPruned(const PrunedDetails& pruned_details) override;
1067   void NotifyNavigationEntriesDeleted() override;
1068   bool ShouldPreserveAbortedURLs() override;
1069
1070   // Invoked before a form repost warning is shown.
1071   void NotifyBeforeFormRepostWarningShow() override;
1072
1073   // Activate this WebContents and show a form repost warning.
1074   void ActivateAndShowRepostFormWarningDialog() override;
1075
1076   void MediaMutedStatusChanged(const MediaPlayerId& id, bool muted);
1077
1078   void UpdateOverridingUserAgent() override;
1079
1080   // Forces overscroll to be disabled (used by touch emulation).
1081   void SetForceDisableOverscrollContent(bool force_disable);
1082
1083   // Override the render view/widget size of the main frame, return whether the
1084   // size changed.
1085   bool SetDeviceEmulationSize(const gfx::Size& new_size);
1086   void ClearDeviceEmulationSize();
1087
1088   AudioStreamMonitor* audio_stream_monitor() { return &audio_stream_monitor_; }
1089
1090   ForwardingAudioStreamFactory* GetAudioStreamFactory();
1091
1092   // Called by MediaWebContentsObserver when playback starts or stops.  See the
1093   // WebContentsObserver function stubs for more details.
1094   void MediaStartedPlaying(
1095       const WebContentsObserver::MediaPlayerInfo& media_info,
1096       const MediaPlayerId& id);
1097   void MediaStoppedPlaying(
1098       const WebContentsObserver::MediaPlayerInfo& media_info,
1099       const MediaPlayerId& id,
1100       WebContentsObserver::MediaStoppedReason reason);
1101   // This will be called before playback is started, check
1102   // GetCurrentlyPlayingVideoCount if you need this when playback starts.
1103   void MediaResized(const gfx::Size& size, const MediaPlayerId& id);
1104   void MediaEffectivelyFullscreenChanged(bool is_fullscreen);
1105
1106   // Called by MediaWebContentsObserver when a buffer underflow occurs. See the
1107   // WebContentsObserver function stubs for more details.
1108   void MediaBufferUnderflow(const MediaPlayerId& id);
1109
1110   // Called by MediaWebContentsObserver when player seek event occurs.
1111   void MediaPlayerSeek(const MediaPlayerId& id);
1112
1113   // Called by MediaWebContentsObserver when a media player is destroyed.
1114   void MediaDestroyed(const MediaPlayerId& id);
1115
1116   int GetCurrentlyPlayingVideoCount() override;
1117   absl::optional<gfx::Size> GetFullscreenVideoSize() override;
1118
1119   MediaWebContentsObserver* media_web_contents_observer() {
1120     return media_web_contents_observer_.get();
1121   }
1122
1123   // Update the web contents visibility.
1124   void UpdateWebContentsVisibility(Visibility visibility);
1125
1126   // Returns the PageVisibilityState for the primary page of this web contents,
1127   // taking the capturing state into account.
1128   PageVisibilityState GetPageVisibilityState() const;
1129
1130   // Called by FindRequestManager when find replies come in from a renderer
1131   // process.
1132   void NotifyFindReply(int request_id,
1133                        int number_of_matches,
1134                        const gfx::Rect& selection_rect,
1135                        int active_match_ordinal,
1136                        bool final_update);
1137
1138   // Modify the counter of connected devices for this WebContents.
1139   void IncrementBluetoothConnectedDeviceCount();
1140   void DecrementBluetoothConnectedDeviceCount();
1141
1142   // Notifies the delegate and observers when the connected to Bluetooth device
1143   // state changes.
1144   void OnIsConnectedToBluetoothDeviceChanged(
1145       bool is_connected_to_bluetooth_device);
1146
1147   void IncrementBluetoothScanningSessionsCount();
1148   void DecrementBluetoothScanningSessionsCount();
1149
1150   // Modify the counter of frames in this WebContents actively using serial
1151   // ports.
1152   void IncrementSerialActiveFrameCount();
1153   void DecrementSerialActiveFrameCount();
1154
1155   // Modify the counter of frames in this WebContents actively using HID
1156   // devices.
1157   void IncrementHidActiveFrameCount();
1158   void DecrementHidActiveFrameCount();
1159
1160   // Notifies the delegate and observers when the connected to USB device state
1161   // changes.
1162   void OnIsConnectedToUsbDeviceChanged(bool is_connected_to_usb_device);
1163
1164   // Modify the counter of frames in this WebContents actively using USB
1165   // devices.
1166   void IncrementUsbActiveFrameCount();
1167   void DecrementUsbActiveFrameCount();
1168
1169   // Modify the counter of File System Access handles for this WebContents.
1170   void IncrementFileSystemAccessHandleCount();
1171   void DecrementFileSystemAccessHandleCount();
1172
1173   // Called when the WebContents gains or loses a persistent video.
1174   void SetHasPersistentVideo(bool has_persistent_video);
1175
1176   // Whether the WebContents effectively fullscreen active player allows
1177   // Picture-in-Picture.
1178   // |IsFullscreen| must return |true| when this method is called.
1179   bool IsPictureInPictureAllowedForFullscreenVideo() const;
1180
1181   // Set this WebContents's `primary_frame_tree_` as the focused frame tree.
1182   // `primary_frame_tree_`'s main frame RenderWidget (and all of its
1183   // subframe widgets) will be activated. GetFocusedRenderWidgetHost will search
1184   // this WebContentsImpl for a focused RenderWidgetHost. The previously focused
1185   // WebContentsImpl, if any, will have its RenderWidgetHosts deactivated.
1186   void SetAsFocusedWebContentsIfNecessary();
1187
1188   // Sets the focused frame tree to be the `frame_tree_to_focus`.
1189   // `frame_tree_to_focus` must be either this WebContents's frame tree or
1190   // contained within it (but not owned by another WebContents).
1191   void SetFocusedFrameTree(FrameTree* frame_tree_to_focus);
1192
1193   // Notifies the Picture-in-Picture controller that there is a new video player
1194   // entering video Picture-in-Picture. (This is not used for document
1195   // Picture-in-Picture,
1196   // cf. PictureInPictureWindowManager::EnterDocumentPictureInPicture().)
1197   // Returns the result of the enter request.
1198   PictureInPictureResult EnterPictureInPicture();
1199
1200   // Updates the Picture-in-Picture controller with a signal that
1201   // Picture-in-Picture mode has ended.
1202   void ExitPictureInPicture();
1203
1204   // Updates the tracking information for |this| to know if there is
1205   // a video currently in Picture-in-Picture mode.
1206   void SetHasPictureInPictureVideo(bool has_picture_in_picture_video);
1207
1208   // Updates the tracking information for |this| to know if there is
1209   // a document currently in Picture-in-Picture mode.
1210   void SetHasPictureInPictureDocument(bool has_picture_in_picture_document);
1211
1212   // Sets the spatial navigation state.
1213   void SetSpatialNavigationDisabled(bool disabled);
1214
1215   // Sets the Stylus handwriting feature status. This status is updated to web
1216   // preferences.
1217   void SetStylusHandwritingEnabled(bool enabled);
1218
1219   // Called when a file selection is to be done.
1220   void RunFileChooser(
1221       RenderFrameHost* render_frame_host,
1222       scoped_refptr<FileChooserImpl::FileSelectListenerImpl> listener,
1223       const blink::mojom::FileChooserParams& params);
1224
1225   // Request to enumerate a directory.  This is equivalent to running the file
1226   // chooser in directory-enumeration mode and having the user select the given
1227   // directory.
1228   void EnumerateDirectory(
1229       RenderFrameHost* render_frame_host,
1230       scoped_refptr<FileChooserImpl::FileSelectListenerImpl> listener,
1231       const base::FilePath& directory_path);
1232
1233 #if BUILDFLAG(IS_ANDROID)
1234   // Called by FindRequestManager when all of the find match rects are in.
1235   void NotifyFindMatchRectsReply(int version,
1236                                  const std::vector<gfx::RectF>& rects,
1237                                  const gfx::RectF& active_rect);
1238 #endif
1239
1240 #if BUILDFLAG(IS_ANDROID)
1241   // Called by WebContentsAndroid to send the Display Cutout safe area to
1242   // DisplayCutoutHostImpl.
1243   void SetDisplayCutoutSafeArea(gfx::Insets insets);
1244 #endif
1245
1246   // Notify observers that the viewport fit value changed. This is called by
1247   // |DisplayCutoutHostImpl|.
1248   void NotifyViewportFitChanged(blink::mojom::ViewportFit value);
1249
1250   // Returns the current FindRequestManager associated with the WebContents;
1251   // this won't create one if none exists.
1252   FindRequestManager* GetFindRequestManagerForTesting();
1253
1254   // Convenience method to notify observers that an inner WebContents was
1255   // created with |this| WebContents as its owner. This does *not* immediately
1256   // guarantee that |inner_web_contents| has been added to the WebContents tree.
1257   void InnerWebContentsCreated(WebContents* inner_web_contents);
1258
1259   // Detaches this WebContents from its outer WebContents.
1260   std::unique_ptr<WebContents> DetachFromOuterWebContents();
1261
1262   // Reattaches this inner WebContents to its outer WebContents.
1263   virtual void ReattachToOuterWebContentsFrame();
1264
1265   // Getter/setter for the Portal associated with this WebContents. If non-null
1266   // then this WebContents is embedded in a portal and its outer WebContents can
1267   // be found by using GetOuterWebContents().
1268   void set_portal(Portal* portal) { portal_ = portal; }
1269   Portal* portal() const { return portal_; }
1270
1271   // Sends a page message to notify every process in the frame tree if the
1272   // web contents is a portal web contents.
1273   void NotifyInsidePortal(bool inside_portal);
1274
1275   // Notifies observers that this WebContents was activated. This contents'
1276   // former portal host, |predecessor_web_contents|, has become a portal pending
1277   // adoption.
1278   // |activation_time| is the time the activation happened, in wall time.
1279   void DidActivatePortal(WebContentsImpl* predecessor_web_contents,
1280                          base::TimeTicks activation_time);
1281
1282   void OnServiceWorkerAccessed(RenderFrameHost* render_frame_host,
1283                                const GURL& scope,
1284                                AllowServiceWorkerResult allowed);
1285
1286   bool JavaScriptDialogDefersNavigations() {
1287     return javascript_dialog_dismiss_notifier_.get();
1288   }
1289
1290   void NotifyOnJavaScriptDialogDismiss(base::OnceClosure callback);
1291
1292   bool has_persistent_video() { return has_persistent_video_; }
1293
1294   // Returns the focused frame's input handler.
1295   blink::mojom::FrameWidgetInputHandler* GetFocusedFrameWidgetInputHandler();
1296
1297   // A render view-originated drag has ended. Informs the render view host and
1298   // WebContentsDelegate.
1299   void SystemDragEnded(RenderWidgetHost* source_rwh);
1300
1301   // These are the content internal equivalents of
1302   // |WebContents::ForEachRenderFrameHost| whose comment can be referred to
1303   // for details. Content internals can also access speculative
1304   // RenderFrameHostImpls if necessary by using the
1305   // |ForEachRenderFrameHostIncludingSpeculative| variations.
1306   void ForEachRenderFrameHostWithAction(
1307       base::FunctionRef<FrameIterationAction(RenderFrameHostImpl*)> on_frame);
1308   void ForEachRenderFrameHost(
1309       base::FunctionRef<void(RenderFrameHostImpl*)> on_frame);
1310   void ForEachRenderFrameHostIncludingSpeculativeWithAction(
1311       base::FunctionRef<FrameIterationAction(RenderFrameHostImpl*)> on_frame);
1312   void ForEachRenderFrameHostIncludingSpeculative(
1313       base::FunctionRef<void(RenderFrameHostImpl*)> on_frame);
1314
1315   // Computes and returns the content specific preferences for this WebContents.
1316   // Recomputes only the "fast" preferences (those not requiring slow
1317   // platform/device polling); the remaining "slow" ones are recomputed only if
1318   // the preference cache is empty.
1319   const blink::web_pref::WebPreferences ComputeWebPreferences();
1320
1321   // Certain WebXr modes integrate with Viz as a compositor directly, and thus
1322   // have their own FrameSinkId that typically renders fullscreen, obscuring
1323   // the WebContents. This allows those WebXr modes to notify us if that
1324   // is occurring. When it has finished, this method may be called again with an
1325   // Invalid FrameSinkId to indicate such. Note that other fullscreen modes,
1326   // e.g. Fullscreen videos, are largely controlled by the renderer process and
1327   // as such are still parented under the existing FrameSinkId.
1328   void OnXrHasRenderTarget(const viz::FrameSinkId& frame_sink_id);
1329
1330   // Because something else may be rendering as the primary contents of this
1331   // WebContents rather than the RenderHostView, targets that wish to capture
1332   // the contents of this WebContents should query for the FrameSinkId of the
1333   // base compositor here.
1334   viz::FrameSinkId GetCaptureFrameSinkId();
1335
1336   void set_show_popup_menu_callback_for_testing(
1337       base::OnceCallback<void(const gfx::Rect&)> callback) {
1338     show_poup_menu_callback_ = std::move(callback);
1339   }
1340
1341   // Sets the value in tests to ensure expected ordering and correctness.
1342   void set_minimum_delay_between_loading_updates_for_testing(
1343       base::TimeDelta duration) {
1344     minimum_delay_between_loading_updates_ms_ = duration;
1345   }
1346
1347   // If the given frame is prerendered, cancels the associated prerender.
1348   // Returns true if a prerender was canceled.
1349   bool CancelPrerendering(FrameTreeNode* frame_tree_node,
1350                           PrerenderHost::FinalStatus final_status);
1351
1352   void set_suppress_ime_events_for_testing(bool suppress) {
1353     suppress_ime_events_for_testing_ = suppress;
1354   }
1355
1356   RenderWidgetHost* mouse_lock_widget_for_testing() {
1357     return mouse_lock_widget_;
1358   }
1359
1360   // Record a prerender activation for DevTools.
1361   void set_last_navigation_was_prerender_activation_for_devtools() {
1362     last_navigation_was_prerender_activation_for_devtools_ = true;
1363   }
1364
1365   // Check if prerender was just activated.
1366   bool last_navigation_was_prerender_activation_for_devtools() {
1367     return last_navigation_was_prerender_activation_for_devtools_;
1368   }
1369
1370   ui::mojom::VirtualKeyboardMode GetVirtualKeyboardMode() const;
1371
1372  private:
1373   using FrameTreeIterationCallback = base::RepeatingCallback<void(FrameTree*)>;
1374   using RenderViewHostIterationCallback =
1375       base::RepeatingCallback<void(RenderViewHostImpl*)>;
1376
1377   friend class WebContentsObserver;
1378   friend class WebContents;  // To implement factory methods.
1379
1380   friend class RenderFrameHostImplBeforeUnloadBrowserTest;
1381   friend class WebContentsImplBrowserTest;
1382   friend class TestWebContentsDestructionObserver;
1383   friend class BeforeUnloadBlockingDelegate;
1384   friend class TestWCDelegateForDialogsAndFullscreen;
1385
1386   FRIEND_TEST_ALL_PREFIXES(WebContentsImplTest, CaptureHoldsWakeLock);
1387   FRIEND_TEST_ALL_PREFIXES(WebContentsImplTest, NoJSMessageOnInterstitials);
1388   FRIEND_TEST_ALL_PREFIXES(WebContentsImplTest, UpdateTitle);
1389   FRIEND_TEST_ALL_PREFIXES(WebContentsImplTest, FindOpenerRVHWhenPending);
1390   FRIEND_TEST_ALL_PREFIXES(WebContentsImplTest,
1391                            CrossSiteCantPreemptAfterUnload);
1392   FRIEND_TEST_ALL_PREFIXES(WebContentsImplTest, PendingContentsDestroyed);
1393   FRIEND_TEST_ALL_PREFIXES(WebContentsImplTest, PendingContentsShown);
1394   FRIEND_TEST_ALL_PREFIXES(WebContentsImplTest, FrameTreeShape);
1395   FRIEND_TEST_ALL_PREFIXES(WebContentsImplTest,
1396                            NonActivityCaptureDoesNotCountAsActivity);
1397   FRIEND_TEST_ALL_PREFIXES(WebContentsImplTest, GetLastActiveTime);
1398   FRIEND_TEST_ALL_PREFIXES(WebContentsImplTest,
1399                            LoadResourceFromMemoryCacheWithBadSecurityInfo);
1400   FRIEND_TEST_ALL_PREFIXES(WebContentsImplTest,
1401                            LoadResourceWithEmptySecurityInfo);
1402   FRIEND_TEST_ALL_PREFIXES(WebContentsImplTest,
1403                            ResetJavaScriptDialogOnUserNavigate);
1404   FRIEND_TEST_ALL_PREFIXES(WebContentsImplTest, ParseDownloadHeaders);
1405   FRIEND_TEST_ALL_PREFIXES(WebContentsImplTest, FaviconURLsSet);
1406   FRIEND_TEST_ALL_PREFIXES(WebContentsImplTest, FaviconURLsResetWithNavigation);
1407   FRIEND_TEST_ALL_PREFIXES(WebContentsImplTest, FaviconURLsUpdateDelay);
1408   FRIEND_TEST_ALL_PREFIXES(WebContentsImplBrowserTest,
1409                            NotifyFullscreenAcquired);
1410   FRIEND_TEST_ALL_PREFIXES(WebContentsImplBrowserTest,
1411                            NotifyFullscreenAcquired_Navigate);
1412   FRIEND_TEST_ALL_PREFIXES(WebContentsImplBrowserTest,
1413                            NotifyFullscreenAcquired_SameOrigin);
1414   FRIEND_TEST_ALL_PREFIXES(WebContentsImplBrowserTest,
1415                            PropagateFullscreenOptions);
1416   FRIEND_TEST_ALL_PREFIXES(WebContentsImplBrowserTest,
1417                            FullscreenAfterFrameUnload);
1418   FRIEND_TEST_ALL_PREFIXES(WebContentsImplBrowserTest,
1419                            MaxFrameCountForCrossProcessNavigation);
1420   FRIEND_TEST_ALL_PREFIXES(WebContentsImplBrowserTest,
1421                            MaxFrameCountRemovedIframes);
1422   FRIEND_TEST_ALL_PREFIXES(WebContentsImplBrowserTest,
1423                            MaxFrameCountInjectedIframes);
1424   FRIEND_TEST_ALL_PREFIXES(WebContentsImplBrowserTest,
1425                            ForEachFrameTreeInnerContents);
1426   FRIEND_TEST_ALL_PREFIXES(FencedFrameMPArchBrowserTest, FrameIteration);
1427   FRIEND_TEST_ALL_PREFIXES(FencedFrameParameterizedBrowserTest,
1428                            ShouldIgnoreJsDialog);
1429   FRIEND_TEST_ALL_PREFIXES(FormStructureBrowserTest, HTMLFiles);
1430   FRIEND_TEST_ALL_PREFIXES(NavigationControllerTest, HistoryNavigate);
1431   FRIEND_TEST_ALL_PREFIXES(RenderFrameHostManagerTest, PageDoesBackAndReload);
1432   FRIEND_TEST_ALL_PREFIXES(SitePerProcessBrowserTest, CrossSiteIframe);
1433   FRIEND_TEST_ALL_PREFIXES(SitePerProcessBrowserTest,
1434                            TwoSubframesCreatePopupsSimultaneously);
1435   FRIEND_TEST_ALL_PREFIXES(SitePerProcessBrowserTest, TextAutosizerPageInfo);
1436   FRIEND_TEST_ALL_PREFIXES(SitePerProcessBrowserTest,
1437                            TwoSubframesCreatePopupMenuWidgetsSimultaneously);
1438   FRIEND_TEST_ALL_PREFIXES(SitePerProcessAccessibilityBrowserTest,
1439                            CrossSiteIframeAccessibility);
1440   FRIEND_TEST_ALL_PREFIXES(RenderFrameHostImplBrowserTest,
1441                            IframeBeforeUnloadParentHang);
1442   FRIEND_TEST_ALL_PREFIXES(RenderFrameHostImplBrowserTest,
1443                            BeforeUnloadDialogRequiresGesture);
1444   FRIEND_TEST_ALL_PREFIXES(RenderFrameHostImplBrowserTest,
1445                            CancelBeforeUnloadResetsURL);
1446   FRIEND_TEST_ALL_PREFIXES(RenderFrameHostImplBrowserTest,
1447                            BeforeUnloadDialogSuppressedForDiscard);
1448   FRIEND_TEST_ALL_PREFIXES(RenderFrameHostImplBrowserTest,
1449                            BeforeUnloadConfirmOnNonActive);
1450   FRIEND_TEST_ALL_PREFIXES(RenderFrameHostImplBrowserTest,
1451                            PendingDialogMakesDiscardUnloadReturnFalse);
1452   FRIEND_TEST_ALL_PREFIXES(DevToolsProtocolTest, JavaScriptDialogNotifications);
1453   FRIEND_TEST_ALL_PREFIXES(DevToolsProtocolTest, JavaScriptDialogInterop);
1454   FRIEND_TEST_ALL_PREFIXES(DevToolsProtocolTest, BeforeUnloadDialog);
1455   FRIEND_TEST_ALL_PREFIXES(DevToolsProtocolTest, PageDisableWithOpenedDialog);
1456   FRIEND_TEST_ALL_PREFIXES(DevToolsProtocolTest,
1457                            PageDisableWithNoDialogManager);
1458   FRIEND_TEST_ALL_PREFIXES(
1459       PrerenderWithRenderDocumentBrowserTest,
1460       ModalDialogShouldNotBeDismissedAfterPrerenderSubframeNavigation);
1461   FRIEND_TEST_ALL_PREFIXES(PrerenderBrowserTest, ForEachRenderFrameHost);
1462   FRIEND_TEST_ALL_PREFIXES(PluginContentOriginAllowlistTest,
1463                            ClearAllowlistOnNavigate);
1464   FRIEND_TEST_ALL_PREFIXES(PluginContentOriginAllowlistTest,
1465                            SubframeInheritsAllowlist);
1466   FRIEND_TEST_ALL_PREFIXES(PointerLockBrowserTest,
1467                            PointerLockInnerContentsCrashes);
1468   FRIEND_TEST_ALL_PREFIXES(PointerLockBrowserTest, PointerLockOopifCrashes);
1469
1470   // So |find_request_manager_| can be accessed for testing.
1471   friend class FindRequestManagerTest;
1472
1473   // TODO(brettw) TestWebContents shouldn't exist!
1474   friend class TestWebContents;
1475
1476 #if defined(USE_EFL)
1477   friend class WebContentsImplEfl;
1478 #endif
1479
1480   class RenderWidgetHostDestructionObserver;
1481   class WebContentsDestructionObserver;
1482
1483   // Represents a WebContents node in a tree of WebContents structure.
1484   //
1485   // Two WebContents with separate FrameTrees can be connected by
1486   // outer/inner relationship using this class. Note that their FrameTrees
1487   // still remain disjoint.
1488   // The parent is referred to as "outer WebContents" and the descendents are
1489   // referred to as "inner WebContents".
1490   // For each inner WebContents, the outer WebContents will have a
1491   // corresponding FrameTreeNode.
1492   class WebContentsTreeNode final : public FrameTreeNode::Observer {
1493    public:
1494     explicit WebContentsTreeNode(WebContentsImpl* current_web_contents);
1495     ~WebContentsTreeNode() final;
1496
1497     // Attaches |inner_web_contents| to the |render_frame_host| within this
1498     // WebContents.
1499     void AttachInnerWebContents(std::unique_ptr<WebContents> inner_web_contents,
1500                                 RenderFrameHostImpl* render_frame_host);
1501
1502     // Disconnects the current WebContents from its outer WebContents, and
1503     // returns ownership to the caller. This is used when activating a portal,
1504     // which causes the WebContents to transition from an inner WebContents to
1505     // an outer WebContents.
1506     // TODO(lfg): Activating a nested portal currently replaces the outermost
1507     // WebContents with the portal. We should allow replacing only the inner
1508     // WebContents with the nested portal.
1509     std::unique_ptr<WebContents> DisconnectFromOuterWebContents();
1510
1511     WebContentsImpl* outer_web_contents() const { return outer_web_contents_; }
1512     int outer_contents_frame_tree_node_id() const {
1513       return outer_contents_frame_tree_node_id_;
1514     }
1515     FrameTreeNode* OuterContentsFrameTreeNode() const;
1516
1517     FrameTree* focused_frame_tree() { return &*focused_frame_tree_; }
1518     void SetFocusedFrameTree(FrameTree* frame_tree);
1519
1520     // Returns the inner WebContents within |frame|, if one exists, or nullptr
1521     // otherwise.
1522     WebContentsImpl* GetInnerWebContentsInFrame(const FrameTreeNode* frame);
1523
1524     std::vector<WebContentsImpl*> GetInnerWebContents() const;
1525
1526    private:
1527     std::unique_ptr<WebContents> DetachInnerWebContents(
1528         WebContentsImpl* inner_web_contents);
1529
1530     // FrameTreeNode::Observer implementation.
1531     void OnFrameTreeNodeDestroyed(FrameTreeNode* node) final;
1532
1533     // The WebContents that owns this WebContentsTreeNode.
1534     const raw_ptr<WebContentsImpl> current_web_contents_;
1535
1536     // The outer WebContents of |current_web_contents_|, or nullptr if
1537     // |current_web_contents_| is the outermost WebContents.
1538     raw_ptr<WebContentsImpl> outer_web_contents_;
1539
1540     // The ID of the FrameTreeNode in the |outer_web_contents_| that hosts
1541     // |current_web_contents_| as an inner WebContents.
1542     int outer_contents_frame_tree_node_id_;
1543
1544     // List of inner WebContents that we host. The outer WebContents owns the
1545     // inner WebContents.
1546     std::vector<std::unique_ptr<WebContents>> inner_web_contents_;
1547
1548     // Only the root node should have this set. This indicates the FrameTree
1549     // that has the focused frame. The FrameTree tree could be arbitrarily deep.
1550     // An inner WebContents if focused is responsible for setting this back to
1551     // another valid during its destruction. See WebContentsImpl destructor.
1552     // TODO(crbug.com/1257595): Support clearing this for inner frame trees.
1553     base::SafeRef<FrameTree> focused_frame_tree_;
1554   };
1555
1556   // Container for WebContentsObservers, which knows when we are iterating over
1557   // observer set.
1558   class WebContentsObserverList {
1559    public:
1560     WebContentsObserverList();
1561     ~WebContentsObserverList();
1562
1563     void AddObserver(WebContentsObserver* observer);
1564     void RemoveObserver(WebContentsObserver* observer);
1565
1566     // T1 must be a pointer to a WebContentsObserver method.
1567     template <typename T1, typename... P1>
1568     void NotifyObservers(T1 func, P1&&... args) {
1569       TRACE_EVENT0("content", "WebContentsObserverList::NotifyObservers");
1570       base::AutoReset<bool> scope(&is_notifying_observers_, true);
1571       for (WebContentsObserver& observer : observers_) {
1572         TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1573                      "Dispatching WebContentsObserver callback");
1574         ((observer).*(func))(std::forward<P1>(args)...);
1575       }
1576     }
1577
1578     bool is_notifying_observers() { return is_notifying_observers_; }
1579
1580     // Exposed to deal with IPC message handlers which need to stop iteration
1581     // early.
1582     const base::ObserverList<WebContentsObserver>::Unchecked& observer_list() {
1583       return observers_;
1584     }
1585
1586    private:
1587     bool is_notifying_observers_ = false;
1588     base::ObserverList<WebContentsObserver>::Unchecked observers_;
1589   };
1590
1591   // See WebContents::Create for a description of these parameters.
1592   explicit WebContentsImpl(BrowserContext* browser_context);
1593
1594   // Covariant return type alternative for WebContents::Create(). Avoids
1595   // need for casting of objects inside the content layer.
1596   static std::unique_ptr<WebContentsImpl> Create(const CreateParams& params);
1597
1598   // Add and remove observers for page navigation notifications. The order in
1599   // which notifications are sent to observers is undefined. Clients must be
1600   // sure to remove the observer before they go away.
1601   void AddObserver(WebContentsObserver* observer);
1602   void RemoveObserver(WebContentsObserver* observer);
1603
1604   // Indicates whether this tab should be considered crashed. The setter will
1605   // also notify the delegate when the flag is changed.
1606   void SetPrimaryMainFrameProcessStatus(base::TerminationStatus status,
1607                                         int error_code);
1608
1609   // Clears a pending contents that has been closed before being shown.
1610   void OnWebContentsDestroyed(WebContentsImpl* web_contents);
1611
1612   // Clears a pending render widget host that has been closed before being
1613   // shown.
1614   void OnRenderWidgetHostDestroyed(RenderWidgetHost* render_widget_host);
1615
1616   // Creates and adds to the map a destruction observer watching `web_contents`.
1617   // No-op if such an observer already exists.
1618   void AddWebContentsDestructionObserver(WebContentsImpl* web_contents);
1619
1620   // Deletes and removes from the map a destruction observer
1621   // watching `web_contents`. No-op if there is no such observer.
1622   void RemoveWebContentsDestructionObserver(WebContentsImpl* web_contents);
1623
1624   // Creates and adds to the map a destruction observer watching
1625   // `render_widget_host`. No-op if such an observer already exists.
1626   void AddRenderWidgetHostDestructionObserver(
1627       RenderWidgetHost* render_widget_host);
1628
1629   // Deletes and removes from the map a destruction observer
1630   // watching `render_widget_host`. No-op if there is no such observer.
1631   void RemoveRenderWidgetHostDestructionObserver(
1632       RenderWidgetHost* render_widget_host);
1633
1634   // Traverses all the WebContents in the WebContentsTree and creates a set of
1635   // all the unique RenderWidgetHostViews.
1636   std::set<RenderWidgetHostViewBase*>
1637   GetRenderWidgetHostViewsInWebContentsTree();
1638
1639   // Called with the result of a DownloadImage() request.
1640   void OnDidDownloadImage(base::WeakPtr<RenderFrameHostImpl> rfh,
1641                           ImageDownloadCallback callback,
1642                           int id,
1643                           const GURL& image_url,
1644                           int32_t http_status_code,
1645                           const std::vector<SkBitmap>& images,
1646                           const std::vector<gfx::Size>& original_image_sizes);
1647
1648   // Callback function when showing JavaScript dialogs. Takes in a routing ID
1649   // pair to identify the RenderFrameHost that opened the dialog, because it's
1650   // possible for the RenderFrameHost to be deleted by the time this is called.
1651   void OnDialogClosed(int render_process_id,
1652                       int render_frame_id,
1653                       JavaScriptDialogCallback response_callback,
1654                       base::ScopedClosureRunner fullscreen_block,
1655                       bool dialog_was_suppressed,
1656                       bool success,
1657                       const std::u16string& user_input);
1658
1659   // IPC message handlers.
1660   void OnUpdateZoomLimits(RenderViewHostImpl* source,
1661                           int minimum_percent,
1662                           int maximum_percent);
1663   void OnShowValidationMessage(RenderViewHostImpl* source,
1664                                const gfx::Rect& anchor_in_root_view,
1665                                const std::u16string& main_text,
1666                                const std::u16string& sub_text);
1667   void OnHideValidationMessage(RenderViewHostImpl* source);
1668   void OnMoveValidationMessage(RenderViewHostImpl* source,
1669                                const gfx::Rect& anchor_in_root_view);
1670
1671   // Determines if content is allowed to overscroll. This value comes from the
1672   // WebContentsDelegate, but can also be overridden by the WebContents.
1673   bool CanOverscrollContent() const;
1674
1675   // Inner WebContents Helpers -------------------------------------------------
1676   //
1677   // These functions are helpers in managing a hierarchy of WebContents
1678   // involved in rendering inner WebContents.
1679
1680   // The following functions update registrations for all RenderWidgetHostViews
1681   // rooted at this WebContents. They are used when attaching/detaching an inner
1682   // WebContents.
1683   //
1684   // Some properties of RenderWidgetHostViews, such as the FrameSinkId and
1685   // TextInputManager, depend on the outermost WebContents, and must be updated
1686   // during attach/detach.
1687   void RecursivelyRegisterRenderWidgetHostViews();
1688   void RecursivelyUnregisterRenderWidgetHostViews();
1689
1690   // When multiple WebContents are present within a tab or window, a single one
1691   // is focused and will route keyboard events in most cases to a RenderWidget
1692   // contained within it. |GetFocusedWebContents()|'s main frame widget will
1693   // receive page focus and blur events when the containing window changes focus
1694   // state.
1695
1696   // Returns true if |this| is the focused WebContents or an ancestor of the
1697   // focused WebContents.
1698   bool ContainsOrIsFocusedWebContents();
1699
1700   // Called just after an inner web contents is attached.
1701   void InnerWebContentsAttached(WebContents* inner_web_contents);
1702
1703   // Called just after an inner web contents is detached.
1704   void InnerWebContentsDetached(WebContents* inner_web_contents);
1705
1706   // Navigation helpers --------------------------------------------------------
1707   //
1708   // These functions are helpers for Navigate() and DidNavigate().
1709
1710   // Handles post-navigation tasks in DidNavigate AFTER the entry has been
1711   // committed to the navigation controller. Note that the navigation entry is
1712   // not provided since it may be invalid/changed after being committed. The
1713   // current navigation entry is in the NavigationController at this point.
1714
1715   // Finds the new RenderWidgetHost and returns it. Note that this can only be
1716   // called once as this call also removes it from the internal map.
1717   RenderWidgetHostView* GetCreatedWidget(int process_id, int route_id);
1718
1719   // Finds the new CreatedWindow by |main_frame_widget_route_id|, initializes
1720   // it for renderer-initiated creation, and returns it. Note that this can only
1721   // be called once as this call also removes it from the internal map.
1722   absl::optional<CreatedWindow> GetCreatedWindow(
1723       int process_id,
1724       int main_frame_widget_route_id);
1725
1726   // Execute a PageBroadcast Mojo method.
1727   void ExecutePageBroadcastMethod(PageBroadcastMethodCallback callback);
1728
1729   // Execute a PageBroadcast Mojo method for all MPArch pages.
1730   void ExecutePageBroadcastMethodForAllPages(
1731       PageBroadcastMethodCallback callback);
1732
1733   void SetOpenerForNewContents(FrameTreeNode* opener, bool opener_suppressed);
1734
1735   // Tracking loading progress -------------------------------------------------
1736
1737   // Resets the tracking state of the current load progress.
1738   void ResetLoadProgressState();
1739
1740   // Notifies the delegate that the load progress was updated.
1741   void SendChangeLoadProgress();
1742
1743   // Notifies the delegate of a change in loading state.
1744   // |details| is used to provide details on the load that just finished
1745   // (but can be null if not applicable).
1746   void LoadingStateChanged(bool should_show_loading_ui,
1747                            LoadNotificationDetails* details);
1748
1749   // Misc non-view stuff -------------------------------------------------------
1750
1751   // Sets the history for a specified RenderViewHost to |history_length|
1752   // entries, with an offset of |history_offset|.
1753   void SetHistoryOffsetAndLengthForView(RenderViewHost* render_view_host,
1754                                         int history_offset,
1755                                         int history_length);
1756
1757   // Helper functions for sending notifications.
1758   void NotifyViewSwapped(RenderViewHost* old_view, RenderViewHost* new_view);
1759   void NotifyFrameSwapped(RenderFrameHostImpl* old_frame,
1760                           RenderFrameHostImpl* new_frame);
1761
1762   // TODO(creis): This should take in a FrameTreeNode to know which node's
1763   // render manager to return.  For now, we just return the root's.
1764   RenderFrameHostManager* GetRenderManager();
1765
1766   // Removes browser plugin embedder if there is one.
1767   void RemoveBrowserPluginEmbedder();
1768
1769   // Returns the size that the main frame should be sized to.
1770   gfx::Size GetSizeForMainFrame();
1771
1772   // Helper method that's called whenever |preferred_size_| or
1773   // |preferred_size_for_capture_| changes, to propagate the new value to the
1774   // |delegate_|.
1775   void OnPreferredSizeChanged(const gfx::Size& old_size);
1776
1777   // Internal helper to create WebUI objects associated with |this|. |url| is
1778   // used to determine which WebUI should be created (if any).
1779   std::unique_ptr<WebUIImpl> CreateWebUI(RenderFrameHostImpl* frame_host,
1780                                          const GURL& url);
1781
1782   void SetJavaScriptDialogManagerForTesting(
1783       JavaScriptDialogManager* dialog_manager);
1784
1785   // Returns the FindRequestManager, which may be found in an outer WebContents.
1786   FindRequestManager* GetFindRequestManager();
1787
1788   // Returns the FindRequestManager, or tries to create one if it doesn't
1789   //  already exist. The FindRequestManager may be found in an outer
1790   // WebContents. If this is an inner WebContents which is not yet attached to
1791   // an outer WebContents the method will return nullptr.
1792   FindRequestManager* GetOrCreateFindRequestManager();
1793
1794   // Prints a console warning when visiting a localhost site with a bad
1795   // certificate via --allow-insecure-localhost.
1796   void ShowInsecureLocalhostWarningIfNeeded(PageImpl& page);
1797
1798   // Format of |headers| is a new line separated list of key value pairs:
1799   // "<key1>: <value1>\r\n<key2>: <value2>".
1800   static download::DownloadUrlParameters::RequestHeadersType
1801   ParseDownloadHeaders(const std::string& headers);
1802
1803   // Sets the visibility of immediate child views, i.e. views whose parent view
1804   // is that of the main frame.
1805   void SetVisibilityForChildViews(bool visible);
1806
1807   // A helper for clearing the link status bubble after navigating away.
1808   // See also UpdateTargetURL.
1809   void ClearTargetURL();
1810
1811   // Called each time |fullscreen_frames_| is updated. Find the new
1812   // |current_fullscreen_frame_| and notify observers whenever it changes.
1813   void FullscreenFrameSetUpdated();
1814
1815   // ui::NativeThemeObserver:
1816   void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override;
1817   void OnCaptionStyleUpdated() override;
1818
1819   // ui::ColorProviderSourceObserver:
1820   void OnColorProviderChanged() override;
1821
1822   // Returns the ColorProvider instance for this WebContents object. This will
1823   // always return a valid ColorProvider instance.
1824   const ui::ColorProvider& GetColorProvider() const override;
1825
1826   // Sets the visibility to |new_visibility| and propagates this to the
1827   // renderer side, taking into account the current capture state. This
1828   // can be called with the current visibility to affect capturing
1829   // changes.
1830   // |is_activity| controls whether a change to |visible| affects
1831   // the value returned by GetLastActiveTime().
1832   void UpdateVisibilityAndNotifyPageAndView(Visibility new_visibility,
1833                                             bool is_activity = true);
1834
1835   // Returns UKM source id for the currently displayed page.
1836   // Intentionally kept private, prefer using
1837   // render_frame_host->GetPageUkmSourceId() if you already have a
1838   // |render_frame_host| reference or
1839   // GetPrimaryMainFrame()->GetPageUkmSourceId() if you don't.
1840   ukm::SourceId GetCurrentPageUkmSourceId() override;
1841
1842   // Bit mask to indicate what types of RenderViewHosts to be returned in
1843   // ForEachRenderViewHost.
1844   enum ForEachRenderViewHostTypes {
1845     kPrerenderViews = 1 << 0,
1846     kBackForwardCacheViews = 1 << 1,
1847     kActiveViews = 1 << 2,
1848     kAllViews = kActiveViews | kBackForwardCacheViews | kPrerenderViews,
1849   };
1850
1851   // For each RenderViewHost (including bfcache, prerendering) call the
1852   // callback, this will be filtered by `view_mask`.
1853   void ForEachRenderViewHost(
1854       ForEachRenderViewHostTypes view_mask,
1855       RenderViewHostIterationCallback on_render_view_host);
1856
1857   // Sets the hardware-related fields in |prefs| that are slow to compute.  The
1858   // fields are set from cache if available, otherwise recomputed.
1859   void SetSlowWebPreferences(const base::CommandLine& command_line,
1860                              blink::web_pref::WebPreferences* prefs);
1861
1862   // This is the actual implementation of the various overloads of
1863   // |ForEachRenderFrameHost|.
1864   void ForEachRenderFrameHostImpl(
1865       base::FunctionRef<FrameIterationAction(RenderFrameHostImpl*)> on_frame,
1866       bool include_speculative);
1867
1868   // Calls |on_frame_tree| for every FrameTree in this WebContents.
1869   // This does not descend into inner WebContents, but does include inner frame
1870   // trees based on MPArch.
1871   void ForEachFrameTree(FrameTreeIterationCallback on_frame_tree);
1872
1873   // Returns the primary frame tree, followed by any other outermost frame trees
1874   // in this WebContents. Outermost frame trees include, for example,
1875   // prerendering frame trees, and do not include, for example, fenced frames or
1876   // portals. Also note that bfcached pages do not have a distinct frame tree,
1877   // so the primary frame tree in the result would be the only FrameTree
1878   // representing any bfcached pages.
1879   std::vector<FrameTree*> GetOutermostFrameTrees();
1880
1881   // Returns the primary main frame, followed by the main frames of any other
1882   // outermost frame trees in this WebContents and the main frames of any
1883   // bfcached pages. Note that unlike GetOutermostFrameTrees, bfcached pages
1884   // have a distinct RenderFrameHostImpl in this result.
1885   std::vector<RenderFrameHostImpl*> GetOutermostMainFrames();
1886
1887   // Called when the base::ScopedClosureRunner returned by
1888   // IncrementCapturerCount() is destructed.
1889   void DecrementCapturerCount(bool stay_hidden,
1890                               bool stay_awake,
1891                               bool is_activity = true);
1892
1893   // Calculates the PageVisibilityState for |visibility|, taking the capturing
1894   // state into account.
1895   PageVisibilityState CalculatePageVisibilityState(Visibility visibility) const;
1896
1897   // Called when the process hosting the primary main RenderFrameHost is known
1898   // to be alive.
1899   void NotifyPrimaryMainFrameProcessIsAlive();
1900
1901   // If |entry| is null, this method updates the WebContents' fallback title for
1902   // when there is no navigation entry (i.e. when GetNavigationEntryForTitle()
1903   // returns nullptr), otherwise updates |entry|'s title. If defined, |entry|
1904   // must belong to the WebContents' primary NavigationController. Returns true
1905   // if the title (entry's or fallback) was changed, false otherwise.
1906   bool UpdateTitleForEntryImpl(NavigationEntryImpl* entry,
1907                                const std::u16string& title);
1908   // Dispatches WebContentsObserver::TitleWasSet and also notifies the delegate
1909   // of a title change if |entry| is the entry whose title is being used as the
1910   // display title.
1911   void NotifyTitleUpdateForEntry(NavigationEntryImpl* entry);
1912   // Returns the navigation entry whose title is used as the display title for
1913   // this WebContents (i.e. for WebContents::GetTitle()). This value can be
1914   // null, in which case a fallback title is used (see
1915   // |page_title_when_no_navigation_entry_|).
1916   NavigationEntry* GetNavigationEntryForTitle();
1917
1918   // Wrapper for ui::GetAvailablePointerAndHoverTypes which temporarily allows
1919   // blocking calls required on Windows when running on touch enabled devices.
1920   static std::pair<int, int> GetAvailablePointerAndHoverTypes();
1921
1922   // Apply shared logic for SetHasPictureInPictureVideo() and
1923   // SetHasPictureInPictureDocument().
1924   void SetHasPictureInPictureCommon(bool has_picture_in_picture);
1925
1926   // Data for core operation ---------------------------------------------------
1927
1928   // Delegate for notifying our owner about stuff. Not owned by us.
1929   raw_ptr<WebContentsDelegate> delegate_;
1930
1931   // The corresponding view.
1932   std::unique_ptr<WebContentsView> view_;
1933
1934   // The view of the RVHD. Usually this is our WebContentsView implementation,
1935   // but if an embedder uses a different WebContentsView, they'll need to
1936   // provide this.
1937   RenderViewHostDelegateView* render_view_host_delegate_view_;
1938
1939   // Tracks CreatedWindow objects that have not been shown yet. They are
1940   // identified by the process ID and routing ID passed to CreateNewWindow.
1941   std::map<GlobalRoutingID, CreatedWindow> pending_contents_;
1942
1943   // Watches for the destruction of items in `pending_contents_`.
1944   std::map<WebContentsImpl*, std::unique_ptr<WebContentsDestructionObserver>>
1945       web_contents_destruction_observers_;
1946
1947   // This map holds widgets that were created on behalf of the renderer but
1948   // haven't been shown yet.
1949   std::map<GlobalRoutingID, RenderWidgetHost*> pending_widgets_;
1950
1951   // Watches for the destruction of items in `pending_widgets_`.
1952   std::map<RenderWidgetHost*,
1953            std::unique_ptr<RenderWidgetHostDestructionObserver>>
1954       render_widget_host_destruction_observers_;
1955
1956   // A list of observers notified when page state changes. Weak references.
1957   // This MUST be listed above `primary_frame_tree_` since at destruction time
1958   // the latter might cause RenderViewHost's destructor to call us and we might
1959   // use the observer list then.
1960   WebContentsObserverList observers_;
1961
1962   // True if this tab was opened by another window. This is true even if the tab
1963   // is opened with "noopener", and won't be unset if the opener is closed.
1964   bool opened_by_another_window_;
1965
1966 #if BUILDFLAG(IS_ANDROID)
1967   std::unique_ptr<WebContentsAndroid> web_contents_android_;
1968 #endif
1969
1970   // Helper classes ------------------------------------------------------------
1971
1972   // Primary FrameTree of this WebContents instance. This WebContents might have
1973   // additional FrameTrees for features like prerendering and fenced frames,
1974   // which either might be standalone (prerendering) to nested within a
1975   // different FrameTree (fenced frame).
1976   FrameTree primary_frame_tree_;
1977
1978   // Contains information about the WebContents tree structure.
1979   WebContentsTreeNode node_;
1980
1981   // SavePackage, lazily created.
1982   scoped_refptr<SavePackage> save_package_;
1983
1984   // Manages/coordinates multi-process find-in-page requests. Created lazily.
1985   std::unique_ptr<FindRequestManager> find_request_manager_;
1986
1987   // Data for loading state ----------------------------------------------------
1988
1989   // Indicates whether the current navigation should show loading UI. Only valid
1990   // if |is_loading_| is true and only tracks loads in the main frame.
1991   // TODO(pbos): Check navigation requests and handles instead of caching this.
1992   bool should_show_loading_ui_;
1993
1994   // Indicates the process state of the primary main frame's renderer process.
1995   // If the process is not live due to a crash, this will be reflected by
1996   // IsCrashed(), though it's possible to not be live while not indicating a
1997   // crash occurred.
1998   base::TerminationStatus primary_main_frame_process_status_;
1999   int primary_main_frame_process_error_code_;
2000
2001   // The current load state and the URL associated with it.
2002   net::LoadStateWithParam load_state_;
2003   std::u16string load_state_host_;
2004   base::TimeTicks load_info_timestamp_;
2005
2006   base::TimeTicks loading_last_progress_update_;
2007
2008   // Default value is set to 100ms between LoadProgressChanged events.
2009   base::TimeDelta minimum_delay_between_loading_updates_ms_ =
2010       base::Milliseconds(100);
2011
2012   // Upload progress, for displaying in the status bar.
2013   // Set to zero when there is no significant upload happening.
2014   uint64_t upload_size_;
2015   uint64_t upload_position_;
2016
2017   // Tracks that this WebContents needs to unblock requests to the renderer.
2018   // See ResumeLoadingCreatedWebContents.
2019   bool is_resume_pending_;
2020
2021   // Data for current page -----------------------------------------------------
2022
2023   // When a title cannot be taken from any entry, this title will be used.
2024   std::u16string page_title_when_no_navigation_entry_;
2025
2026   // The last published theme color.
2027   absl::optional<SkColor> last_sent_theme_color_;
2028
2029   // The last published background color.
2030   absl::optional<SkColor> last_sent_background_color_;
2031
2032   // Data for misc internal state ----------------------------------------------
2033
2034   // When either > 0, the WebContents is currently being captured (e.g.,
2035   // for screenshots or mirroring); and the underlying RenderWidgetHost
2036   // should not be told it is hidden. If |visible_capturer_count_| > 0,
2037   // the underlying Page is set to fully visible. Otherwise, it is set
2038   // to be hidden but still paint.
2039   int visible_capturer_count_ = 0;
2040   int hidden_capturer_count_ = 0;
2041
2042   // When > 0, |capture_wake_lock_| will be held to prevent display sleep.
2043   int stay_awake_capturer_count_ = 0;
2044
2045   // WakeLock held to ensure screen capture keeps the display on. E.g., for
2046   // presenting through tab capture APIs.
2047   mojo::Remote<device::mojom::WakeLock> capture_wake_lock_;
2048
2049   // The visibility of the WebContents. Initialized from
2050   // |CreateParams::initially_hidden|. Updated from
2051   // UpdateWebContentsVisibility(), WasShown(), WasHidden(), WasOccluded().
2052   Visibility visibility_ = Visibility::VISIBLE;
2053
2054   // Whether there has been a call to UpdateWebContentsVisibility(VISIBLE).
2055   bool did_first_set_visible_ = false;
2056
2057   // Set to true while calling out to notify one-off observers (ie non-
2058   // WebContentsObservers). These observers should not destroy WebContentsImpl
2059   // while it is on the call stack, as that leads to use-after-frees.
2060   bool prevent_destruction_ = false;
2061
2062   bool is_being_destroyed_ = false;
2063
2064   // Indicates whether we should notify about disconnection of this
2065   // WebContentsImpl. This is used to ensure disconnection notifications only
2066   // happen if a connection notification has happened and that they happen only
2067   // once.
2068   bool notify_disconnection_;
2069
2070   // Set to true if we shouldn't send input events.
2071   bool ignore_input_events_ = false;
2072
2073   // Pointer to the JavaScript dialog manager, lazily assigned. Used because the
2074   // delegate of this WebContentsImpl is nulled before its destructor is called.
2075   raw_ptr<JavaScriptDialogManager> dialog_manager_;
2076
2077   // Set to true when there is an active JavaScript dialog showing.
2078   bool is_showing_javascript_dialog_ = false;
2079
2080   // Set to true when there is an active "before unload" dialog.  When true,
2081   // we've forced the throbber to start in Navigate, and we need to remember to
2082   // turn it off in OnJavaScriptMessageBoxClosed if the navigation is canceled.
2083   bool is_showing_before_unload_dialog_;
2084
2085   // Settings that get passed to the renderer process.
2086   blink::RendererPreferences renderer_preferences_;
2087
2088   // The time that this WebContents was last made active. The initial value is
2089   // the WebContents creation time.
2090   base::TimeTicks last_active_time_;
2091
2092   // The time that this WebContents last received an 'interactive' input event
2093   // from the user. Interactive input events are things like mouse clicks and
2094   // keyboard input, but not mouse wheel scrolling or mouse moves.
2095   base::TimeTicks last_interactive_input_event_time_;
2096
2097   // See description above setter.
2098   bool closed_by_user_gesture_;
2099
2100   // The number of active fullscreen blockers.
2101   int fullscreen_blocker_count_ = 0;
2102
2103   // Minimum/maximum zoom percent.
2104   const int minimum_zoom_percent_;
2105   const int maximum_zoom_percent_;
2106
2107   // Used to correctly handle integer zooming through a smooth scroll device.
2108   float zoom_scroll_remainder_;
2109
2110   // The intrinsic size of the page.
2111   gfx::Size preferred_size_;
2112
2113   // The preferred size for content screen capture.  When |capturer_count_| > 0,
2114   // this overrides |preferred_size_|.
2115   gfx::Size preferred_size_for_capture_;
2116
2117   // When device emulation is enabled, override the size of current and newly
2118   // created render views/widgets.
2119   gfx::Size device_emulation_size_;
2120   gfx::Size view_size_before_emulation_;
2121
2122 #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
2123   // Holds information about a current color chooser dialog, if one is visible.
2124   class ColorChooserHolder;
2125   std::unique_ptr<ColorChooserHolder> color_chooser_holder_;
2126 #endif  // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
2127
2128   // Manages the embedder state for browser plugins, if this WebContents is an
2129   // embedder; NULL otherwise.
2130   std::unique_ptr<BrowserPluginEmbedder> browser_plugin_embedder_;
2131   // Manages the guest state for browser plugin, if this WebContents is a guest;
2132   // NULL otherwise.
2133   std::unique_ptr<BrowserPluginGuest> browser_plugin_guest_;
2134
2135   // All live RenderWidgetHostImpls that are created by this object and may
2136   // outlive it.
2137   std::set<RenderWidgetHostImpl*> created_widgets_;
2138
2139   // Process id of the shown fullscreen widget, or kInvalidUniqueID if there is
2140   // no fullscreen widget.
2141   int fullscreen_widget_process_id_;
2142
2143   // Routing id of the shown fullscreen widget or MSG_ROUTING_NONE otherwise.
2144   int fullscreen_widget_routing_id_;
2145
2146   // At the time the fullscreen widget was being shut down, did it have focus?
2147   // This is used to restore focus to the WebContentsView after both: 1) the
2148   // fullscreen widget is destroyed, and 2) the WebContentsDelegate has
2149   // completed making layout changes to effect an exit from fullscreen mode.
2150   bool fullscreen_widget_had_focus_at_shutdown_;
2151
2152   // When a new tab is created asynchronously, stores the OpenURLParams needed
2153   // to continue loading the page once the tab is ready.
2154   std::unique_ptr<OpenURLParams> delayed_open_url_params_;
2155
2156   // When a new tab is created with window.open(), navigation can be deferred
2157   // to execute asynchronously. In such case, the parameters need to be saved
2158   // for the navigation to be started at a later point.
2159   std::unique_ptr<NavigationController::LoadURLParams> delayed_load_url_params_;
2160
2161   // Whether overscroll should be unconditionally disabled.
2162   bool force_disable_overscroll_content_;
2163
2164   // Whether the last JavaScript dialog shown was suppressed. Used for testing.
2165   bool last_dialog_suppressed_;
2166
2167   mojo::Remote<device::mojom::GeolocationContext> geolocation_context_;
2168
2169   mojo::AssociatedRemote<blink::mojom::ContextMenuClient> context_menu_client_;
2170
2171   std::unique_ptr<WakeLockContextHost> wake_lock_context_host_;
2172   bool enable_wake_locks_ = true;
2173
2174   // The last set/computed value of WebPreferences for this WebContents, either
2175   // set directly through SetWebPreferences, or set after recomputing values
2176   // from ComputeWebPreferences.
2177   std::unique_ptr<blink::web_pref::WebPreferences> web_preferences_;
2178
2179   bool updating_web_preferences_ = false;
2180
2181 #if BUILDFLAG(IS_ANDROID)
2182   std::unique_ptr<NFCHost> nfc_host_;
2183 #endif
2184
2185   mojo::ReceiverSet<blink::mojom::ColorChooserFactory>
2186       color_chooser_factory_receivers_;
2187
2188   std::unique_ptr<ScreenOrientationProvider> screen_orientation_provider_;
2189
2190   // The accessibility mode for all frames. This is queried when each frame
2191   // is created, and broadcast to all frames when it changes.
2192   ui::AXMode accessibility_mode_;
2193
2194   std::unique_ptr<ui::AXEventRecorder> event_recorder_;
2195
2196   // Monitors power levels for audio streams associated with this WebContents.
2197   AudioStreamMonitor audio_stream_monitor_;
2198
2199   // Coordinates all the audio streams for this WebContents. Lazily initialized.
2200   absl::optional<ForwardingAudioStreamFactory> audio_stream_factory_;
2201
2202   size_t bluetooth_connected_device_count_ = 0;
2203   size_t bluetooth_scanning_sessions_count_ = 0;
2204   size_t serial_active_frame_count_ = 0;
2205   size_t hid_active_frame_count_ = 0;
2206   size_t usb_active_frame_count_ = 0;
2207
2208   size_t file_system_access_handle_count_ = 0;
2209
2210   bool has_picture_in_picture_video_ = false;
2211   bool has_picture_in_picture_document_ = false;
2212
2213   // Manages media players, CDMs, and power save blockers for media.
2214   std::unique_ptr<MediaWebContentsObserver> media_web_contents_observer_;
2215
2216 #if BUILDFLAG(ENABLE_PPAPI)
2217   // Observes pepper playback changes, and notifies MediaSession.
2218   std::unique_ptr<PepperPlaybackObserver> pepper_playback_observer_;
2219 #endif  // BUILDFLAG(ENABLE_PPAPI)
2220
2221   std::unique_ptr<RenderWidgetHostInputEventRouter> rwh_input_event_router_;
2222
2223   // TextInputManager tracks the IME-related state for all the
2224   // RenderWidgetHostViews on this WebContents. Only exists on the outermost
2225   // WebContents and is automatically destroyed when a WebContents becomes an
2226   // inner WebContents by attaching to an outer WebContents. Then the
2227   // IME-related state for RenderWidgetHosts on the inner WebContents is tracked
2228   // by the TextInputManager in the outer WebContents.
2229   std::unique_ptr<TextInputManager> text_input_manager_;
2230
2231   // Tests can set this to true in order to force this web contents to always
2232   // return nullptr for the above `text_input_manager_`, effectively blocking
2233   // IME events from propagating out of the renderer.
2234   bool suppress_ime_events_for_testing_ = false;
2235
2236   // Stores the RenderWidgetHost that currently holds a mouse lock or nullptr if
2237   // there's no RenderWidgetHost holding a lock.
2238   raw_ptr<RenderWidgetHostImpl> mouse_lock_widget_ = nullptr;
2239
2240   // Stores the RenderWidgetHost that currently holds a keyboard lock or nullptr
2241   // if no RenderWidgetHost has the keyboard locked.
2242   raw_ptr<RenderWidgetHostImpl> keyboard_lock_widget_ = nullptr;
2243
2244   // Indicates whether the escape key is one of the requested keys to be locked.
2245   // This information is used to drive the browser UI so the correct exit
2246   // instructions are displayed to the user in fullscreen mode.
2247   bool esc_key_locked_ = false;
2248
2249 #if BUILDFLAG(IS_ANDROID)
2250   std::unique_ptr<service_manager::InterfaceProvider> java_interfaces_;
2251 #endif
2252
2253   // Whether this WebContents is for content overlay.
2254   bool is_overlay_content_;
2255
2256   bool showing_context_menu_;
2257
2258   int currently_playing_video_count_ = 0;
2259   base::flat_map<MediaPlayerId, gfx::Size> cached_video_sizes_;
2260
2261   bool has_persistent_video_ = false;
2262
2263   bool is_spatial_navigation_disabled_ = false;
2264
2265   bool stylus_handwriting_enabled_ = false;
2266
2267   bool is_currently_audible_ = false;
2268   bool was_ever_audible_ = false;
2269
2270   // Helper variable for resolving races in UpdateTargetURL / ClearTargetURL.
2271   raw_ptr<RenderFrameHost> frame_that_set_last_target_url_ = nullptr;
2272
2273   // Whether we should override user agent in new tabs.
2274   bool should_override_user_agent_in_new_tabs_ = false;
2275
2276   // Used to determine the value of is-user-agent-overriden for renderer
2277   // initiated navigations.
2278   NavigationController::UserAgentOverrideOption
2279       renderer_initiated_user_agent_override_option_ =
2280           NavigationController::UA_OVERRIDE_INHERIT;
2281
2282   // Gets notified about changes in viewport fit events.
2283   std::unique_ptr<DisplayCutoutHostImpl> display_cutout_host_impl_;
2284
2285   // Stores a set of frames that are fullscreen.
2286   // See https://fullscreen.spec.whatwg.org.
2287   std::set<RenderFrameHostImpl*> fullscreen_frames_;
2288
2289   // Store the frame that is currently fullscreen, nullptr if there is none.
2290   raw_ptr<RenderFrameHostImpl> current_fullscreen_frame_ = nullptr;
2291
2292   // Whether location bar should be focused by default. This is computed in
2293   // DidStartNavigation/DidFinishNavigation and only set for an initial
2294   // navigation triggered by the browser going to about:blank.
2295   bool should_focus_location_bar_by_default_ = false;
2296
2297   // Stores the Portal object associated with this WebContents, if there is one.
2298   // If non-null then this WebContents is embedded in a portal and its outer
2299   // WebContents can be found by using GetOuterWebContents().
2300   raw_ptr<Portal> portal_ = nullptr;
2301
2302   // Stores the rect of the Windows Control Overlay, which contains system UX
2303   // affordances (e.g. close), for installed desktop Progress Web Apps (PWAs),
2304   // if the app specifies the 'window-controls-overlay' DisplayMode in its
2305   // manifest. This is in frame space coordinates.
2306   gfx::Rect window_controls_overlay_rect_;
2307
2308   // Observe native theme for changes to dark mode, preferred color scheme, and
2309   // preferred contrast. Used to notify the renderer of preferred color scheme
2310   // and preferred contrast changes.
2311   base::ScopedObservation<ui::NativeTheme, ui::NativeThemeObserver>
2312       native_theme_observation_{this};
2313
2314   bool using_dark_colors_ = false;
2315   ui::NativeTheme::PreferredColorScheme preferred_color_scheme_ =
2316       ui::NativeTheme::PreferredColorScheme::kLight;
2317   ui::NativeTheme::PreferredContrast preferred_contrast_ =
2318       ui::NativeTheme::PreferredContrast::kNoPreference;
2319
2320   // Tracks clients who want to be notified when a JavaScript dialog is
2321   // dismissed.
2322   std::unique_ptr<JavaScriptDialogDismissNotifier>
2323       javascript_dialog_dismiss_notifier_;
2324
2325   // The max number of loaded frames that have been seen in this WebContents.
2326   // This number is reset with each main frame navigation.
2327   size_t max_loaded_frame_count_ = 0;
2328
2329   // This boolean value is used to keep track of whether we finished the first
2330   // successful navigation in this WebContents's primary main frame.
2331   bool first_primary_navigation_completed_ = false;
2332
2333   // Monitors system screen info changes to notify the renderer.
2334   std::unique_ptr<ScreenChangeMonitor> screen_change_monitor_;
2335
2336   // Records the last time we saw a screen orientation change.
2337   base::TimeTicks last_screen_orientation_change_time_;
2338
2339   // Manages a transient affordance for this page's frames to enter fullscreen.
2340   blink::TransientAllowFullscreen transient_allow_fullscreen_;
2341
2342   // Indicates how many sources are currently suppressing the unresponsive
2343   // renderer dialog.
2344   int suppress_unresponsive_renderer_count_ = 0;
2345
2346   std::unique_ptr<PrerenderHostRegistry> prerender_host_registry_;
2347
2348   std::unique_ptr<power_scheduler::PowerModeVoter> audible_power_mode_voter_;
2349
2350   viz::FrameSinkId xr_render_target_;
2351
2352   base::OnceCallback<void(const gfx::Rect&)> show_poup_menu_callback_;
2353
2354   // Allows the app in the current WebContents to opt-in to exposing
2355   // information to apps that capture it.
2356   blink::mojom::CaptureHandleConfig capture_handle_config_;
2357
2358   // Background color of the page set by the embedder to be passed to all
2359   // renderers attached to this WebContents, for use in the main frame.
2360   // It is used when the page has not loaded enough to know a background
2361   // color or if the page does not set a background color.
2362   absl::optional<SkColor> page_base_background_color_;
2363
2364   // TODO(1231679): Remove/reevaluate after the PCScan experiment is finished.
2365   std::unique_ptr<StarScanLoadObserver> star_scan_load_observer_;
2366
2367   // Stores WebContents::CreateParams::creator_location_.
2368   base::Location creator_location_;
2369
2370   // The initial aspect ratio (only used for WebContents associated with a
2371   // PictureInPicture window). This value is either the parameter given in
2372   // WebContents::CreateParams::initial_picture_in_picture_aspect_ratio, or a
2373   // default value if the given value is unset or invalid.
2374   float pip_initial_aspect_ratio_ = 1.0f;
2375
2376   // Stores WebContents::CreateParams::lock_picture_in_picture_aspect_ratio.
2377   bool pip_lock_aspect_ratio_ = false;
2378
2379   VisibleTimeRequestTrigger visible_time_request_trigger_;
2380
2381   // Stores the information whether last navigation was prerender activation for
2382   // DevTools. Set when a prerender activation completes, and cleared when
2383   // either DevTools is opened and consults this value or when a non-prerendered
2384   // navigation commits in the primary main frame.
2385   bool last_navigation_was_prerender_activation_for_devtools_ = false;
2386
2387   bool prerender2_disabled_ = false;
2388
2389 #if defined(USE_EFL)
2390   Evas_Object* efl_native_view_ = nullptr;
2391   void* ewk_view_ = nullptr;
2392 #endif
2393
2394   base::WeakPtrFactory<WebContentsImpl> loading_weak_factory_{this};
2395   base::WeakPtrFactory<WebContentsImpl> weak_factory_{this};
2396 };
2397
2398 // Dangerous methods which should never be made part of the public API, so we
2399 // grant their use only to an explicit friend list (c++ attorney/client idiom).
2400 class CONTENT_EXPORT WebContentsImpl::FriendWrapper {
2401  public:
2402   using CreatedCallback = base::RepeatingCallback<void(WebContents*)>;
2403
2404   FriendWrapper(const FriendWrapper&) = delete;
2405   FriendWrapper& operator=(const FriendWrapper&) = delete;
2406
2407  private:
2408   friend base::CallbackListSubscription RegisterWebContentsCreationCallback(
2409       base::RepeatingCallback<void(WebContents*)>);
2410
2411   FriendWrapper();  // Not instantiable.
2412
2413   // Adds a callback called on creation of each new WebContents.
2414   static base::CallbackListSubscription AddCreatedCallbackForTesting(
2415       const CreatedCallback& callback);
2416 };
2417
2418 }  // namespace content
2419
2420 #endif  // CONTENT_BROWSER_WEB_CONTENTS_WEB_CONTENTS_IMPL_H_