1 /*
2  * Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
3  *                     1999-2001 Lars Knoll <knoll@kde.org>
4  *                     1999-2001 Antti Koivisto <koivisto@kde.org>
5  *                     2000-2001 Simon Hausmann <hausmann@kde.org>
6  *                     2000-2001 Dirk Mueller <mueller@kde.org>
7  *                     2000 Stefan Schimanski <1Stein@gmx.de>
8  * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights
9  * reserved.
10  * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
11  * Copyright (C) 2008 Eric Seidel <eric@webkit.org>
12  *
13  * This library is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU Library General Public
15  * License as published by the Free Software Foundation; either
16  * version 2 of the License, or (at your option) any later version.
17  *
18  * This library is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21  * Library General Public License for more details.
22  *
23  * You should have received a copy of the GNU Library General Public License
24  * along with this library; see the file COPYING.LIB.  If not, write to
25  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
26  * Boston, MA 02110-1301, USA.
27  */
28 
29 #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_LOCAL_FRAME_H_
30 #define THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_LOCAL_FRAME_H_
31 
32 #include <memory>
33 
34 #include "base/macros.h"
35 #include "base/time/default_tick_clock.h"
36 #include "base/unguessable_token.h"
37 #include "mojo/public/cpp/bindings/associated_receiver.h"
38 #include "mojo/public/cpp/bindings/associated_remote.h"
39 #include "mojo/public/cpp/bindings/pending_associated_receiver.h"
40 #include "mojo/public/cpp/bindings/pending_receiver.h"
41 #include "mojo/public/cpp/bindings/unique_receiver_set.h"
42 #include "third_party/blink/public/mojom/frame/frame.mojom-blink.h"
43 #include "third_party/blink/public/mojom/frame/frame_owner_properties.mojom-blink-forward.h"
44 #include "third_party/blink/public/mojom/frame/lifecycle.mojom-blink-forward.h"
45 #include "third_party/blink/public/mojom/input/focus_type.mojom-blink-forward.h"
46 #include "third_party/blink/public/mojom/loader/pause_subresource_loading_handle.mojom-blink-forward.h"
47 #include "third_party/blink/public/mojom/reporting/reporting.mojom-blink.h"
48 #include "third_party/blink/public/mojom/web_feature/web_feature.mojom-blink-forward.h"
49 #include "third_party/blink/public/platform/task_type.h"
50 #include "third_party/blink/public/platform/viewport_intersection_state.h"
51 #include "third_party/blink/renderer/core/clipboard/raw_system_clipboard.h"
52 #include "third_party/blink/renderer/core/clipboard/system_clipboard.h"
53 #include "third_party/blink/renderer/core/core_export.h"
54 #include "third_party/blink/renderer/core/dom/weak_identifier_map.h"
55 #include "third_party/blink/renderer/core/editing/forward.h"
56 #include "third_party/blink/renderer/core/frame/frame.h"
57 #include "third_party/blink/renderer/core/frame/frame_types.h"
58 #include "third_party/blink/renderer/core/frame/local_dom_window.h"
59 #include "third_party/blink/renderer/core/frame/local_frame_view.h"
60 #include "third_party/blink/renderer/core/inspector/inspector_issue.h"
61 #include "third_party/blink/renderer/core/loader/frame_loader.h"
62 #include "third_party/blink/renderer/platform/graphics/touch_action.h"
63 #include "third_party/blink/renderer/platform/heap/handle.h"
64 #include "third_party/blink/renderer/platform/instrumentation/instance_counters.h"
65 #include "third_party/blink/renderer/platform/loader/fetch/client_hints_preferences.h"
66 #include "third_party/blink/renderer/platform/scheduler/public/frame_scheduler.h"
67 #include "third_party/blink/renderer/platform/supplementable.h"
68 
69 namespace base {
70 class SingleThreadTaskRunner;
71 }
72 
73 namespace gfx {
74 class Point;
75 }
76 
77 namespace blink {
78 
79 class AdTracker;
80 class AssociatedInterfaceProvider;
81 class BrowserInterfaceBrokerProxy;
82 class Color;
83 class ContentCaptureManager;
84 class Document;
85 class Editor;
86 class Element;
87 class EventHandler;
88 class EventHandlerRegistry;
89 class FloatSize;
90 class FrameConsole;
91 class FrameOverlay;
92 // class FrameScheduler;
93 class FrameSelection;
94 class FrameWidget;
95 class InputMethodController;
96 class InspectorTraceEvents;
97 class CoreProbeSink;
98 class IdlenessDetector;
99 class InspectorTaskRunner;
100 class InterfaceRegistry;
101 class IntSize;
102 class LayoutView;
103 class LocalWindowProxy;
104 class LocalFrameClient;
105 class Node;
106 class NodeTraversal;
107 class PerformanceMonitor;
108 class PluginData;
109 class ScriptController;
110 class SmoothScrollSequencer;
111 class SpellChecker;
112 class TextSuggestionController;
113 class WebContentSettingsClient;
114 class WebPluginContainerImpl;
115 class WebPrescientNetworking;
116 class WebURLLoaderFactory;
117 
118 extern template class CORE_EXTERN_TEMPLATE_EXPORT Supplement<LocalFrame>;
119 
120 class CORE_EXPORT LocalFrame final : public Frame,
121                                      public FrameScheduler::Delegate,
122                                      public Supplementable<LocalFrame>,
123                                      public mojom::blink::LocalFrame,
124                                      public mojom::blink::LocalMainFrame {
125   USING_GARBAGE_COLLECTED_MIXIN(LocalFrame);
126 
127  public:
128   // For a description of |inheriting_agent_factory| go see the comment on the
129   // Frame constructor.
130   LocalFrame(
131       LocalFrameClient*,
132       Page&,
133       FrameOwner*,
134       WindowAgentFactory* inheriting_agent_factory,
135       InterfaceRegistry*,
136       const base::TickClock* clock = base::DefaultTickClock::GetInstance());
137 
138   void Init();
139   void SetView(LocalFrameView*);
140   void CreateView(const IntSize&, const Color&);
141 
142   // Frame overrides:
143   ~LocalFrame() override;
144   void Trace(Visitor*) override;
145   void Navigate(FrameLoadRequest&, WebFrameLoadType) override;
146   bool ShouldClose() override;
147   const SecurityContext* GetSecurityContext() const override;
148   void PrintNavigationErrorMessage(const Frame&, const char* reason);
149   void PrintNavigationWarning(const String&);
150   bool DetachDocument() override;
151   void CheckCompleted() override;
152   void DidChangeVisibilityState() override;
153   void HookBackForwardCacheEviction() override;
154   void RemoveBackForwardCacheEviction() override;
155   // This sets the is_inert_ flag and also recurses through this frame's
156   // subtree, updating the inert bit on all descendant frames.
157   void SetIsInert(bool) override;
158   void SetInheritedEffectiveTouchAction(TouchAction) override;
159   bool BubbleLogicalScrollFromChildFrame(
160       mojom::blink::ScrollDirection direction,
161       ScrollGranularity granularity,
162       Frame* child) override;
163   void DidFocus() override;
164 
165   void DidChangeThemeColor();
166 
167   void DetachChildren();
168   // After Document is attached, resets state related to document, and sets
169   // context to the current document.
170   void DidAttachDocument();
171 
172   void Reload(WebFrameLoadType);
173 
174   // Note: these two functions are not virtual but intentionally shadow the
175   // corresponding method in the Frame base class to return the
176   // LocalFrame-specific subclass.
177   LocalWindowProxy* WindowProxy(DOMWrapperWorld&);
178   LocalDOMWindow* DomWindow() const;
179   void SetDOMWindow(LocalDOMWindow*);
180   LocalFrameView* View() const override;
181   Document* GetDocument() const;
182   void SetPagePopupOwner(Element&);
PagePopupOwner()183   Element* PagePopupOwner() const { return page_popup_owner_.Get(); }
184 
185   // Root of the layout tree for the document contained in this frame.
186   LayoutView* ContentLayoutObject() const;
187 
188   Editor& GetEditor() const;
189   EventHandler& GetEventHandler() const;
190   EventHandlerRegistry& GetEventHandlerRegistry() const;
191   FrameLoader& Loader() const;
192   FrameSelection& Selection() const;
193   InputMethodController& GetInputMethodController() const;
194   TextSuggestionController& GetTextSuggestionController() const;
195   ScriptController& GetScriptController() const;
196   SpellChecker& GetSpellChecker() const;
197   FrameConsole& Console() const;
198 
199   // A local root is the root of a connected subtree that contains only
200   // LocalFrames. The local root is responsible for coordinating input, layout,
201   // et cetera for that subtree of frames.
202   bool IsLocalRoot() const;
203   LocalFrame& LocalFrameRoot() const;
204 
GetProbeSink()205   CoreProbeSink* GetProbeSink() { return probe_sink_.Get(); }
206   scoped_refptr<InspectorTaskRunner> GetInspectorTaskRunner();
207 
208   // Returns ContentCaptureManager in LocalFrameRoot.
209   ContentCaptureManager* GetContentCaptureManager();
210 
211   // Returns the current state of caret browsing mode.
212   bool IsCaretBrowsingEnabled() const;
213 
214   // Activates the user activation states of the |LocalFrame| (provided it's
215   // non-null) and all its ancestors.
216   static void NotifyUserActivation(LocalFrame*,
217                                    bool need_browser_verification = false);
218 
219   // Returns the transient user activation state of the |LocalFrame|, provided
220   // it is non-null.  Otherwise returns |false|.
221   static bool HasTransientUserActivation(LocalFrame*);
222 
223   // Consumes the transient user activation state of the |LocalFrame|, provided
224   // the frame pointer is non-null and the state hasn't been consumed since
225   // activation.  Returns |true| if successfully consumed the state.
226   static bool ConsumeTransientUserActivation(
227       LocalFrame*,
228       UserActivationUpdateSource update_source =
229           UserActivationUpdateSource::kRenderer);
230 
231   // =========================================================================
232   // All public functions below this point are candidates to move out of
233   // LocalFrame into another class.
234 
235   // See GraphicsLayerClient.h for accepted flags.
236   String GetLayerTreeAsTextForTesting(unsigned flags = 0) const;
237 
238   // Begin printing with the given page size information.
239   // The frame content will fit to the page size with specified shrink ratio.
240   // If this frame doesn't need to fit into a page size, default values are
241   // used.
242   void StartPrinting(const FloatSize& page_size = FloatSize(),
243                      const FloatSize& original_page_size = FloatSize(),
244                      float maximum_shrink_ratio = 0);
245 
246   void EndPrinting();
247   bool ShouldUsePrintingLayout() const;
248   FloatSize ResizePageRectsKeepingRatio(const FloatSize& original_size,
249                                         const FloatSize& expected_size) const;
250 
251   bool InViewSourceMode() const;
252   void SetInViewSourceMode(bool = true);
253 
254   void SetPageZoomFactor(float);
PageZoomFactor()255   float PageZoomFactor() const { return page_zoom_factor_; }
256   void SetTextZoomFactor(float);
TextZoomFactor()257   float TextZoomFactor() const { return text_zoom_factor_; }
258   void SetPageAndTextZoomFactors(float page_zoom_factor,
259                                  float text_zoom_factor);
260 
261   void DeviceScaleFactorChanged();
262   double DevicePixelRatio() const;
263 
264   String SelectedText() const;
265   String SelectedTextForClipboard() const;
266 
267   PositionWithAffinityTemplate<EditingAlgorithm<NodeTraversal>>
268   PositionForPoint(const PhysicalOffset& frame_point);
269   Document* DocumentAtPoint(const PhysicalOffset&);
270 
271   void RemoveSpellingMarkersUnderWords(const Vector<String>& words);
272 
273   bool ShouldThrottleRendering() const;
274   void DispatchBeforeUnloadEventForFreeze();
275 
276   // Returns frame scheduler for this frame.
277   // FrameScheduler is destroyed during frame detach and nullptr will be
278   // returned after it.
279   FrameScheduler* GetFrameScheduler();
280   scoped_refptr<base::SingleThreadTaskRunner> GetTaskRunner(TaskType);
281   void ScheduleVisualUpdateUnlessThrottled();
282 
IsNavigationAllowed()283   bool IsNavigationAllowed() const { return navigation_disable_count_ == 0; }
284 
285   // destination_url is only used when a navigation is blocked due to
286   // framebusting defenses, in order to give the option of restarting the
287   // navigation at a later time.
288   bool CanNavigate(const Frame&, const KURL& destination_url = KURL());
289 
290   BrowserInterfaceBrokerProxy& GetBrowserInterfaceBroker();
291 
GetInterfaceRegistry()292   InterfaceRegistry* GetInterfaceRegistry() { return interface_registry_; }
293 
294   // Returns an AssociatedInterfaceProvider the frame can use to request
295   // navigation-associated interfaces from the browser. Messages transmitted
296   // over such interfaces will be dispatched in FIFO order with respect to each
297   // other and messages implementing navigation.
298   //
299   // Carefully consider whether an interface needs to be navigation-associated
300   // before introducing new navigation-associated interfaces.
301   //
302   // Navigation-associated interfaces are currently implemented as
303   // channel-associated interfaces. See
304   // https://chromium.googlesource.com/chromium/src/+/master/docs/mojo_ipc_conversion.md#Channel_Associated-Interfaces
305   AssociatedInterfaceProvider* GetRemoteNavigationAssociatedInterfaces();
306 
307   LocalFrameClient* Client() const;
308 
309   // Returns the widget for this frame, or from the nearest ancestor which is a
310   // local root. It is never null for frames in ordinary Pages (which means the
311   // Page is inside a WebView), except very early in initialization. For frames
312   // in a non-ordinary Page (without a WebView, such as in unit tests, popups,
313   // devtools), it will always be null.
314   FrameWidget* GetWidgetForLocalRoot();
315 
316   WebContentSettingsClient* GetContentSettingsClient();
317 
318   PluginData* GetPluginData() const;
319 
GetPerformanceMonitor()320   PerformanceMonitor* GetPerformanceMonitor() { return performance_monitor_; }
GetIdlenessDetector()321   IdlenessDetector* GetIdlenessDetector() { return idleness_detector_; }
GetAdTracker()322   AdTracker* GetAdTracker() { return ad_tracker_; }
323   void SetAdTrackerForTesting(AdTracker* ad_tracker);
324 
325   enum class LazyLoadImageSetting {
326     kDisabled,
327     kEnabledExplicit,
328     kEnabledAutomatic
329   };
330   // Returns the enabled state of lazyloading of images.
331   LazyLoadImageSetting GetLazyLoadImageSetting() const;
332 
333   // Returns true if parser-blocking script should be force-deferred to execute
334   // after parsing completes for this frame.
335   bool ShouldForceDeferScript() const;
336 
337   // The returned value is a off-heap raw-ptr and should not be stored.
338   WebURLLoaderFactory* GetURLLoaderFactory();
339 
IsInert()340   bool IsInert() const { return is_inert_; }
341 
342   // If the frame hosts a PluginDocument, this method returns the
343   // WebPluginContainerImpl that hosts the plugin. If the provided node is a
344   // plugin, then it returns its WebPluginContainerImpl. Otherwise, uses the
345   // currently focused element (if any).
346   // TODO(slangley): Refactor this method to extract the logic of looking up
347   // focused element or passed node into explicit methods.
348   WebPluginContainerImpl* GetWebPluginContainer(Node* = nullptr) const;
349 
350   // Called on a view for a LocalFrame with a RemoteFrame parent. This makes
351   // viewport intersection and occlusion/obscuration available that accounts for
352   // remote ancestor frames and their respective scroll positions, clips, etc.
353   void SetViewportIntersectionFromParent(const ViewportIntersectionState&);
354 
355   IntSize GetMainFrameViewportSize() const override;
356   IntPoint GetMainFrameScrollOffset() const override;
357 
358   // See viewport_intersection_state.h for more info on these methods.
RemoteViewportOffset()359   gfx::Point RemoteViewportOffset() const {
360     return intersection_state_.viewport_offset;
361   }
RemoteViewportIntersection()362   IntRect RemoteViewportIntersection() const {
363     return intersection_state_.viewport_intersection;
364   }
RemoteMainFrameDocumentIntersection()365   IntRect RemoteMainFrameDocumentIntersection() const {
366     return intersection_state_.main_frame_document_intersection;
367   }
368 
CanSkipStickyFrameTracking()369   bool CanSkipStickyFrameTracking() const {
370     return intersection_state_.can_skip_sticky_frame_tracking;
371   }
372 
373   FrameOcclusionState GetOcclusionState() const;
374 
375   bool NeedsOcclusionTracking() const;
376 
377   // Replaces the initial empty document with a Document suitable for
378   // |mime_type| and populated with the contents of |data|. Only intended for
379   // use in internal-implementation LocalFrames that aren't in the frame tree.
380   void ForceSynchronousDocumentInstall(const AtomicString& mime_type,
381                                        scoped_refptr<SharedBuffer> data);
382 
should_send_resource_timing_info_to_parent()383   bool should_send_resource_timing_info_to_parent() const {
384     return should_send_resource_timing_info_to_parent_;
385   }
SetShouldSendResourceTimingInfoToParent(bool value)386   void SetShouldSendResourceTimingInfoToParent(bool value) {
387     should_send_resource_timing_info_to_parent_ = value;
388   }
389 
390   // TODO(https://crbug.com/578349): provisional frames are a hack that should
391   // be removed.
392   bool IsProvisional() const;
393 
394   // Called in the constructor if AdTracker heuristics have determined that this
395   // frame is an ad; LocalFrames created on behalf of OOPIF aren't set until
396   // just before commit (ReadyToCommitNavigation time) by the embedder.
397   void SetIsAdSubframe(blink::mojom::AdFrameType ad_frame_type);
398 
399   // Updates the frame color overlay to match the highlight ad setting.
400   void UpdateAdHighlight();
401 
402   // Binds |receiver| and prevents resource loading until either the frame is
403   // navigated or the receiver pipe is closed.
404   void PauseSubresourceLoading(
405       mojo::PendingReceiver<blink::mojom::blink::PauseSubresourceLoadingHandle>
406           receiver);
407 
408   void ResumeSubresourceLoading();
409 
410   void AnimateSnapFling(base::TimeTicks monotonic_time);
411 
GetClientHintsPreferences()412   ClientHintsPreferences& GetClientHintsPreferences() {
413     return client_hints_preferences_;
414   }
415 
416   SmoothScrollSequencer& GetSmoothScrollSequencer();
417 
418   const mojo::Remote<mojom::blink::ReportingServiceProxy>& GetReportingService()
419       const;
420 
421   // Returns the frame host ptr. The interface returned is backed by an
422   // associated interface with the legacy Chrome IPC channel.
423   mojom::blink::LocalFrameHost& GetLocalFrameHostRemote();
424 
425   // Overlays a color on top of this LocalFrameView if it is associated with
426   // the main frame. Should not have multiple consumers.
427   void SetMainFrameColorOverlay(SkColor color);
428 
429   // Overlays a color on top of this LocalFrameView if it is associated with
430   // a subframe. Should not have multiple consumers.
431   void SetSubframeColorOverlay(SkColor color);
432   void UpdateFrameColorOverlayPrePaint();
433 
434   // For CompositeAfterPaint.
435   void PaintFrameColorOverlay(GraphicsContext&);
436 
437   // To be called from OomInterventionImpl.
438   void ForciblyPurgeV8Memory();
439 
440   void SetLifecycleState(mojom::FrameLifecycleState state);
441 
442   void WasHidden();
443   void WasShown();
444 
445   // Whether the frame clips its content to the frame's size.
446   bool ClipsContent() const;
447 
448   // For a navigation initiated from this LocalFrame with user gesture, record
449   // the UseCounter AdClickNavigation if this frame is an adframe.
450   //
451   // TODO(crbug.com/939370): Currently this is called in a couple of sites,
452   // which is fragile and prone to break. If we have the ad status in
453   // RemoteFrame, we could call it at FrameLoader::StartNavigation where all
454   // navigations go through.
455   void MaybeLogAdClickNavigation();
456 
457   // Triggers a use counter if a feature, which is currently available in all
458   // frames, would be blocked by the introduction of feature policy. This takes
459   // two counters (which may be the same). It triggers |blockedCrossOrigin| if
460   // the frame is cross-origin relative to the top-level document, and triggers
461   // |blockedSameOrigin| if it is same-origin with the top level, but is
462   // embedded in any way through a cross-origin frame. (A->B->A embedding)
463   void CountUseIfFeatureWouldBeBlockedByFeaturePolicy(
464       mojom::WebFeature blocked_cross_origin,
465       mojom::WebFeature blocked_same_origin);
466 
467   void FinishedLoading(FrameLoader::NavigationFinishState);
468 
469   void UpdateFaviconURL();
470 
471   using IsCapturingMediaCallback = base::RepeatingCallback<bool()>;
472   void SetIsCapturingMediaCallback(IsCapturingMediaCallback callback);
473   bool IsCapturingMedia() const;
474 
475   void DidChangeVisibleToHitTesting() override;
476 
477   WebPrescientNetworking* PrescientNetworking();
478   void SetPrescientNetworkingForTesting(
479       std::unique_ptr<WebPrescientNetworking> prescient_networking);
480 
481   void SetEmbeddingToken(const base::UnguessableToken& embedding_token);
482   const base::Optional<base::UnguessableToken>& GetEmbeddingToken() const;
483 
484   void CopyImageAtViewportPoint(const IntPoint& viewport_point);
485   void MediaPlayerActionAtViewportPoint(
486       const IntPoint& viewport_position,
487       const blink::mojom::blink::MediaPlayerActionType type,
488       bool enable);
489 
490   // Handle the request as a download. If the request is for a blob: URL,
491   // a BlobURLToken should be provided as |blob_url_token| to ensure the
492   // correct blob gets downloaded.
493   void DownloadURL(
494       const ResourceRequest& request,
495       network::mojom::blink::RedirectMode cross_origin_redirect_behavior);
496   void DownloadURL(
497       const ResourceRequest& request,
498       network::mojom::blink::RedirectMode cross_origin_redirect_behavior,
499       mojo::ScopedMessagePipeHandle blob_url_token);
500 
501   // blink::mojom::LocalFrame overrides:
502   void GetTextSurroundingSelection(
503       uint32_t max_length,
504       GetTextSurroundingSelectionCallback callback) final;
505   void SendInterventionReport(const String& id, const String& message) final;
506   void SetFrameOwnerProperties(
507       mojom::blink::FrameOwnerPropertiesPtr properties) final;
508   void NotifyUserActivation() final;
509   void AddMessageToConsole(mojom::blink::ConsoleMessageLevel level,
510                            const WTF::String& message,
511                            bool discard_duplicates) final;
512   void AddInspectorIssue(mojom::blink::InspectorIssueInfoPtr) final;
513   void Collapse(bool collapsed) final;
514   void EnableViewSourceMode() final;
515   void Focus() final;
516   void ClearFocusedElement() final;
517   void GetResourceSnapshotForWebBundle(
518       mojo::PendingReceiver<
519           data_decoder::mojom::blink::ResourceSnapshotForWebBundle> receiver)
520       final;
521   void CopyImageAt(const gfx::Point& window_point) final;
522   void SaveImageAt(const gfx::Point& window_point) final;
523   void ReportBlinkFeatureUsage(const Vector<mojom::blink::WebFeature>&) final;
524   void RenderFallbackContent() final;
525   void BeforeUnload(bool is_reload, BeforeUnloadCallback callback) final;
526   void MediaPlayerActionAt(
527       const gfx::Point& window_point,
528       blink::mojom::blink::MediaPlayerActionPtr action) final;
529   void AdvanceFocusInForm(mojom::blink::FocusType focus_type) final;
530   void ReportContentSecurityPolicyViolation(
531       network::mojom::blink::CSPViolationPtr csp_violation) final;
532   // Updates the snapshotted policy attributes (sandbox flags and feature policy
533   // container policy) in the frame's FrameOwner. This is used when this frame's
534   // parent is in another process and it dynamically updates this frame's
535   // sandbox flags or container policy. The new policy won't take effect until
536   // the next navigation.
537   void DidUpdateFramePolicy(const FramePolicy& frame_policy) final;
538 
539   // blink::mojom::LocalMainFrame overrides:
540   void AnimateDoubleTapZoom(const gfx::Point& point,
541                             const gfx::Rect& rect) override;
542   void SetScaleFactor(float scale) override;
543   void ClosePage(
544       mojom::blink::LocalMainFrame::ClosePageCallback callback) override;
545   // Performs the specified plugin action on the node at the given location.
546   void PluginActionAt(const gfx::Point& location,
547                       mojom::blink::PluginActionType action) override;
548   void SetInitialFocus(bool reverse) override;
549   void EnablePreferredSizeChangedMode() override;
550   void ZoomToFindInPageRect(const gfx::Rect& rect_in_root_frame) override;
551 
552   SystemClipboard* GetSystemClipboard();
553   RawSystemClipboard* GetRawSystemClipboard();
554 
555   // Indicate that this frame was attached as a MainFrame.
556   void WasAttachedAsLocalMainFrame();
557 
558   // Returns the first URL loaded in this frame that is cross-origin to the
559   // parent frame.
560   base::Optional<String> FirstUrlCrossOriginToParent() const;
561 
562  private:
563   friend class FrameNavigationDisabler;
564 
565   // Frame protected overrides:
566   void DetachImpl(FrameDetachType) override;
567 
568   // Intentionally private to prevent redundant checks when the type is
569   // already LocalFrame.
IsLocalFrame()570   bool IsLocalFrame() const override { return true; }
IsRemoteFrame()571   bool IsRemoteFrame() const override { return false; }
572 
EnableNavigation()573   void EnableNavigation() { --navigation_disable_count_; }
DisableNavigation()574   void DisableNavigation() { ++navigation_disable_count_; }
575 
576   void SetIsAdSubframeIfNecessary();
577 
578   void PropagateInertToChildFrames();
579 
580   // Internal implementation for starting or ending printing.
581   // |printing| is true when printing starts, false when printing ends.
582   // |page_size|, |original_page_size|, and |maximum_shrink_ratio| are only
583   // meaningful when we should use printing layout for this frame.
584   void SetPrinting(bool printing,
585                    const FloatSize& page_size,
586                    const FloatSize& original_page_size,
587                    float maximum_shrink_ratio);
588 
589   // FrameScheduler::Delegate overrides:
590   ukm::UkmRecorder* GetUkmRecorder() override;
591   ukm::SourceId GetUkmSourceId() override;
592   void UpdateTaskTime(base::TimeDelta time) override;
593   void UpdateActiveSchedulerTrackedFeatures(uint64_t features_mask) override;
594   const base::UnguessableToken& GetAgentClusterId() const override;
595 
596   // Activates the user activation states of this frame and all its ancestors.
597   void NotifyUserActivation(bool need_browser_verification);
598 
599   // Consumes and returns the transient user activation state this frame, after
600   // updating all other frames in the frame tree.
601   bool ConsumeTransientUserActivation(UserActivationUpdateSource update_source);
602 
603   void SetFrameColorOverlay(SkColor color);
604 
605   void DidFreeze();
606   void DidResume();
607   void PauseContext();
608   void UnpauseContext();
609 
610   void EvictFromBackForwardCache();
611 
612   HitTestResult HitTestResultForVisualViewportPos(
613       const IntPoint& pos_in_viewport);
614 
615   bool ShouldThrottleDownload();
616 
617   static void BindToReceiver(
618       blink::LocalFrame* frame,
619       mojo::PendingAssociatedReceiver<mojom::blink::LocalFrame> receiver);
620   static void BindToMainFrameReceiver(
621       blink::LocalFrame* frame,
622       mojo::PendingAssociatedReceiver<mojom::blink::LocalMainFrame> receiver);
623 
624   std::unique_ptr<FrameScheduler> frame_scheduler_;
625 
626   // Holds all PauseSubresourceLoadingHandles allowing either |this| to delete
627   // them explicitly or the pipe closing to delete them.
628   mojo::UniqueReceiverSet<blink::mojom::blink::PauseSubresourceLoadingHandle>
629       pause_handle_receivers_;
630 
631   mutable FrameLoader loader_;
632 
633   // Cleared by LocalFrame::detach(), so as to keep the observable lifespan
634   // of LocalFrame::view().
635   Member<LocalFrameView> view_;
636   // Usually 0. Non-null if this is the top frame of PagePopup.
637   Member<Element> page_popup_owner_;
638 
639   const Member<ScriptController> script_controller_;
640   const Member<Editor> editor_;
641   const Member<SpellChecker> spell_checker_;
642   const Member<FrameSelection> selection_;
643   const Member<EventHandler> event_handler_;
644   const Member<FrameConsole> console_;
645   const Member<InputMethodController> input_method_controller_;
646   const Member<TextSuggestionController> text_suggestion_controller_;
647 
648   int navigation_disable_count_;
649   // TODO(dcheng): In theory, this could be replaced by checking the
650   // FrameLoaderStateMachine if a real load has committed. Unfortunately, the
651   // internal state tracked there is incorrect today. See
652   // https://crbug.com/778318.
653   bool should_send_resource_timing_info_to_parent_ = true;
654 
655   float page_zoom_factor_;
656   float text_zoom_factor_;
657 
658   bool in_view_source_mode_;
659 
660   Member<CoreProbeSink> probe_sink_;
661   scoped_refptr<InspectorTaskRunner> inspector_task_runner_;
662   Member<PerformanceMonitor> performance_monitor_;
663   Member<AdTracker> ad_tracker_;
664   Member<IdlenessDetector> idleness_detector_;
665   Member<InspectorTraceEvents> inspector_trace_events_;
666   // SmoothScrollSequencer is only populated for local roots; all local frames
667   // use the instance owned by their local root.
668   Member<SmoothScrollSequencer> smooth_scroll_sequencer_;
669   Member<ContentCaptureManager> content_capture_manager_;
670 
671   InterfaceRegistry* const interface_registry_;
672   // This is declared mutable so that the service endpoint can be cached by
673   // const methods.
674   mutable mojo::Remote<mojom::blink::ReportingServiceProxy> reporting_service_;
675 
676   ViewportIntersectionState intersection_state_;
677 
678   // Per-frame URLLoader factory.
679   std::unique_ptr<WebURLLoaderFactory> url_loader_factory_;
680 
681   ClientHintsPreferences client_hints_preferences_;
682 
683   // The value of |is_save_data_enabled_| is read once per frame from
684   // NetworkStateNotifier, which is guarded by a mutex lock, and cached locally
685   // here for performance.
686   // TODO(sclittle): This field doesn't really belong here - we should find some
687   // way to make the state of NetworkStateNotifier accessible without needing to
688   // acquire a mutex, such as by adding thread-local objects to hold the network
689   // state that get updated whenever the network state changes. That way, this
690   // field would be no longer necessary.
691   const bool is_save_data_enabled_;
692 
693   IsCapturingMediaCallback is_capturing_media_callback_;
694 
695   std::unique_ptr<FrameOverlay> frame_color_overlay_;
696 
697   base::Optional<base::UnguessableToken> embedding_token_;
698 
699   mojom::FrameLifecycleState lifecycle_state_;
700   base::Optional<mojom::FrameLifecycleState> pending_lifecycle_state_;
701 
702   std::unique_ptr<WebPrescientNetworking> prescient_networking_;
703 
704   mojo::AssociatedRemote<mojom::blink::LocalFrameHost> local_frame_host_remote_;
705   mojo::AssociatedReceiver<mojom::blink::LocalFrame> receiver_{this};
706   mojo::AssociatedReceiver<mojom::blink::LocalMainFrame> main_frame_receiver_{
707       this};
708 
709   // Variable to control burst of download requests.
710   int num_burst_download_requests_ = 0;
711   base::TimeTicks burst_download_start_time_;
712 
713   // Access to the global sanitized system clipboard.
714   Member<SystemClipboard> system_clipboard_;
715   // Access to the global raw/unsanitized system clipboard
716   Member<RawSystemClipboard> raw_system_clipboard_;
717 
718   // Stores the first URL that was loaded in this frame that is cross-origin
719   // to the parent frame. For this URL we know that the parent origin provided
720   // it by either setting the |src| attribute or by navigating the iframe.
721   // Thus we can safely reveal it to the parent origin in Web APIs.
722   // TODO(ulan): Move this to the browser process once performance.measureMemory
723   // starts using Performance Manager to support cross-site iframes.
724   base::Optional<String> first_url_cross_origin_to_parent_;
725 };
726 
Loader()727 inline FrameLoader& LocalFrame::Loader() const {
728   return loader_;
729 }
730 
View()731 inline LocalFrameView* LocalFrame::View() const {
732   return view_.Get();
733 }
734 
GetScriptController()735 inline ScriptController& LocalFrame::GetScriptController() const {
736   return *script_controller_;
737 }
738 
Selection()739 inline FrameSelection& LocalFrame::Selection() const {
740   return *selection_;
741 }
742 
GetEditor()743 inline Editor& LocalFrame::GetEditor() const {
744   return *editor_;
745 }
746 
GetSpellChecker()747 inline SpellChecker& LocalFrame::GetSpellChecker() const {
748   return *spell_checker_;
749 }
750 
Console()751 inline FrameConsole& LocalFrame::Console() const {
752   return *console_;
753 }
754 
GetInputMethodController()755 inline InputMethodController& LocalFrame::GetInputMethodController() const {
756   return *input_method_controller_;
757 }
758 
GetTextSuggestionController()759 inline TextSuggestionController& LocalFrame::GetTextSuggestionController()
760     const {
761   return *text_suggestion_controller_;
762 }
763 
InViewSourceMode()764 inline bool LocalFrame::InViewSourceMode() const {
765   return in_view_source_mode_;
766 }
767 
SetInViewSourceMode(bool mode)768 inline void LocalFrame::SetInViewSourceMode(bool mode) {
769   in_view_source_mode_ = mode;
770 }
771 
GetEventHandler()772 inline EventHandler& LocalFrame::GetEventHandler() const {
773   DCHECK(event_handler_);
774   return *event_handler_;
775 }
776 
777 template <>
778 struct DowncastTraits<LocalFrame> {
779   static bool AllowFrom(const Frame& frame) { return frame.IsLocalFrame(); }
780 };
781 
782 DECLARE_WEAK_IDENTIFIER_MAP(LocalFrame);
783 
784 class FrameNavigationDisabler {
785   STACK_ALLOCATED();
786 
787  public:
788   explicit FrameNavigationDisabler(LocalFrame&);
789   ~FrameNavigationDisabler();
790 
791  private:
792   LocalFrame* frame_;
793 
794   DISALLOW_COPY_AND_ASSIGN(FrameNavigationDisabler);
795 };
796 
797 // A helper class for attributing cost inside a scope to a LocalFrame, with
798 // output written to the trace log. The class is irrelevant to the core logic
799 // of LocalFrame.  Sample usage:
800 //
801 // void foo(LocalFrame* frame)
802 // {
803 //     ScopedFrameBlamer frameBlamer(frame);
804 //     TRACE_EVENT0("blink", "foo");
805 //     // Do some real work...
806 // }
807 //
808 // In Trace Viewer, we can find the cost of slice |foo| attributed to |frame|.
809 // Design doc:
810 // https://docs.google.com/document/d/15BB-suCb9j-nFt55yCFJBJCGzLg2qUm3WaSOPb8APtI/edit?usp=sharing
811 //
812 // This class is used in performance-sensitive code (like V8 entry), so care
813 // should be taken to ensure that it has an efficient fast path (for the common
814 // case where we are not tracking this).
815 class ScopedFrameBlamer {
816   STACK_ALLOCATED();
817 
818  public:
819   explicit ScopedFrameBlamer(LocalFrame*);
820   ~ScopedFrameBlamer() {
821     if (UNLIKELY(frame_))
822       LeaveContext();
823   }
824 
825  private:
826   void LeaveContext();
827 
828   LocalFrame* frame_;
829 
830   DISALLOW_COPY_AND_ASSIGN(ScopedFrameBlamer);
831 };
832 
833 }  // namespace blink
834 
835 #endif  // THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_LOCAL_FRAME_H_
836