2 * Copyright (C) 2014 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
14 * * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 #include "third_party/blink/renderer/core/frame/web_frame_widget_impl.h"
36 #include "base/auto_reset.h"
37 #include "base/debug/crash_logging.h"
38 #include "base/debug/dump_without_crashing.h"
39 #include "base/functional/callback_helpers.h"
40 #include "base/functional/function_ref.h"
41 #include "base/metrics/histogram_macros.h"
42 #include "base/numerics/safe_conversions.h"
43 #include "base/task/single_thread_task_runner.h"
44 #include "base/time/time.h"
45 #include "build/build_config.h"
46 #include "cc/animation/animation_host.h"
47 #include "cc/base/features.h"
48 #include "cc/trees/compositor_commit_data.h"
49 #include "cc/trees/layer_tree_host.h"
50 #include "cc/trees/swap_promise.h"
51 #include "cc/trees/ukm_manager.h"
52 #include "third_party/blink/public/common/features.h"
53 #include "third_party/blink/public/mojom/frame/intrinsic_sizing_info.mojom-blink.h"
54 #include "third_party/blink/public/mojom/input/input_handler.mojom-blink.h"
55 #include "third_party/blink/public/mojom/input/touch_event.mojom-blink.h"
56 #include "third_party/blink/public/platform/platform.h"
57 #include "third_party/blink/public/web/web_autofill_client.h"
58 #include "third_party/blink/public/web/web_local_frame.h"
59 #include "third_party/blink/public/web/web_local_frame_client.h"
60 #include "third_party/blink/public/web/web_non_composited_widget_client.h"
61 #include "third_party/blink/public/web/web_performance_metrics_for_reporting.h"
62 #include "third_party/blink/public/web/web_plugin.h"
63 #include "third_party/blink/public/web/web_settings.h"
64 #include "third_party/blink/public/web/web_view_client.h"
65 #include "third_party/blink/renderer/core/content_capture/content_capture_manager.h"
66 #include "third_party/blink/renderer/core/core_initializer.h"
67 #include "third_party/blink/renderer/core/dom/element.h"
68 #include "third_party/blink/renderer/core/dom/focus_params.h"
69 #include "third_party/blink/renderer/core/dom/layout_tree_builder_traversal.h"
70 #include "third_party/blink/renderer/core/editing/editing_utilities.h"
71 #include "third_party/blink/renderer/core/editing/ephemeral_range.h"
72 #include "third_party/blink/renderer/core/editing/frame_selection.h"
73 #include "third_party/blink/renderer/core/editing/ime/edit_context.h"
74 #include "third_party/blink/renderer/core/editing/ime/input_method_controller.h"
75 #include "third_party/blink/renderer/core/editing/ime/stylus_writing_gesture.h"
76 #include "third_party/blink/renderer/core/editing/selection_template.h"
77 #include "third_party/blink/renderer/core/events/current_input_event.h"
78 #include "third_party/blink/renderer/core/events/pointer_event_factory.h"
79 #include "third_party/blink/renderer/core/events/web_input_event_conversion.h"
80 #include "third_party/blink/renderer/core/events/wheel_event.h"
81 #include "third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.h"
82 #include "third_party/blink/renderer/core/exported/web_plugin_container_impl.h"
83 #include "third_party/blink/renderer/core/exported/web_settings_impl.h"
84 #include "third_party/blink/renderer/core/exported/web_view_impl.h"
85 #include "third_party/blink/renderer/core/frame/local_dom_window.h"
86 #include "third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.h"
87 #include "third_party/blink/renderer/core/frame/local_frame_view.h"
88 #include "third_party/blink/renderer/core/frame/remote_frame_client.h"
89 #include "third_party/blink/renderer/core/frame/screen.h"
90 #include "third_party/blink/renderer/core/frame/screen_metrics_emulator.h"
91 #include "third_party/blink/renderer/core/frame/settings.h"
92 #include "third_party/blink/renderer/core/frame/visual_viewport.h"
93 #include "third_party/blink/renderer/core/frame/web_feature.h"
94 #include "third_party/blink/renderer/core/frame/web_local_frame_impl.h"
95 #include "third_party/blink/renderer/core/html/fenced_frame/document_fenced_frames.h"
96 #include "third_party/blink/renderer/core/html/fenced_frame/html_fenced_frame_element.h"
97 #include "third_party/blink/renderer/core/html/forms/text_control_element.h"
98 #include "third_party/blink/renderer/core/html/html_frame_owner_element.h"
99 #include "third_party/blink/renderer/core/html/html_plugin_element.h"
100 #include "third_party/blink/renderer/core/html/portal/document_portals.h"
101 #include "third_party/blink/renderer/core/html/portal/portal_contents.h"
102 #include "third_party/blink/renderer/core/input/context_menu_allowed_scope.h"
103 #include "third_party/blink/renderer/core/input/event_handler.h"
104 #include "third_party/blink/renderer/core/input/touch_action_util.h"
105 #include "third_party/blink/renderer/core/layout/hit_test_location.h"
106 #include "third_party/blink/renderer/core/layout/hit_test_request.h"
107 #include "third_party/blink/renderer/core/layout/layout_box.h"
108 #include "third_party/blink/renderer/core/layout/layout_embedded_content.h"
109 #include "third_party/blink/renderer/core/layout/layout_object.h"
110 #include "third_party/blink/renderer/core/layout/layout_shift_tracker.h"
111 #include "third_party/blink/renderer/core/layout/layout_text.h"
112 #include "third_party/blink/renderer/core/loader/document_loader.h"
113 #include "third_party/blink/renderer/core/loader/interactive_detector.h"
114 #include "third_party/blink/renderer/core/page/context_menu_controller.h"
115 #include "third_party/blink/renderer/core/page/drag_actions.h"
116 #include "third_party/blink/renderer/core/page/drag_data.h"
117 #include "third_party/blink/renderer/core/page/focus_controller.h"
118 #include "third_party/blink/renderer/core/page/link_highlight.h"
119 #include "third_party/blink/renderer/core/page/page.h"
120 #include "third_party/blink/renderer/core/page/page_animator.h"
121 #include "third_party/blink/renderer/core/page/pointer_lock_controller.h"
122 #include "third_party/blink/renderer/core/page/scrolling/fragment_anchor.h"
123 #include "third_party/blink/renderer/core/page/validation_message_client.h"
124 #include "third_party/blink/renderer/core/page/viewport_description.h"
125 #include "third_party/blink/renderer/core/paint/timing/first_meaningful_paint_detector.h"
126 #include "third_party/blink/renderer/core/paint/timing/paint_timing_detector.h"
127 #include "third_party/blink/renderer/core/probe/core_probes.h"
128 #include "third_party/blink/renderer/core/scroll/scroll_into_view_util.h"
129 #include "third_party/blink/renderer/core/scroll/scrollbar_theme.h"
130 #include "third_party/blink/renderer/core/timing/dom_window_performance.h"
131 #include "third_party/blink/renderer/core/timing/window_performance.h"
132 #include "third_party/blink/renderer/core/view_transition/view_transition.h"
133 #include "third_party/blink/renderer/core/view_transition/view_transition_utils.h"
134 #include "third_party/blink/renderer/platform/graphics/animation_worklet_mutator_dispatcher_impl.h"
135 #include "third_party/blink/renderer/platform/graphics/compositor_mutator_client.h"
136 #include "third_party/blink/renderer/platform/graphics/paint_worklet_paint_dispatcher.h"
137 #include "third_party/blink/renderer/platform/heap/cross_thread_handle.h"
138 #include "third_party/blink/renderer/platform/heap/persistent.h"
139 #include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
140 #include "third_party/blink/renderer/platform/keyboard_codes.h"
141 #include "third_party/blink/renderer/platform/runtime_enabled_features.h"
142 #include "third_party/blink/renderer/platform/scheduler/public/non_main_thread.h"
143 #include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
144 #include "third_party/blink/renderer/platform/widget/input/main_thread_event_queue.h"
145 #include "third_party/blink/renderer/platform/widget/input/widget_input_handler_manager.h"
146 #include "third_party/blink/renderer/platform/widget/widget_base.h"
147 #include "third_party/blink/renderer/platform/wtf/cross_thread_copier_base.h"
148 #include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
149 #include "third_party/blink/renderer/platform/wtf/functional.h"
150 #include "ui/base/dragdrop/mojom/drag_drop_types.mojom-blink.h"
151 #include "ui/base/ui_base_types.h"
152 #include "ui/gfx/geometry/point_conversions.h"
154 #if BUILDFLAG(IS_MAC)
155 #include "third_party/blink/renderer/core/editing/substring_util.h"
156 #include "third_party/blink/renderer/platform/fonts/mac/attributed_string_type_converter.h"
157 #include "ui/base/mojom/attributed_string.mojom-blink.h"
158 #include "ui/gfx/geometry/point.h"
161 #if BUILDFLAG(IS_EFL)
162 #include "skia/ext/image_operations.h"
163 #include "third_party/blink/renderer/core/html/forms/html_input_element.h"
164 #include "third_party/blink/renderer/core/input_type_names.h"
170 struct CrossThreadCopier<blink::WebFrameWidgetImpl::PromiseCallbacks>
171 : public CrossThreadCopierByValuePassThrough<
172 blink::WebFrameWidgetImpl::PromiseCallbacks> {
173 STATIC_ONLY(CrossThreadCopier);
182 using ::ui::mojom::blink::DragOperation;
184 void ForEachLocalFrameControlledByWidget(
186 base::FunctionRef<void(WebLocalFrameImpl*)> callback) {
187 callback(WebLocalFrameImpl::FromFrame(frame));
188 for (Frame* child = frame->FirstChild(); child;
189 child = child->NextSibling()) {
190 if (auto* local_child = DynamicTo<LocalFrame>(child)) {
191 ForEachLocalFrameControlledByWidget(local_child, callback);
196 // Iterate the remote children that will be controlled by the widget. Skip over
197 // any RemoteFrames have have another LocalFrame root as their parent.
198 void ForEachRemoteFrameChildrenControlledByWidget(
200 base::FunctionRef<void(RemoteFrame*)> callback) {
201 for (Frame* child = frame->Tree().FirstChild(); child;
202 child = child->Tree().NextSibling()) {
203 if (auto* remote_frame = DynamicTo<RemoteFrame>(child)) {
204 callback(remote_frame);
205 ForEachRemoteFrameChildrenControlledByWidget(remote_frame, callback);
206 } else if (auto* local_frame = DynamicTo<LocalFrame>(child)) {
207 // If iteration arrives at a local root then don't descend as it will be
208 // controlled by another widget.
209 if (!local_frame->IsLocalRoot()) {
210 ForEachRemoteFrameChildrenControlledByWidget(local_frame, callback);
215 if (auto* local_frame = DynamicTo<LocalFrame>(frame)) {
216 if (Document* document = local_frame->GetDocument()) {
217 // Iterate on any portals owned by a local frame.
218 if (auto* portals = DocumentPortals::Get(*document)) {
219 for (PortalContents* portal : portals->GetPortals()) {
220 if (RemoteFrame* remote_frame = portal->GetFrame())
221 callback(remote_frame);
224 // Iterate on any fenced frames owned by a local frame.
225 if (auto* fenced_frames = DocumentFencedFrames::Get(*document)) {
226 for (HTMLFencedFrameElement* fenced_frame :
227 fenced_frames->GetFencedFrames()) {
228 callback(To<RemoteFrame>(fenced_frame->ContentFrame()));
235 viz::FrameSinkId GetRemoteFrameSinkId(const HitTestResult& result) {
236 Node* node = result.InnerNode();
237 auto* frame_owner = DynamicTo<HTMLFrameOwnerElement>(node);
238 if (!frame_owner || !frame_owner->ContentFrame() ||
239 !frame_owner->ContentFrame()->IsRemoteFrame())
240 return viz::FrameSinkId();
242 RemoteFrame* remote_frame = To<RemoteFrame>(frame_owner->ContentFrame());
243 if (remote_frame->IsIgnoredForHitTest())
244 return viz::FrameSinkId();
245 LayoutObject* object = node->GetLayoutObject();
247 if (!object->IsBox())
248 return viz::FrameSinkId();
250 PhysicalOffset local_point(ToRoundedPoint(result.LocalPoint()));
251 if (!To<LayoutBox>(object)->ComputedCSSContentBoxRect().Contains(local_point))
252 return viz::FrameSinkId();
254 return remote_frame->GetFrameSinkId();
257 bool IsElementNotNullAndEditable(Element* element) {
261 if (IsEditable(*element))
264 auto* text_control = ToTextControlOrNull(element);
265 if (text_control && !text_control->IsDisabledOrReadOnly())
268 if (EqualIgnoringASCIICase(element->FastGetAttribute(html_names::kRoleAttr),
276 bool& InputDisabledPerBrowsingContextGroup(
277 const base::UnguessableToken& token) {
278 using BrowsingContextGroupMap = std::map<base::UnguessableToken, bool>;
279 DEFINE_STATIC_LOCAL(BrowsingContextGroupMap, values, ());
280 return values[token];
285 // WebFrameWidget ------------------------------------------------------------
287 bool WebFrameWidgetImpl::ignore_input_events_ = false;
290 void WebFrameWidgetImpl::SetIgnoreInputEvents(
291 const base::UnguessableToken& browsing_context_group_token,
293 if (base::FeatureList::IsEnabled(
294 features::kPausePagesPerBrowsingContextGroup)) {
295 CHECK_NE(InputDisabledPerBrowsingContextGroup(browsing_context_group_token),
297 InputDisabledPerBrowsingContextGroup(browsing_context_group_token) = value;
299 CHECK_NE(ignore_input_events_, value);
300 ignore_input_events_ = value;
305 bool WebFrameWidgetImpl::IgnoreInputEvents(
306 const base::UnguessableToken& browsing_context_group_token) {
307 if (base::FeatureList::IsEnabled(
308 features::kPausePagesPerBrowsingContextGroup)) {
309 return InputDisabledPerBrowsingContextGroup(browsing_context_group_token);
311 return ignore_input_events_;
315 WebFrameWidgetImpl::WebFrameWidgetImpl(
316 base::PassKey<WebLocalFrame>,
317 CrossVariantMojoAssociatedRemote<mojom::blink::FrameWidgetHostInterfaceBase>
319 CrossVariantMojoAssociatedReceiver<mojom::blink::FrameWidgetInterfaceBase>
321 CrossVariantMojoAssociatedRemote<mojom::blink::WidgetHostInterfaceBase>
323 CrossVariantMojoAssociatedReceiver<mojom::blink::WidgetInterfaceBase>
325 scoped_refptr<base::SingleThreadTaskRunner> task_runner,
326 const viz::FrameSinkId& frame_sink_id,
328 bool never_composited,
329 bool is_for_child_local_root,
330 bool is_for_nested_main_frame,
331 bool is_for_scalable_page)
332 : widget_base_(std::make_unique<WidgetBase>(
333 /*widget_base_client=*/this,
334 std::move(widget_host),
339 /*is_embedded=*/is_for_child_local_root || is_for_nested_main_frame,
340 is_for_scalable_page)),
341 frame_sink_id_(frame_sink_id),
342 is_for_child_local_root_(is_for_child_local_root),
343 is_for_scalable_page_(is_for_scalable_page) {
345 if (is_for_nested_main_frame)
346 main_data().is_for_nested_main_frame = is_for_nested_main_frame;
347 frame_widget_host_.Bind(std::move(frame_widget_host), task_runner);
348 receiver_.Bind(std::move(frame_widget), task_runner);
351 WebFrameWidgetImpl::~WebFrameWidgetImpl() {
352 // Ensure that Close is called and we aren't releasing |widget_base_| in the
354 // TODO(crbug.com/1139104): This CHECK can be changed to a DCHECK once
355 // the issue is solved.
356 CHECK(!widget_base_);
359 void WebFrameWidgetImpl::BindLocalRoot(WebLocalFrame& local_root) {
360 local_root_ = To<WebLocalFrameImpl>(local_root);
361 CHECK(local_root_ && local_root_->GetFrame());
362 if (RuntimeEnabledFeatures::LongAnimationFrameMonitoringEnabled(
363 local_root_->GetFrame()->DomWindow()) &&
365 animation_frame_timing_monitor_ =
366 MakeGarbageCollected<AnimationFrameTimingMonitor>(
367 *this, local_root_->GetFrame()->GetProbeSink());
371 bool WebFrameWidgetImpl::ForTopMostMainFrame() const {
372 return ForMainFrame() && !main_data().is_for_nested_main_frame;
375 void WebFrameWidgetImpl::SetIsNestedMainFrameWidget(bool is_nested) {
376 main_data().is_for_nested_main_frame = is_nested;
379 void WebFrameWidgetImpl::Close() {
380 // TODO(bokan): This seems wrong since the page may have other still-active
381 // frame widgets. See also: https://crbug.com/1344531.
382 GetPage()->WillStopCompositing();
384 if (ForMainFrame()) {
385 // Closing the WebFrameWidgetImpl happens in response to the local main
386 // frame being detached from the Page/WebViewImpl.
387 View()->SetMainFrameViewWidget(nullptr);
390 if (animation_frame_timing_monitor_) {
391 animation_frame_timing_monitor_->Shutdown();
392 animation_frame_timing_monitor_.Clear();
395 mutator_dispatcher_ = nullptr;
396 local_root_ = nullptr;
397 widget_base_->Shutdown();
398 widget_base_.reset();
399 // These WeakPtrs must be invalidated for WidgetInputHandlerManager at the
400 // same time as the WidgetBase is.
401 input_handler_weak_ptr_factory_.InvalidateWeakPtrs();
403 input_target_receiver_.reset();
406 WebLocalFrame* WebFrameWidgetImpl::LocalRoot() const {
407 return local_root_.Get();
410 bool WebFrameWidgetImpl::RequestedMainFramePending() {
411 return View() && View()->does_composite() && LayerTreeHost() &&
412 LayerTreeHost()->RequestedMainFramePending();
415 ukm::UkmRecorder* WebFrameWidgetImpl::MainFrameUkmRecorder() {
417 if (!local_root_->IsOutermostMainFrame()) {
421 if (!local_root_->GetFrame() || !local_root_->GetFrame()->DomWindow()) {
425 return local_root_->GetFrame()->DomWindow()->UkmRecorder();
427 ukm::SourceId WebFrameWidgetImpl::MainFrameUkmSourceId() {
429 if (!local_root_->IsOutermostMainFrame()) {
430 return ukm::kInvalidSourceId;
433 if (!local_root_->GetFrame() || !local_root_->GetFrame()->DomWindow()) {
434 return ukm::kInvalidSourceId;
437 return local_root_->GetFrame()->DomWindow()->UkmSourceID();
440 bool WebFrameWidgetImpl::IsMainFrameFullyLoaded() const {
442 if (!local_root_->IsOutermostMainFrame()) {
446 return local_root_->GetFrame() &&
447 local_root_->GetFrame()->Loader().GetDocumentLoader() &&
448 !local_root_->GetFrame()
456 gfx::Rect WebFrameWidgetImpl::ComputeBlockBound(
457 const gfx::Point& point_in_root_frame,
458 bool ignore_clipping) const {
459 HitTestLocation location(local_root_->GetFrameView()->ConvertFromRootFrame(
460 PhysicalOffset(point_in_root_frame)));
461 HitTestRequest::HitTestRequestType hit_type =
462 HitTestRequest::kReadOnly | HitTestRequest::kActive |
463 (ignore_clipping ? HitTestRequest::kIgnoreClipping : 0);
464 HitTestResult result =
465 local_root_->GetFrame()->GetEventHandler().HitTestResultAtLocation(
467 result.SetToShadowHostIfInUAShadowRoot();
469 Node* node = result.InnerNodeOrImageMapImage();
473 // Find the block type node based on the hit node.
474 // FIXME: This wants to walk flat tree with
475 // LayoutTreeBuilderTraversal::parent().
477 (!node->GetLayoutObject() || node->GetLayoutObject()->IsInline()))
478 node = LayoutTreeBuilderTraversal::Parent(*node);
480 // Return the bounding box in the root frame's coordinate space.
482 gfx::Rect absolute_rect =
483 node->GetLayoutObject()->AbsoluteBoundingBoxRect();
484 LocalFrame* frame = node->GetDocument().GetFrame();
485 return frame->View()->ConvertToRootFrame(absolute_rect);
490 void WebFrameWidgetImpl::DragTargetDragEnter(
491 const WebDragData& web_drag_data,
492 const gfx::PointF& point_in_viewport,
493 const gfx::PointF& screen_point,
494 DragOperationsMask operations_allowed,
495 uint32_t key_modifiers,
496 DragTargetDragEnterCallback callback) {
497 auto* target = local_root_->GetFrame()->DocumentAtPoint(
498 PhysicalOffset::FromPointFRound(ViewportToRootFrame(point_in_viewport)));
500 // Any execution context should do the work since no file should ever be
501 // created during drag events.
502 current_drag_data_ = DataObject::Create(
503 target ? target->GetExecutionContext() : nullptr, web_drag_data);
504 operations_allowed_ = operations_allowed;
506 DragTargetDragEnterOrOver(point_in_viewport, screen_point, kDragEnter,
509 std::move(callback).Run(drag_operation_.operation,
510 drag_operation_.document_is_handling_drag);
513 void WebFrameWidgetImpl::DragTargetDragOver(
514 const gfx::PointF& point_in_viewport,
515 const gfx::PointF& screen_point,
516 DragOperationsMask operations_allowed,
517 uint32_t key_modifiers,
518 DragTargetDragOverCallback callback) {
519 operations_allowed_ = operations_allowed;
521 DragTargetDragEnterOrOver(point_in_viewport, screen_point, kDragOver,
524 std::move(callback).Run(drag_operation_.operation,
525 drag_operation_.document_is_handling_drag);
528 void WebFrameWidgetImpl::DragTargetDragLeave(
529 const gfx::PointF& point_in_viewport,
530 const gfx::PointF& screen_point) {
531 base::ScopedClosureRunner runner(
532 WTF::BindOnce(&WebFrameWidgetImpl::CancelDrag, WrapWeakPersistent(this)));
533 if (ShouldIgnoreInputEvents() || !current_drag_data_) {
537 gfx::PointF point_in_root_frame(ViewportToRootFrame(point_in_viewport));
538 DragData drag_data(current_drag_data_.Get(), point_in_root_frame,
539 screen_point, operations_allowed_,
540 /*force_default_action=*/false);
542 GetPage()->GetDragController().DragExited(&drag_data,
543 *local_root_->GetFrame());
545 // FIXME: why is the drag scroll timer not stopped here?
548 void WebFrameWidgetImpl::DragTargetDrop(const WebDragData& web_drag_data,
549 const gfx::PointF& point_in_viewport,
550 const gfx::PointF& screen_point,
551 uint32_t key_modifiers,
552 base::OnceClosure callback) {
553 base::ScopedClosureRunner callback_runner(std::move(callback));
554 base::ScopedClosureRunner runner(
555 WTF::BindOnce(&WebFrameWidgetImpl::CancelDrag, WrapWeakPersistent(this)));
557 if (ShouldIgnoreInputEvents() || !current_drag_data_) {
561 auto* target = local_root_->GetFrame()->DocumentAtPoint(
562 PhysicalOffset::FromPointFRound(ViewportToRootFrame(point_in_viewport)));
564 current_drag_data_ = DataObject::Create(
565 target ? target->GetExecutionContext() : nullptr, web_drag_data);
567 // If this webview transitions from the "drop accepting" state to the "not
568 // accepting" state, then our IPC message reply indicating that may be in-
569 // flight, or else delayed by javascript processing in this webview. If a
570 // drop happens before our IPC reply has reached the browser process, then
571 // the browser forwards the drop to this webview. So only allow a drop to
572 // proceed if our webview drag operation state is not DragOperation::kNone.
574 if (drag_operation_.operation == DragOperation::kNone) {
575 // IPC RACE CONDITION: do not allow this drop.
576 DragTargetDragLeave(point_in_viewport, screen_point);
580 current_drag_data_->SetModifiers(key_modifiers);
581 DragData drag_data(current_drag_data_.Get(),
582 ViewportToRootFrame(point_in_viewport), screen_point,
583 operations_allowed_, web_drag_data.ForceDefaultAction());
584 GetPage()->GetDragController().PerformDrag(&drag_data,
585 *local_root_->GetFrame());
588 void WebFrameWidgetImpl::DragSourceEndedAt(const gfx::PointF& point_in_viewport,
589 const gfx::PointF& screen_point,
590 DragOperation operation,
591 base::OnceClosure callback) {
592 base::ScopedClosureRunner callback_runner(std::move(callback));
593 base::ScopedClosureRunner runner(
594 WTF::BindOnce(&WebFrameWidgetImpl::DragSourceSystemDragEnded,
595 WrapWeakPersistent(this)));
597 if (ShouldIgnoreInputEvents()) {
601 WebMouseEvent fake_mouse_move(
602 WebInputEvent::Type::kMouseMove,
603 GetPage()->GetVisualViewport().ViewportToRootFrame(point_in_viewport),
604 screen_point, WebPointerProperties::Button::kLeft, 0,
605 WebInputEvent::kNoModifiers, base::TimeTicks::Now());
606 fake_mouse_move.SetFrameScale(1);
607 local_root_->GetFrame()->GetEventHandler().DragSourceEndedAt(fake_mouse_move,
611 void WebFrameWidgetImpl::DragSourceSystemDragEnded() {
614 // It's possible for this to be false if the source stopped dragging at a
616 if (!doing_drag_and_drop_) {
619 GetPage()->GetDragController().DragEnded();
620 doing_drag_and_drop_ = false;
623 gfx::Rect WebFrameWidgetImpl::GetAbsoluteCaretBounds() {
624 LocalFrame* local_frame = GetPage()->GetFocusController().FocusedFrame();
626 auto& selection = local_frame->Selection();
627 if (selection.GetSelectionInDOMTree().IsCaret())
628 return selection.AbsoluteCaretBounds();
633 void WebFrameWidgetImpl::OnStartStylusWriting(
634 OnStartStylusWritingCallback callback) {
635 // Focus the stylus writable element for current touch sequence as we have
636 // detected writing has started.
637 LocalFrame* frame = LocalRootImpl()->GetFrame();
639 std::move(callback).Run(absl::nullopt, absl::nullopt);
643 Element* stylus_writable_element =
644 frame->GetEventHandler().CurrentTouchDownElement();
645 if (!stylus_writable_element) {
646 std::move(callback).Run(absl::nullopt, absl::nullopt);
650 if (auto* text_control = EnclosingTextControl(stylus_writable_element)) {
651 text_control->Focus(FocusParams(FocusTrigger::kUserGesture));
652 } else if (auto* html_element =
653 DynamicTo<HTMLElement>(stylus_writable_element)) {
654 html_element->Focus(FocusParams(FocusTrigger::kUserGesture));
656 Element* focused_element = FocusedElement();
657 // Since the element can change after it gets focused, we just verify if
658 // the focused element is editable to continue writing.
659 if (IsElementNotNullAndEditable(focused_element)) {
660 std::move(callback).Run(
661 focused_element->BoundsInWidget(),
662 frame->View()->FrameToViewport(GetAbsoluteCaretBounds()));
666 std::move(callback).Run(absl::nullopt, absl::nullopt);
669 void WebFrameWidgetImpl::HandleStylusWritingGestureAction(
670 mojom::blink::StylusWritingGestureDataPtr gesture_data,
671 HandleStylusWritingGestureActionCallback callback) {
672 LocalFrame* focused_frame = FocusedLocalFrameInWidget();
673 if (!focused_frame) {
674 std::move(callback).Run(mojom::blink::HandwritingGestureResult::kFailed);
677 mojom::blink::HandwritingGestureResult result =
678 StylusWritingGesture::ApplyGesture(focused_frame,
679 std::move(gesture_data));
680 std::move(callback).Run(result);
683 void WebFrameWidgetImpl::SetBackgroundOpaque(bool opaque) {
684 View()->SetBaseBackgroundColorOverrideTransparent(!opaque);
687 void WebFrameWidgetImpl::SetTextDirection(base::i18n::TextDirection direction) {
688 LocalFrame* focusedFrame = FocusedLocalFrameInWidget();
690 focusedFrame->SetTextDirection(direction);
693 void WebFrameWidgetImpl::SetInheritedEffectiveTouchActionForSubFrame(
694 TouchAction touch_action) {
695 DCHECK(ForSubframe());
696 LocalRootImpl()->GetFrame()->SetInheritedEffectiveTouchAction(touch_action);
699 void WebFrameWidgetImpl::UpdateRenderThrottlingStatusForSubFrame(
701 bool subtree_throttled,
702 bool display_locked) {
703 DCHECK(ForSubframe());
704 // TODO(szager,vmpstr): The parent render process currently rolls up
705 // display_locked into the value of subtree throttled here; display_locked
706 // should be maintained as a separate bit and transmitted between render
708 LocalRootImpl()->GetFrameView()->UpdateRenderThrottlingStatus(
709 is_throttled, subtree_throttled, display_locked, /*recurse=*/true);
712 #if BUILDFLAG(IS_MAC)
713 void WebFrameWidgetImpl::GetStringAtPoint(const gfx::Point& point_in_local_root,
714 GetStringAtPointCallback callback) {
715 gfx::Point baseline_point;
716 ui::mojom::blink::AttributedStringPtr attributed_string = nullptr;
717 base::apple::ScopedCFTypeRef<CFAttributedStringRef> string =
718 SubstringUtil::AttributedWordAtPoint(this, point_in_local_root,
721 attributed_string = ui::mojom::blink::AttributedString::From(string.get());
724 std::move(callback).Run(std::move(attributed_string), baseline_point);
728 void WebFrameWidgetImpl::BindWidgetCompositor(
729 mojo::PendingReceiver<mojom::blink::WidgetCompositor> receiver) {
730 widget_base_->BindWidgetCompositor(std::move(receiver));
733 void WebFrameWidgetImpl::BindInputTargetClient(
734 mojo::PendingReceiver<viz::mojom::blink::InputTargetClient> receiver) {
735 DCHECK(!input_target_receiver_.is_bound());
736 input_target_receiver_.Bind(
738 local_root_->GetTaskRunner(TaskType::kInternalInputBlocking));
741 void WebFrameWidgetImpl::FrameSinkIdAt(const gfx::PointF& point,
742 const uint64_t trace_id,
743 FrameSinkIdAtCallback callback) {
744 TRACE_EVENT_WITH_FLOW1("viz,benchmark", "Event.Pipeline",
745 TRACE_ID_GLOBAL(trace_id),
746 TRACE_EVENT_FLAG_FLOW_IN | TRACE_EVENT_FLAG_FLOW_OUT,
747 "step", "FrameSinkIdAt");
749 gfx::PointF local_point;
750 viz::FrameSinkId id = GetFrameSinkIdAtPoint(point, &local_point);
751 std::move(callback).Run(id, local_point);
754 viz::FrameSinkId WebFrameWidgetImpl::GetFrameSinkIdAtPoint(
755 const gfx::PointF& point_in_dips,
756 gfx::PointF* local_point_in_dips) {
757 HitTestResult result =
758 CoreHitTestResultAt(widget_base_->DIPsToBlinkSpace(point_in_dips));
760 Node* result_node = result.InnerNode();
761 *local_point_in_dips = gfx::PointF(point_in_dips);
763 // TODO(crbug.com/797828): When the node is null the caller may
764 // need to do extra checks. Like maybe update the layout and then
765 // call the hit-testing API. Either way it might be better to have
766 // a DCHECK for the node rather than a null check here.
768 return frame_sink_id_;
771 viz::FrameSinkId remote_frame_sink_id = GetRemoteFrameSinkId(result);
772 if (remote_frame_sink_id.is_valid()) {
773 gfx::PointF local_point(result.LocalPoint());
774 LayoutObject* object = result_node->GetLayoutObject();
775 if (auto* box = DynamicTo<LayoutBox>(object))
776 local_point -= gfx::Vector2dF(box->PhysicalContentBoxOffset());
778 *local_point_in_dips = widget_base_->BlinkSpaceToDIPs(local_point);
779 return remote_frame_sink_id;
782 // Return the FrameSinkId for the current widget if the point did not hit
783 // test to a remote frame, or the point is outside of the remote frame's
784 // content box, or the remote frame doesn't have a valid FrameSinkId yet.
785 return frame_sink_id_;
788 gfx::RectF WebFrameWidgetImpl::BlinkSpaceToDIPs(const gfx::RectF& rect) {
789 return widget_base_->BlinkSpaceToDIPs(rect);
792 gfx::Rect WebFrameWidgetImpl::BlinkSpaceToEnclosedDIPs(const gfx::Rect& rect) {
793 return widget_base_->BlinkSpaceToEnclosedDIPs(rect);
796 gfx::Size WebFrameWidgetImpl::BlinkSpaceToFlooredDIPs(const gfx::Size& size) {
797 return widget_base_->BlinkSpaceToFlooredDIPs(size);
800 gfx::RectF WebFrameWidgetImpl::DIPsToBlinkSpace(const gfx::RectF& rect) {
801 return widget_base_->DIPsToBlinkSpace(rect);
804 gfx::PointF WebFrameWidgetImpl::DIPsToBlinkSpace(const gfx::PointF& point) {
805 return widget_base_->DIPsToBlinkSpace(point);
808 gfx::Point WebFrameWidgetImpl::DIPsToRoundedBlinkSpace(
809 const gfx::Point& point) {
810 return widget_base_->DIPsToRoundedBlinkSpace(point);
813 float WebFrameWidgetImpl::DIPsToBlinkSpace(float scalar) {
814 return widget_base_->DIPsToBlinkSpace(scalar);
817 gfx::Size WebFrameWidgetImpl::DIPsToCeiledBlinkSpace(const gfx::Size& size) {
818 return widget_base_->DIPsToCeiledBlinkSpace(size);
821 void WebFrameWidgetImpl::SetActive(bool active) {
822 View()->SetIsActive(active);
825 WebInputEventResult WebFrameWidgetImpl::HandleKeyEvent(
826 const WebKeyboardEvent& event) {
827 DCHECK((event.GetType() == WebInputEvent::Type::kRawKeyDown) ||
828 (event.GetType() == WebInputEvent::Type::kKeyDown) ||
829 (event.GetType() == WebInputEvent::Type::kKeyUp));
831 // Please refer to the comments explaining the m_suppressNextKeypressEvent
833 // The m_suppressNextKeypressEvent is set if the KeyDown is handled by
834 // Webkit. A keyDown event is typically associated with a keyPress(char)
835 // event and a keyUp event. We reset this flag here as this is a new keyDown
837 suppress_next_keypress_event_ = false;
839 // If there is a popup open, it should be the one processing the event,
841 scoped_refptr<WebPagePopupImpl> page_popup = View()->GetPagePopup();
843 page_popup->HandleKeyEvent(event);
844 if (event.GetType() == WebInputEvent::Type::kRawKeyDown) {
845 suppress_next_keypress_event_ = true;
847 return WebInputEventResult::kHandledSystem;
850 auto* frame = DynamicTo<LocalFrame>(FocusedCoreFrame());
852 return WebInputEventResult::kNotHandled;
854 WebInputEventResult result = frame->GetEventHandler().KeyEvent(event);
855 // EventHandler may have detached the frame.
856 if (!LocalRootImpl())
859 if (result != WebInputEventResult::kNotHandled) {
860 if (WebInputEvent::Type::kRawKeyDown == event.GetType()) {
861 // Suppress the next keypress event unless the focused node is a plugin
862 // node. (Flash needs these keypress events to handle non-US keyboards.)
863 Element* element = FocusedElement();
864 if (element && element->GetLayoutObject() &&
865 element->GetLayoutObject()->IsEmbeddedObject()) {
866 if (event.windows_key_code == VKEY_TAB) {
867 // If the plugin supports keyboard focus then we should not send a tab
869 WebPluginContainerImpl* plugin_view =
870 To<LayoutEmbeddedContent>(element->GetLayoutObject())->Plugin();
871 if (plugin_view && plugin_view->SupportsKeyboardFocus()) {
872 suppress_next_keypress_event_ = true;
876 suppress_next_keypress_event_ = true;
882 #if !BUILDFLAG(IS_MAC)
883 const WebInputEvent::Type kContextMenuKeyTriggeringEventType =
884 #if BUILDFLAG(IS_WIN)
885 WebInputEvent::Type::kKeyUp;
887 WebInputEvent::Type::kRawKeyDown;
889 const WebInputEvent::Type kShiftF10TriggeringEventType =
890 WebInputEvent::Type::kRawKeyDown;
892 bool is_unmodified_menu_key =
893 !(event.GetModifiers() & WebInputEvent::kInputModifiers) &&
894 event.windows_key_code == VKEY_APPS;
895 bool is_shift_f10 = (event.GetModifiers() & WebInputEvent::kInputModifiers) ==
896 WebInputEvent::kShiftKey &&
897 event.windows_key_code == VKEY_F10;
898 if ((is_unmodified_menu_key &&
899 event.GetType() == kContextMenuKeyTriggeringEventType) ||
900 (is_shift_f10 && event.GetType() == kShiftF10TriggeringEventType)) {
901 View()->SendContextMenuEvent();
902 return WebInputEventResult::kHandledSystem;
904 #endif // !BUILDFLAG(IS_MAC)
906 return WebInputEventResult::kNotHandled;
909 void WebFrameWidgetImpl::HandleMouseDown(LocalFrame& local_root,
910 const WebMouseEvent& event) {
911 WebViewImpl* view_impl = View();
912 // If there is a popup open, close it as the user is clicking on the page
913 // (outside of the popup). We also save it so we can prevent a click on an
914 // element from immediately reopening the same popup.
915 scoped_refptr<WebPagePopupImpl> page_popup;
916 if (event.button == WebMouseEvent::Button::kLeft) {
917 page_popup = view_impl->GetPagePopup();
918 view_impl->CancelPagePopup();
921 // Take capture on a mouse down on a plugin so we can send it mouse events.
922 // If the hit node is a plugin but a scrollbar is over it don't start mouse
923 // capture because it will interfere with the scrollbar receiving events.
924 PhysicalOffset point(LayoutUnit(event.PositionInWidget().x()),
925 LayoutUnit(event.PositionInWidget().y()));
926 if (event.button == WebMouseEvent::Button::kLeft) {
927 HitTestLocation location(
928 LocalRootImpl()->GetFrameView()->ConvertFromRootFrame(point));
929 HitTestResult result(
930 LocalRootImpl()->GetFrame()->GetEventHandler().HitTestResultAtLocation(
932 result.SetToShadowHostIfInUAShadowRoot();
933 Node* hit_node = result.InnerNode();
934 auto* html_element = DynamicTo<HTMLElement>(hit_node);
935 if (!result.GetScrollbar() && hit_node && hit_node->GetLayoutObject() &&
936 hit_node->GetLayoutObject()->IsEmbeddedObject() && html_element &&
937 html_element->IsPluginElement()) {
938 mouse_capture_element_ = To<HTMLPlugInElement>(hit_node);
939 SetMouseCapture(true);
940 TRACE_EVENT_NESTABLE_ASYNC_BEGIN0("input", "capturing mouse",
941 TRACE_ID_LOCAL(this));
945 WidgetEventHandler::HandleMouseDown(local_root, event);
946 // WidgetEventHandler may have detached the frame.
947 if (!LocalRootImpl())
950 if (view_impl->GetPagePopup() && page_popup &&
951 view_impl->GetPagePopup()->HasSamePopupClient(page_popup.get())) {
952 // That click triggered a page popup that is the same as the one we just
953 // closed. It needs to be closed.
954 view_impl->CancelPagePopup();
957 // Dispatch the contextmenu event regardless of if the click was swallowed.
958 if (!GetPage()->GetSettings().GetShowContextMenuOnMouseUp()) {
959 #if BUILDFLAG(IS_MAC)
960 if (event.button == WebMouseEvent::Button::kRight ||
961 (event.button == WebMouseEvent::Button::kLeft &&
962 event.GetModifiers() & WebMouseEvent::kControlKey))
963 MouseContextMenu(event);
965 if (event.button == WebMouseEvent::Button::kRight)
966 MouseContextMenu(event);
971 void WebFrameWidgetImpl::HandleMouseLeave(LocalFrame& local_root,
972 const WebMouseEvent& event) {
973 View()->SetMouseOverURL(WebURL());
974 WidgetEventHandler::HandleMouseLeave(local_root, event);
975 // WidgetEventHandler may have detached the frame.
978 void WebFrameWidgetImpl::MouseContextMenu(const WebMouseEvent& event) {
979 GetPage()->GetContextMenuController().ClearContextMenu();
981 WebMouseEvent transformed_event =
982 TransformWebMouseEvent(LocalRootImpl()->GetFrameView(), event);
983 transformed_event.menu_source_type = kMenuSourceMouse;
984 transformed_event.id = PointerEventFactory::kMouseId;
986 // Find the right target frame. See issue 1186900.
987 HitTestResult result =
988 HitTestResultForRootFramePos(transformed_event.PositionInRootFrame());
990 if (result.InnerNodeOrImageMapImage())
991 target_frame = result.InnerNodeOrImageMapImage()->GetDocument().GetFrame();
993 target_frame = GetPage()->GetFocusController().FocusedOrMainFrame();
995 // This will need to be changed to a nullptr check when focus control
996 // is refactored, at which point focusedOrMainFrame will never return a
998 // See https://crbug.com/341918.
999 LocalFrame* target_local_frame = DynamicTo<LocalFrame>(target_frame);
1000 if (!target_local_frame)
1004 ContextMenuAllowedScope scope;
1005 target_local_frame->GetEventHandler().SendContextMenuEvent(
1008 // Actually showing the context menu is handled by the ContextMenuClient
1009 // implementation...
1012 WebInputEventResult WebFrameWidgetImpl::HandleMouseUp(
1013 LocalFrame& local_root,
1014 const WebMouseEvent& event) {
1015 WebInputEventResult result =
1016 WidgetEventHandler::HandleMouseUp(local_root, event);
1017 // WidgetEventHandler may have detached the frame.
1018 if (!LocalRootImpl())
1021 if (GetPage()->GetSettings().GetShowContextMenuOnMouseUp()) {
1022 // Dispatch the contextmenu event regardless of if the click was swallowed.
1023 // On Mac/Linux, we handle it on mouse down, not up.
1024 if (event.button == WebMouseEvent::Button::kRight)
1025 MouseContextMenu(event);
1030 WebInputEventResult WebFrameWidgetImpl::HandleGestureEvent(
1031 const WebGestureEvent& event) {
1032 WebInputEventResult event_result = WebInputEventResult::kNotHandled;
1034 // Fling events are not sent to the renderer.
1035 CHECK(event.GetType() != WebInputEvent::Type::kGestureFlingStart);
1036 CHECK(event.GetType() != WebInputEvent::Type::kGestureFlingCancel);
1038 WebViewImpl* web_view = View();
1040 LocalFrame* frame = LocalRootImpl()->GetFrame();
1041 WebGestureEvent scaled_event = TransformWebGestureEvent(frame->View(), event);
1043 // Special handling for double tap and scroll events as we don't want to
1044 // hit test for them.
1045 switch (event.GetType()) {
1046 case WebInputEvent::Type::kGestureDoubleTap:
1047 if (web_view->SettingsImpl()->DoubleTapToZoomEnabled() &&
1048 web_view->MinimumPageScaleFactor() !=
1049 web_view->MaximumPageScaleFactor()) {
1050 gfx::Point pos_in_local_frame_root =
1051 gfx::ToFlooredPoint(scaled_event.PositionInRootFrame());
1052 auto block_bounds = ComputeBlockBound(pos_in_local_frame_root, false);
1054 if (ForMainFrame()) {
1055 web_view->AnimateDoubleTapZoom(pos_in_local_frame_root, block_bounds);
1057 // This sends the tap point and bounds to the main frame renderer via
1058 // the browser, where their coordinates will be transformed into the
1059 // main frame's coordinate space.
1060 GetAssociatedFrameWidgetHost()->AnimateDoubleTapZoomInMainFrame(
1061 pos_in_local_frame_root, block_bounds);
1064 event_result = WebInputEventResult::kHandledSystem;
1065 DidHandleGestureEvent(event);
1066 return event_result;
1067 case WebInputEvent::Type::kGestureScrollBegin:
1068 case WebInputEvent::Type::kGestureScrollEnd:
1069 case WebInputEvent::Type::kGestureScrollUpdate:
1070 // If we are getting any scroll toss close any page popup that is open.
1071 web_view->CancelPagePopup();
1073 // Scrolling-related gesture events invoke EventHandler recursively for
1074 // each frame down the chain, doing a single-frame hit-test per frame.
1075 // This matches handleWheelEvent. Perhaps we could simplify things by
1076 // rewriting scroll handling to work inner frame out, and then unify with
1077 // other gesture events.
1079 frame->GetEventHandler().HandleGestureScrollEvent(scaled_event);
1080 DidHandleGestureEvent(event);
1081 return event_result;
1086 // Hit test across all frames and do touch adjustment as necessary for the
1088 GestureEventWithHitTestResults targeted_event =
1089 frame->GetEventHandler().TargetGestureEvent(scaled_event);
1091 // Link highlight animations are only for the main frame.
1092 // TODO(bokan): This isn't intentional, see https://crbug.com/1344531.
1093 if (ForMainFrame()) {
1094 // Handle link highlighting outside the main switch to avoid getting lost in
1095 // the complicated set of cases handled below.
1096 switch (scaled_event.GetType()) {
1097 case WebInputEvent::Type::kGestureShowPress:
1098 // Queue a highlight animation, then hand off to regular handler.
1099 web_view->EnableTapHighlightAtPoint(targeted_event);
1101 case WebInputEvent::Type::kGestureShortPress:
1102 case WebInputEvent::Type::kGestureLongPress:
1103 case WebInputEvent::Type::kGestureTapCancel:
1104 case WebInputEvent::Type::kGestureTap:
1105 GetPage()->GetLinkHighlight().UpdateOpacityAndRequestAnimation();
1112 switch (scaled_event.GetType()) {
1113 case WebInputEvent::Type::kGestureTap: {
1114 #if BUILDFLAG(IS_EFL)
1115 if (web_view->SettingsImpl()->LinkEffectEnabled()) {
1116 HitTestResult result = targeted_event.GetHitTestResult();
1117 result.SetToShadowHostIfInUAShadowRoot();
1118 if (result.CanPlayLinkEffect())
1119 FocusedWebLocalFrameInWidget()->Client()->PlayLinkEffect();
1123 ContextMenuAllowedScope scope;
1125 frame->GetEventHandler().HandleGestureEvent(targeted_event);
1128 if (web_view->GetPagePopup() && last_hidden_page_popup_ &&
1129 web_view->GetPagePopup()->HasSamePopupClient(
1130 last_hidden_page_popup_.get())) {
1131 // The tap triggered a page popup that is the same as the one we just
1132 // closed. It needs to be closed.
1133 web_view->CancelPagePopup();
1135 // Don't have this value persist outside of a single tap gesture, plus
1136 // we're done with it now.
1137 last_hidden_page_popup_ = nullptr;
1140 case WebInputEvent::Type::kGestureTwoFingerTap:
1141 case WebInputEvent::Type::kGestureLongPress:
1142 case WebInputEvent::Type::kGestureLongTap:
1143 if (scaled_event.GetType() == WebInputEvent::Type::kGestureLongTap) {
1144 if (LocalFrame* inner_frame =
1145 targeted_event.GetHitTestResult().InnerNodeFrame()) {
1146 if (!inner_frame->GetEventHandler().LongTapShouldInvokeContextMenu())
1148 } else if (!frame->GetEventHandler().LongTapShouldInvokeContextMenu()) {
1153 GetPage()->GetContextMenuController().ClearContextMenu();
1155 ContextMenuAllowedScope scope;
1157 frame->GetEventHandler().HandleGestureEvent(targeted_event);
1161 case WebInputEvent::Type::kGestureTapDown:
1162 // Touch pinch zoom and scroll on the page (outside of a popup) must hide
1163 // the popup. In case of a touch scroll or pinch zoom, this function is
1164 // called with GestureTapDown rather than a GSB/GSU/GSE or GPB/GPU/GPE.
1165 // When we close a popup because of a GestureTapDown, we also save it so
1166 // we can prevent the following GestureTap from immediately reopening the
1168 // This value should not persist outside of a gesture, so is cleared by
1169 // GestureTap (where it is used) and by GestureCancel.
1170 last_hidden_page_popup_ = web_view->GetPagePopup();
1171 web_view->CancelPagePopup();
1173 frame->GetEventHandler().HandleGestureEvent(targeted_event);
1175 case WebInputEvent::Type::kGestureTapCancel:
1176 // Don't have this value persist outside of a single tap gesture.
1177 last_hidden_page_popup_ = nullptr;
1179 frame->GetEventHandler().HandleGestureEvent(targeted_event);
1181 case WebInputEvent::Type::kGestureShowPress:
1182 case WebInputEvent::Type::kGestureTapUnconfirmed:
1183 case WebInputEvent::Type::kGestureShortPress:
1185 frame->GetEventHandler().HandleGestureEvent(targeted_event);
1190 DidHandleGestureEvent(event);
1191 return event_result;
1194 WebInputEventResult WebFrameWidgetImpl::HandleMouseWheel(
1196 const WebMouseWheelEvent& event) {
1197 View()->CancelPagePopup();
1198 return WidgetEventHandler::HandleMouseWheel(frame, event);
1199 // WidgetEventHandler may have detached the frame.
1202 WebInputEventResult WebFrameWidgetImpl::HandleCharEvent(
1203 const WebKeyboardEvent& event) {
1204 DCHECK_EQ(event.GetType(), WebInputEvent::Type::kChar);
1206 // Please refer to the comments explaining the m_suppressNextKeypressEvent
1207 // member. The m_suppressNextKeypressEvent is set if the KeyDown is
1208 // handled by Webkit. A keyDown event is typically associated with a
1209 // keyPress(char) event and a keyUp event. We reset this flag here as it
1210 // only applies to the current keyPress event.
1211 bool suppress = suppress_next_keypress_event_;
1212 suppress_next_keypress_event_ = false;
1214 // If there is a popup open, it should be the one processing the event,
1216 scoped_refptr<WebPagePopupImpl> page_popup = View()->GetPagePopup();
1218 return page_popup->HandleKeyEvent(event);
1220 LocalFrame* frame = To<LocalFrame>(FocusedCoreFrame());
1222 return suppress ? WebInputEventResult::kHandledSuppressed
1223 : WebInputEventResult::kNotHandled;
1226 EventHandler& handler = frame->GetEventHandler();
1228 if (!event.IsCharacterKey())
1229 return WebInputEventResult::kHandledSuppressed;
1231 // Accesskeys are triggered by char events and can't be suppressed.
1232 // It is unclear whether a keypress should be dispatched as well
1234 if (handler.HandleAccessKey(event))
1235 return WebInputEventResult::kHandledSystem;
1237 // Safari 3.1 does not pass off windows system key messages (WM_SYSCHAR) to
1238 // the eventHandler::keyEvent. We mimic this behavior on all platforms since
1239 // for now we are converting other platform's key events to windows key
1241 if (event.is_system_key)
1242 return WebInputEventResult::kNotHandled;
1245 return WebInputEventResult::kHandledSuppressed;
1247 WebInputEventResult result = handler.KeyEvent(event);
1248 if (result != WebInputEventResult::kNotHandled)
1251 return WebInputEventResult::kNotHandled;
1254 void WebFrameWidgetImpl::CancelDrag() {
1255 drag_operation_ = DragController::Operation();
1256 current_drag_data_ = nullptr;
1259 void WebFrameWidgetImpl::StartDragging(LocalFrame* source_frame,
1260 const WebDragData& drag_data,
1261 DragOperationsMask operations_allowed,
1262 const SkBitmap& drag_image,
1263 const gfx::Vector2d& cursor_offset,
1264 const gfx::Rect& drag_obj_rect) {
1265 doing_drag_and_drop_ = true;
1266 if (drag_and_drop_disabled_) {
1267 DragSourceSystemDragEnded();
1271 gfx::Vector2d offset_in_dips =
1272 widget_base_->BlinkSpaceToFlooredDIPs(gfx::Point() + cursor_offset)
1273 .OffsetFromOrigin();
1274 gfx::Rect drag_obj_rect_in_dips =
1275 gfx::Rect(widget_base_->BlinkSpaceToFlooredDIPs(drag_obj_rect.origin()),
1276 widget_base_->BlinkSpaceToFlooredDIPs(drag_obj_rect.size()));
1277 source_frame->GetLocalFrameHostRemote().StartDragging(
1278 drag_data, operations_allowed, drag_image, offset_in_dips,
1279 drag_obj_rect_in_dips, possible_drag_event_info_.Clone());
1282 void WebFrameWidgetImpl::DragTargetDragEnterOrOver(
1283 const gfx::PointF& point_in_viewport,
1284 const gfx::PointF& screen_point,
1285 DragAction drag_action,
1286 uint32_t key_modifiers) {
1287 if (ShouldIgnoreInputEvents() || !current_drag_data_) {
1292 gfx::PointF point_in_root_frame = ViewportToRootFrame(point_in_viewport);
1294 current_drag_data_->SetModifiers(key_modifiers);
1295 DragData drag_data(current_drag_data_.Get(), point_in_root_frame,
1296 screen_point, operations_allowed_,
1297 /*force_default_action=*/false);
1299 drag_operation_ = GetPage()->GetDragController().DragEnteredOrUpdated(
1300 &drag_data, *local_root_->GetFrame());
1302 // Mask the drag operation against the drag source's allowed
1304 if (!(static_cast<int>(drag_operation_.operation) &
1305 drag_data.DraggingSourceOperationMask())) {
1306 drag_operation_ = DragController::Operation();
1310 void WebFrameWidgetImpl::SendOverscrollEventFromImplSide(
1311 const gfx::Vector2dF& overscroll_delta,
1312 cc::ElementId scroll_latched_element_id) {
1313 if (!RuntimeEnabledFeatures::OverscrollCustomizationEnabled())
1316 Node* target_node = View()->FindNodeFromScrollableCompositorElementId(
1317 scroll_latched_element_id);
1319 target_node->GetDocument().EnqueueOverscrollEventForNode(
1320 target_node, overscroll_delta.x(), overscroll_delta.y());
1324 void WebFrameWidgetImpl::SendScrollEndEventFromImplSide(
1325 bool affects_outer_viewport,
1326 cc::ElementId scroll_latched_element_id) {
1327 if (!RuntimeEnabledFeatures::ScrollEndEventsEnabled())
1330 Node* target_node = View()->FindNodeFromScrollableCompositorElementId(
1331 scroll_latched_element_id);
1332 bool target_is_root_scroller = false;
1333 if (View()->MainFrameImpl()) {
1334 Node* document_node = View()->MainFrameImpl()->GetDocument();
1335 if (target_node == document_node) {
1336 target_is_root_scroller = true;
1340 // Scrolls consumed entirely by the VisualViewport and not the
1341 // LayoutViewport should not trigger scrollends on the document. The
1342 // VisualViewport currently handles scroll but not scrollends. If that
1343 // changes, we should consider firing scrollend at the visualviewport
1344 // instead of simply bailing.
1345 if (affects_outer_viewport || !target_is_root_scroller) {
1346 target_node->GetDocument().EnqueueScrollEndEventForNode(target_node);
1351 void WebFrameWidgetImpl::UpdateCompositorScrollState(
1352 const cc::CompositorCommitData& commit_data) {
1353 if (WebDevToolsAgentImpl* devtools = LocalRootImpl()->DevToolsAgentImpl())
1354 devtools->SetPageIsScrolling(commit_data.is_scroll_active);
1356 RecordManipulationTypeCounts(commit_data.manipulation_info);
1358 if (commit_data.scroll_latched_element_id == cc::ElementId())
1361 if (!commit_data.overscroll_delta.IsZero()) {
1362 SendOverscrollEventFromImplSide(commit_data.overscroll_delta,
1363 commit_data.scroll_latched_element_id);
1366 // TODO(bokan): If a scroll ended and a new one began in the same Blink frame
1367 // (e.g. during a long running main thread task), this will erroneously
1368 // dispatch the scroll end to the latter (still-scrolling) element.
1369 // https://crbug.com/1116780.
1370 if (commit_data.scroll_end_data.scroll_gesture_did_end) {
1371 SendScrollEndEventFromImplSide(
1372 commit_data.scroll_end_data.gesture_affects_outer_viewport_scroll,
1373 commit_data.scroll_latched_element_id);
1377 WebInputMethodController*
1378 WebFrameWidgetImpl::GetActiveWebInputMethodController() const {
1379 WebLocalFrameImpl* local_frame =
1380 WebLocalFrameImpl::FromFrame(FocusedLocalFrameInWidget());
1381 return local_frame ? local_frame->GetInputMethodController() : nullptr;
1384 void WebFrameWidgetImpl::DisableDragAndDrop() {
1385 drag_and_drop_disabled_ = true;
1388 gfx::PointF WebFrameWidgetImpl::ViewportToRootFrame(
1389 const gfx::PointF& point_in_viewport) const {
1390 return GetPage()->GetVisualViewport().ViewportToRootFrame(point_in_viewport);
1393 WebViewImpl* WebFrameWidgetImpl::View() const {
1394 return local_root_->ViewImpl();
1397 Page* WebFrameWidgetImpl::GetPage() const {
1398 return View()->GetPage();
1401 mojom::blink::FrameWidgetHost*
1402 WebFrameWidgetImpl::GetAssociatedFrameWidgetHost() const {
1403 return frame_widget_host_.get();
1406 void WebFrameWidgetImpl::RequestDecode(
1407 const PaintImage& image,
1408 base::OnceCallback<void(bool)> callback) {
1409 widget_base_->LayerTreeHost()->QueueImageDecode(image, std::move(callback));
1412 void WebFrameWidgetImpl::Trace(Visitor* visitor) const {
1413 visitor->Trace(local_root_);
1414 visitor->Trace(current_drag_data_);
1415 visitor->Trace(frame_widget_host_);
1416 visitor->Trace(receiver_);
1417 visitor->Trace(input_target_receiver_);
1418 visitor->Trace(mouse_capture_element_);
1419 visitor->Trace(device_emulator_);
1420 visitor->Trace(animation_frame_timing_monitor_);
1423 #if BUILDFLAG(IS_TIZEN_TV)
1424 void WebFrameWidgetImpl::EdgeScrollBy(const gfx::Point& offset, const gfx::Point& mouse_position) {
1425 bool handled = false;
1426 WebViewImpl* webview = View();
1428 handled = webview->EdgeScrollBy(
1429 blink::ScrollOffset(offset.x(), offset.y()),
1430 gfx::Point(mouse_position.x(), mouse_position.y()));
1431 widget_base_->DidEdgeScrollBy(offset, handled);
1434 void WebFrameWidgetImpl::SetTranslatedURL(const WTF::String& url) {
1435 WebViewImpl* webview = View();
1438 webview->SetTranslatedURL(blink::WebString::FromUTF8(url.Ascii()));
1441 void WebFrameWidgetImpl::SetParentalRatingResult(const WTF::String& url,
1443 WebViewImpl* webview = View();
1445 LOG(ERROR) << "no webview.";
1448 webview->SetParentalRatingResult(blink::WebString::FromUTF8(url.Ascii()),
1453 void WebFrameWidgetImpl::SetNeedsRecalculateRasterScales() {
1454 if (!View()->does_composite())
1456 widget_base_->LayerTreeHost()->SetNeedsRecalculateRasterScales();
1459 void WebFrameWidgetImpl::SetBackgroundColor(SkColor color) {
1460 if (!View()->does_composite())
1462 // TODO(crbug/1308932): Remove FromColor and make all SkColor4f.
1463 widget_base_->LayerTreeHost()->set_background_color(
1464 SkColor4f::FromColor(color));
1467 void WebFrameWidgetImpl::SetOverscrollBehavior(
1468 const cc::OverscrollBehavior& overscroll_behavior) {
1469 if (!View()->does_composite())
1471 widget_base_->LayerTreeHost()->SetOverscrollBehavior(overscroll_behavior);
1474 void WebFrameWidgetImpl::SetPrefersReducedMotion(bool prefers_reduced_motion) {
1475 if (!View()->does_composite())
1477 widget_base_->LayerTreeHost()->SetPrefersReducedMotion(
1478 prefers_reduced_motion);
1481 void WebFrameWidgetImpl::StartPageScaleAnimation(const gfx::Point& destination,
1483 float new_page_scale,
1484 base::TimeDelta duration) {
1485 widget_base_->LayerTreeHost()->StartPageScaleAnimation(
1486 destination, use_anchor, new_page_scale, duration);
1489 void WebFrameWidgetImpl::RequestBeginMainFrameNotExpected(bool request) {
1490 if (!View()->does_composite())
1492 widget_base_->LayerTreeHost()->RequestBeginMainFrameNotExpected(request);
1495 void WebFrameWidgetImpl::DidCommitAndDrawCompositorFrame() {
1496 ForEachLocalFrameControlledByWidget(
1497 local_root_->GetFrame(), [](WebLocalFrameImpl* local_frame) {
1498 local_frame->Client()->DidCommitAndDrawCompositorFrame();
1502 void WebFrameWidgetImpl::DidObserveFirstScrollDelay(
1503 base::TimeDelta first_scroll_delay,
1504 base::TimeTicks first_scroll_timestamp) {
1505 if (!local_root_ || !(local_root_->GetFrame()) ||
1506 !(local_root_->GetFrame()->GetDocument())) {
1509 InteractiveDetector* interactive_detector =
1510 InteractiveDetector::From(*(local_root_->GetFrame()->GetDocument()));
1511 if (interactive_detector) {
1512 interactive_detector->DidObserveFirstScrollDelay(first_scroll_delay,
1513 first_scroll_timestamp);
1517 void WebFrameWidgetImpl::WillBeginMainFrame() {
1518 if (animation_frame_timing_monitor_) {
1519 animation_frame_timing_monitor_->WillBeginMainFrame();
1523 bool WebFrameWidgetImpl::ShouldIgnoreInputEvents() {
1525 return IgnoreInputEvents(GetPage()->BrowsingContextGroupToken());
1528 std::unique_ptr<cc::LayerTreeFrameSink>
1529 WebFrameWidgetImpl::AllocateNewLayerTreeFrameSink() {
1533 void WebFrameWidgetImpl::ReportLongAnimationFrameTiming(
1534 AnimationFrameTimingInfo* timing_info) {
1535 WebSecurityOrigin root_origin = local_root_->GetSecurityOrigin();
1536 ForEachLocalFrameControlledByWidget(
1537 local_root_->GetFrame(), [&](WebLocalFrameImpl* local_frame) {
1538 if (local_frame == local_root_ ||
1539 !local_frame->GetSecurityOrigin().IsSameOriginWith(root_origin)) {
1540 DOMWindowPerformance::performance(
1541 *local_frame->GetFrame()->DomWindow())
1542 ->ReportLongAnimationFrameTiming(timing_info);
1547 void WebFrameWidgetImpl::ReportLongTaskTiming(base::TimeTicks start_time,
1548 base::TimeTicks end_time,
1549 ExecutionContext* task_context) {
1551 CHECK(local_root_->GetFrame());
1552 ForEachLocalFrameControlledByWidget(
1553 local_root_->GetFrame(), [&](WebLocalFrameImpl* local_frame) {
1554 CHECK(local_frame->GetFrame());
1555 CHECK(local_frame->GetFrame()->DomWindow());
1556 // Note: |task_context| could be the execution context of any same-agent
1558 DOMWindowPerformance::performance(*local_frame->GetFrame()->DomWindow())
1559 ->ReportLongTask(start_time, end_time, task_context,
1560 /*has_multiple_contexts=*/false);
1564 bool WebFrameWidgetImpl::ShouldReportLongAnimationFrameTiming() const {
1565 return widget_base_ && !IsHidden();
1567 void WebFrameWidgetImpl::OnTaskCompletedForFrame(
1568 base::TimeTicks start_time,
1569 base::TimeTicks end_time,
1570 base::TimeTicks desired_execution_time,
1571 LocalFrame* frame) {
1572 if (animation_frame_timing_monitor_) {
1573 animation_frame_timing_monitor_->OnTaskCompleted(
1574 start_time, end_time, desired_execution_time, frame);
1578 void WebFrameWidgetImpl::DidBeginMainFrame() {
1579 LocalFrame* root_frame = LocalRootImpl()->GetFrame();
1582 if (LocalFrameView* frame_view = root_frame->View())
1583 frame_view->RunPostLifecycleSteps();
1585 if (animation_frame_timing_monitor_) {
1586 animation_frame_timing_monitor_->DidBeginMainFrame();
1589 if (Page* page = root_frame->GetPage())
1590 page->Animator().PostAnimate();
1593 void WebFrameWidgetImpl::UpdateLifecycle(WebLifecycleUpdate requested_update,
1594 DocumentUpdateReason reason) {
1595 TRACE_EVENT0("blink", "WebFrameWidgetImpl::UpdateLifecycle");
1596 if (!LocalRootImpl())
1599 if (requested_update == WebLifecycleUpdate::kAll &&
1600 animation_frame_timing_monitor_) {
1601 animation_frame_timing_monitor_->WillPerformStyleAndLayoutCalculation();
1604 GetPage()->UpdateLifecycle(*LocalRootImpl()->GetFrame(), requested_update,
1606 if (requested_update != WebLifecycleUpdate::kAll)
1609 View()->UpdatePagePopup();
1611 // Meaningful layout events and background colors only apply to main frames.
1612 if (ForMainFrame()) {
1613 MainFrameData& data = main_data();
1615 // There is no background color for non-composited WebViews (eg
1617 if (View()->does_composite()) {
1618 SkColor background_color = View()->BackgroundColor();
1619 SetBackgroundColor(background_color);
1620 if (background_color != data.last_background_color) {
1621 LocalRootImpl()->GetFrame()->DidChangeBackgroundColor(
1622 SkColor4f::FromColor(background_color), false /* color_adjust */);
1623 data.last_background_color = background_color;
1627 if (LocalFrameView* view = LocalRootImpl()->GetFrameView()) {
1628 LocalFrame* frame = LocalRootImpl()->GetFrame();
1630 if (data.should_dispatch_first_visually_non_empty_layout &&
1631 view->IsVisuallyNonEmpty()) {
1632 data.should_dispatch_first_visually_non_empty_layout = false;
1633 // TODO(esprehn): Move users of this callback to something
1634 // better, the heuristic for "visually non-empty" is bad.
1635 DidMeaningfulLayout(WebMeaningfulLayout::kVisuallyNonEmpty);
1638 if (data.should_dispatch_first_layout_after_finished_parsing &&
1639 frame->GetDocument()->HasFinishedParsing()) {
1640 data.should_dispatch_first_layout_after_finished_parsing = false;
1641 DidMeaningfulLayout(WebMeaningfulLayout::kFinishedParsing);
1644 if (data.should_dispatch_first_layout_after_finished_loading &&
1645 frame->GetDocument()->IsLoadCompleted()) {
1646 data.should_dispatch_first_layout_after_finished_loading = false;
1647 DidMeaningfulLayout(WebMeaningfulLayout::kFinishedLoading);
1653 void WebFrameWidgetImpl::DidCompletePageScaleAnimation() {
1654 // Page scale animations only happen on the main frame.
1655 DCHECK(ForMainFrame());
1656 if (auto* focused_frame = View()->FocusedFrame()) {
1657 if (focused_frame->AutofillClient())
1658 focused_frame->AutofillClient()->DidCompleteFocusChangeInFrame();
1661 if (page_scale_animation_for_testing_callback_)
1662 std::move(page_scale_animation_for_testing_callback_).Run();
1665 void WebFrameWidgetImpl::ScheduleAnimation() {
1666 if (!View()->does_composite()) {
1667 non_composited_client_->ScheduleNonCompositedAnimation();
1671 if (widget_base_->WillBeDestroyed()) {
1675 widget_base_->LayerTreeHost()->SetNeedsAnimate();
1678 void WebFrameWidgetImpl::FocusChanged(mojom::blink::FocusState focus_state) {
1679 // TODO(crbug.com/689777): FocusChange events are only sent to the MainFrame
1680 // these maybe should goto the local root so that the rest of input messages
1681 // sent to those are preserved in order.
1682 DCHECK(ForMainFrame());
1683 View()->SetIsActive(focus_state == mojom::blink::FocusState::kFocused ||
1685 mojom::blink::FocusState::kNotFocusedAndActive);
1686 View()->SetPageFocus(focus_state == mojom::blink::FocusState::kFocused);
1689 bool WebFrameWidgetImpl::ShouldAckSyntheticInputImmediately() {
1690 // TODO(bokan): The RequestPresentation API appears not to function in VR. As
1691 // a short term workaround for https://crbug.com/940063, ACK input
1692 // immediately rather than using RequestPresentation.
1693 if (GetPage()->GetSettings().GetImmersiveModeEnabled())
1698 void WebFrameWidgetImpl::UpdateVisualProperties(
1699 const VisualProperties& visual_properties) {
1700 SetZoomLevel(visual_properties.zoom_level);
1702 // TODO(danakj): In order to synchronize updates between local roots, the
1703 // display mode should be propagated to RenderFrameProxies and down through
1704 // their RenderWidgetHosts to child WebFrameWidgetImpl via the
1705 // VisualProperties waterfall, instead of coming to each WebFrameWidgetImpl
1707 // https://developer.mozilla.org/en-US/docs/Web/CSS/@media/display-mode
1708 SetDisplayMode(visual_properties.display_mode);
1709 SetWindowShowState(visual_properties.window_show_state);
1710 SetResizable(visual_properties.resizable);
1712 if (ForMainFrame()) {
1714 visual_properties.auto_resize_enabled,
1715 visual_properties.min_size_for_auto_resize,
1716 visual_properties.max_size_for_auto_resize,
1717 visual_properties.screen_infos.current().device_scale_factor);
1720 bool capture_sequence_number_changed =
1721 visual_properties.capture_sequence_number !=
1722 last_capture_sequence_number_;
1723 if (capture_sequence_number_changed) {
1724 last_capture_sequence_number_ = visual_properties.capture_sequence_number;
1726 // Send the capture sequence number to RemoteFrames that are below the
1727 // local root for this widget.
1728 ForEachRemoteFrameControlledByWidget(
1729 [capture_sequence_number = visual_properties.capture_sequence_number](
1730 RemoteFrame* remote_frame) {
1731 remote_frame->UpdateCaptureSequenceNumber(capture_sequence_number);
1735 if (!View()->AutoResizeMode()) {
1736 // This needs to run before ApplyVisualPropertiesSizing below,
1737 // which updates the current set of screen_infos from visual properties.
1738 if (DidChangeFullscreenState(visual_properties)) {
1739 is_fullscreen_granted_ = visual_properties.is_fullscreen_granted;
1740 if (is_fullscreen_granted_)
1741 View()->DidEnterFullscreen();
1743 View()->DidExitFullscreen();
1747 gfx::Size old_visible_viewport_size_in_dips =
1748 widget_base_->VisibleViewportSizeInDIPs();
1749 ApplyVisualPropertiesSizing(visual_properties);
1751 if (old_visible_viewport_size_in_dips !=
1752 widget_base_->VisibleViewportSizeInDIPs()) {
1753 ForEachLocalFrameControlledByWidget(
1754 local_root_->GetFrame(),
1755 &WebLocalFrameImpl::ResetHasScrolledFocusedEditableIntoView);
1757 // Propagate changes down to child local root RenderWidgets and
1758 // BrowserPlugins in other frame trees/processes.
1759 ForEachRemoteFrameControlledByWidget(
1760 [visible_viewport_size = widget_base_->VisibleViewportSizeInDIPs()](
1761 RemoteFrame* remote_frame) {
1762 remote_frame->DidChangeVisibleViewportSize(visible_viewport_size);
1766 // All non-top-level Widgets (child local-root frames, Portals, GuestViews,
1767 // etc.) propagate and consume the page scale factor as "external", meaning
1768 // that it comes from the top level widget's page scale.
1769 if (!ForTopMostMainFrame()) {
1770 // The main frame controls the page scale factor, from blink. For other
1771 // frame widgets, the page scale from pinch zoom and compositing scale is
1772 // received from its parent as part of the visual properties here. While
1773 // blink doesn't need to know this page scale factor outside the main frame,
1774 // the compositor does in order to produce its output at the correct scale.
1775 float combined_scale_factor = visual_properties.page_scale_factor *
1776 visual_properties.compositing_scale_factor;
1777 widget_base_->LayerTreeHost()->SetExternalPageScaleFactor(
1778 combined_scale_factor, visual_properties.is_pinch_gesture_active);
1780 NotifyPageScaleFactorChanged(visual_properties.page_scale_factor,
1781 visual_properties.is_pinch_gesture_active);
1783 NotifyCompositingScaleFactorChanged(
1784 visual_properties.compositing_scale_factor);
1786 // Ensure the external scale factor in top-level widgets is reset as it may
1787 // be leftover from when a widget was nested and was promoted to top level
1788 // (e.g. portal activation).
1789 widget_base_->LayerTreeHost()->SetExternalPageScaleFactor(
1791 /*is_pinch_gesture_active=*/false);
1794 EventHandler& event_handler = local_root_->GetFrame()->GetEventHandler();
1795 if (event_handler.cursor_accessibility_scale_factor() !=
1796 visual_properties.cursor_accessibility_scale_factor) {
1797 ForEachLocalFrameControlledByWidget(
1798 local_root_->GetFrame(), [&](WebLocalFrameImpl* local_frame) {
1799 local_frame->GetFrame()
1801 .set_cursor_accessibility_scale_factor(
1802 visual_properties.cursor_accessibility_scale_factor);
1804 // Propagate changes down to any child RemoteFrames.
1805 ForEachRemoteFrameControlledByWidget(
1806 [scale_factor = visual_properties.cursor_accessibility_scale_factor](
1807 RemoteFrame* remote_frame) {
1808 remote_frame->CursorAccessibilityScaleFactorChanged(scale_factor);
1812 // TODO(crbug.com/939118): This code path where scroll_focused_node_into_view
1813 // is set is used only for WebView, crbug 939118 tracks fixing webviews to
1814 // not use scroll_focused_node_into_view.
1815 if (visual_properties.scroll_focused_node_into_view)
1816 ScrollFocusedEditableElementIntoView();
1819 void WebFrameWidgetImpl::ApplyVisualPropertiesSizing(
1820 const VisualProperties& visual_properties) {
1821 gfx::Rect new_compositor_viewport_pixel_rect =
1822 visual_properties.compositor_viewport_pixel_rect;
1823 if (ForMainFrame()) {
1825 widget_base_->DIPsToCeiledBlinkSpace(visual_properties.new_size)) {
1826 // Only hide popups when the size changes. Eg https://crbug.com/761908.
1827 View()->CancelPagePopup();
1830 if (auto* device_emulator = DeviceEmulator()) {
1831 device_emulator->UpdateVisualProperties(visual_properties);
1835 if (AutoResizeMode()) {
1836 new_compositor_viewport_pixel_rect = gfx::Rect(gfx::ScaleToCeiledSize(
1837 widget_base_->BlinkSpaceToFlooredDIPs(size_.value_or(gfx::Size())),
1838 visual_properties.screen_infos.current().device_scale_factor));
1842 SetWindowSegments(visual_properties.root_widget_window_segments);
1844 widget_base_->UpdateSurfaceAndScreenInfo(
1845 visual_properties.local_surface_id.value_or(viz::LocalSurfaceId()),
1846 new_compositor_viewport_pixel_rect, visual_properties.screen_infos);
1848 // Store this even when auto-resizing, it is the size of the full viewport
1849 // used for clipping, and this value is propagated down the Widget
1850 // hierarchy via the VisualProperties waterfall.
1851 widget_base_->SetVisibleViewportSizeInDIPs(
1852 visual_properties.visible_viewport_size);
1854 virtual_keyboard_resize_height_physical_px_ =
1855 visual_properties.virtual_keyboard_resize_height_physical_px;
1856 DCHECK(!virtual_keyboard_resize_height_physical_px_ || ForTopMostMainFrame());
1858 if (ForMainFrame()) {
1859 if (!AutoResizeMode()) {
1860 size_ = widget_base_->DIPsToCeiledBlinkSpace(visual_properties.new_size);
1862 View()->ResizeWithBrowserControls(
1864 widget_base_->DIPsToCeiledBlinkSpace(
1865 widget_base_->VisibleViewportSizeInDIPs()),
1866 visual_properties.browser_controls_params);
1869 #if !BUILDFLAG(IS_ANDROID)
1870 LocalRootImpl()->GetFrame()->UpdateWindowControlsOverlay(
1871 visual_properties.window_controls_overlay_rect);
1875 // Widgets in a WebView's frame tree without a local main frame
1876 // set the size of the WebView to be the |visible_viewport_size|, in order
1877 // to limit compositing in (out of process) child frames to what is visible.
1879 // Note that child frames in the same process/WebView frame tree as the
1880 // main frame do not do this in order to not clobber the source of truth in
1882 if (!View()->MainFrameImpl()) {
1883 View()->Resize(widget_base_->DIPsToCeiledBlinkSpace(
1884 widget_base_->VisibleViewportSizeInDIPs()));
1887 Resize(widget_base_->DIPsToCeiledBlinkSpace(visual_properties.new_size));
1891 bool WebFrameWidgetImpl::DidChangeFullscreenState(
1892 const VisualProperties& visual_properties) const {
1893 if (visual_properties.is_fullscreen_granted != is_fullscreen_granted_)
1895 // If changing fullscreen from one display to another, the fullscreen
1896 // granted state will not change, but we still need to resolve promises
1897 // by considering this a change.
1898 return visual_properties.is_fullscreen_granted &&
1899 widget_base_->screen_infos().current().display_id !=
1900 visual_properties.screen_infos.current().display_id;
1903 int WebFrameWidgetImpl::GetLayerTreeId() {
1904 if (!View()->does_composite())
1906 return widget_base_->LayerTreeHost()->GetId();
1909 const cc::LayerTreeSettings* WebFrameWidgetImpl::GetLayerTreeSettings() {
1910 if (!View()->does_composite()) {
1913 return &widget_base_->LayerTreeHost()->GetSettings();
1916 void WebFrameWidgetImpl::UpdateBrowserControlsState(
1917 cc::BrowserControlsState constraints,
1918 cc::BrowserControlsState current,
1920 DCHECK(View()->does_composite());
1921 widget_base_->LayerTreeHost()->UpdateBrowserControlsState(constraints,
1925 void WebFrameWidgetImpl::SetHaveScrollEventHandlers(bool has_handlers) {
1926 widget_base_->LayerTreeHost()->SetHaveScrollEventHandlers(has_handlers);
1929 void WebFrameWidgetImpl::SetEventListenerProperties(
1930 cc::EventListenerClass listener_class,
1931 cc::EventListenerProperties listener_properties) {
1932 widget_base_->LayerTreeHost()->SetEventListenerProperties(
1933 listener_class, listener_properties);
1935 if (listener_class == cc::EventListenerClass::kTouchStartOrMove ||
1936 listener_class == cc::EventListenerClass::kTouchEndOrCancel) {
1937 bool has_touch_handlers =
1938 EventListenerProperties(cc::EventListenerClass::kTouchStartOrMove) !=
1939 cc::EventListenerProperties::kNone ||
1940 EventListenerProperties(cc::EventListenerClass::kTouchEndOrCancel) !=
1941 cc::EventListenerProperties::kNone;
1942 if (!has_touch_handlers_ || *has_touch_handlers_ != has_touch_handlers) {
1943 has_touch_handlers_ = has_touch_handlers;
1945 widget_base_->WidgetScheduler()->SetHasTouchHandler(has_touch_handlers);
1946 // Set touch event consumers based on whether there are touch event
1947 // handlers or the page has hit testable scrollbars.
1948 auto touch_event_consumers = mojom::blink::TouchEventConsumers::New(
1949 has_touch_handlers, GetPage()->GetScrollbarTheme().AllowsHitTest());
1950 frame_widget_host_->SetHasTouchEventConsumers(
1951 std::move(touch_event_consumers));
1953 } else if (listener_class == cc::EventListenerClass::kPointerRawUpdate) {
1954 SetHasPointerRawUpdateEventHandlers(listener_properties !=
1955 cc::EventListenerProperties::kNone);
1959 cc::EventListenerProperties WebFrameWidgetImpl::EventListenerProperties(
1960 cc::EventListenerClass listener_class) const {
1961 return widget_base_->LayerTreeHost()->event_listener_properties(
1965 mojom::blink::DisplayMode WebFrameWidgetImpl::DisplayMode() const {
1966 return display_mode_;
1969 ui::WindowShowState WebFrameWidgetImpl::WindowShowState() const {
1970 return window_show_state_;
1973 bool WebFrameWidgetImpl::Resizable() const {
1977 const WebVector<gfx::Rect>& WebFrameWidgetImpl::WindowSegments() const {
1978 return window_segments_;
1981 bool WebFrameWidgetImpl::StartDeferringCommits(base::TimeDelta timeout,
1982 cc::PaintHoldingReason reason) {
1983 if (!View()->does_composite())
1985 return widget_base_->LayerTreeHost()->StartDeferringCommits(timeout, reason);
1988 void WebFrameWidgetImpl::StopDeferringCommits(
1989 cc::PaintHoldingCommitTrigger triggger) {
1990 if (!View()->does_composite())
1992 widget_base_->LayerTreeHost()->StopDeferringCommits(triggger);
1995 std::unique_ptr<cc::ScopedPauseRendering> WebFrameWidgetImpl::PauseRendering() {
1996 if (!View()->does_composite())
1998 return widget_base_->LayerTreeHost()->PauseRendering();
2001 absl::optional<int> WebFrameWidgetImpl::GetMaxRenderBufferBounds() const {
2002 if (!View()->does_composite()) {
2003 return absl::nullopt;
2005 return widget_base_->GetMaxRenderBufferBounds();
2008 std::unique_ptr<cc::ScopedDeferMainFrameUpdate>
2009 WebFrameWidgetImpl::DeferMainFrameUpdate() {
2010 return widget_base_->LayerTreeHost()->DeferMainFrameUpdate();
2013 void WebFrameWidgetImpl::SetBrowserControlsShownRatio(float top_ratio,
2014 float bottom_ratio) {
2015 widget_base_->LayerTreeHost()->SetBrowserControlsShownRatio(top_ratio,
2019 void WebFrameWidgetImpl::SetBrowserControlsParams(
2020 cc::BrowserControlsParams params) {
2021 widget_base_->LayerTreeHost()->SetBrowserControlsParams(params);
2024 void WebFrameWidgetImpl::SynchronouslyCompositeForTesting(
2025 base::TimeTicks frame_time) {
2026 widget_base_->LayerTreeHost()->CompositeForTest(frame_time, false,
2027 base::OnceClosure());
2030 void WebFrameWidgetImpl::SetDeviceColorSpaceForTesting(
2031 const gfx::ColorSpace& color_space) {
2032 DCHECK(ForMainFrame());
2033 // We are changing the device color space from the renderer, so allocate a
2034 // new viz::LocalSurfaceId to avoid surface invariants violations in tests.
2035 widget_base_->LayerTreeHost()->RequestNewLocalSurfaceId();
2037 display::ScreenInfos screen_infos = widget_base_->screen_infos();
2038 for (display::ScreenInfo& screen_info : screen_infos.screen_infos)
2039 screen_info.display_color_spaces = gfx::DisplayColorSpaces(color_space);
2040 widget_base_->UpdateScreenInfo(screen_infos);
2043 // TODO(665924): Remove direct dispatches of mouse events from
2044 // PointerLockController, instead passing them through EventHandler.
2045 void WebFrameWidgetImpl::PointerLockMouseEvent(
2046 const WebCoalescedInputEvent& coalesced_event) {
2047 const WebInputEvent& input_event = coalesced_event.Event();
2048 const WebMouseEvent& mouse_event =
2049 static_cast<const WebMouseEvent&>(input_event);
2050 WebMouseEvent transformed_event =
2051 TransformWebMouseEvent(local_root_->GetFrameView(), mouse_event);
2053 AtomicString event_type;
2054 switch (input_event.GetType()) {
2055 case WebInputEvent::Type::kMouseDown:
2056 event_type = event_type_names::kMousedown;
2057 if (!GetPage() || !GetPage()->GetPointerLockController().GetElement())
2059 LocalFrame::NotifyUserActivation(
2061 ->GetPointerLockController()
2065 mojom::blink::UserActivationNotificationType::kInteraction);
2067 case WebInputEvent::Type::kMouseUp:
2068 event_type = event_type_names::kMouseup;
2070 case WebInputEvent::Type::kMouseMove:
2071 event_type = event_type_names::kMousemove;
2073 case WebInputEvent::Type::kMouseEnter:
2074 case WebInputEvent::Type::kMouseLeave:
2075 case WebInputEvent::Type::kContextMenu:
2076 // These should not be normally dispatched but may be due to timing
2077 // because pointer lost messaging happens on separate mojo channel.
2080 NOTREACHED() << input_event.GetType();
2084 GetPage()->GetPointerLockController().DispatchLockedMouseEvent(
2086 TransformWebMouseEventVector(
2087 local_root_->GetFrameView(),
2088 coalesced_event.GetCoalescedEventsPointers()),
2089 TransformWebMouseEventVector(
2090 local_root_->GetFrameView(),
2091 coalesced_event.GetPredictedEventsPointers()),
2095 bool WebFrameWidgetImpl::IsPointerLocked() {
2097 return GetPage()->GetPointerLockController().IsPointerLocked();
2102 void WebFrameWidgetImpl::ShowContextMenu(
2103 ui::mojom::blink::MenuSourceType source_type,
2104 const gfx::Point& location) {
2105 host_context_menu_location_ = location;
2109 GetPage()->GetContextMenuController().ClearContextMenu();
2111 ContextMenuAllowedScope scope;
2112 if (LocalFrame* focused_frame =
2113 GetPage()->GetFocusController().FocusedFrame()) {
2114 focused_frame->GetEventHandler().ShowNonLocatedContextMenu(
2115 nullptr, static_cast<blink::WebMenuSourceType>(source_type));
2118 host_context_menu_location_.reset();
2121 void WebFrameWidgetImpl::SetViewportIntersection(
2122 mojom::blink::ViewportIntersectionStatePtr intersection_state,
2123 const absl::optional<VisualProperties>& visual_properties) {
2124 // Remote viewports are only applicable to local frames with remote ancestors.
2125 // TODO(https://crbug.com/1148960): Should this deal with portals?
2126 DCHECK(ForSubframe() || !LocalRootImpl()->GetFrame()->IsOutermostMainFrame());
2128 if (visual_properties.has_value())
2129 UpdateVisualProperties(visual_properties.value());
2130 ApplyViewportIntersection(std::move(intersection_state));
2133 void WebFrameWidgetImpl::ApplyViewportIntersectionForTesting(
2134 mojom::blink::ViewportIntersectionStatePtr intersection_state) {
2135 ApplyViewportIntersection(std::move(intersection_state));
2138 void WebFrameWidgetImpl::ApplyViewportIntersection(
2139 mojom::blink::ViewportIntersectionStatePtr intersection_state) {
2140 if (ForSubframe()) {
2141 // This information is propagated to LTH to define the region for filling
2142 // the on-screen text content.
2143 // TODO(khushalsagar) : This needs to also be done for main frames which are
2144 // embedded pages (see Frame::IsOutermostMainFrame()).
2145 child_data().compositor_visible_rect =
2146 intersection_state->compositor_visible_rect;
2147 widget_base_->LayerTreeHost()->SetVisualDeviceViewportIntersectionRect(
2148 intersection_state->compositor_visible_rect);
2150 LocalRootImpl()->GetFrame()->SetViewportIntersectionFromParent(
2151 *intersection_state);
2154 void WebFrameWidgetImpl::EnableDeviceEmulation(
2155 const DeviceEmulationParams& parameters) {
2156 // Device Emaulation is only supported for the main frame.
2157 DCHECK(ForMainFrame());
2158 if (!device_emulator_) {
2159 gfx::Size size_in_dips = widget_base_->BlinkSpaceToFlooredDIPs(Size());
2161 device_emulator_ = MakeGarbageCollected<ScreenMetricsEmulator>(
2162 this, widget_base_->screen_infos(), size_in_dips,
2163 widget_base_->VisibleViewportSizeInDIPs(),
2164 widget_base_->WidgetScreenRect(), widget_base_->WindowScreenRect());
2166 device_emulator_->ChangeEmulationParams(parameters);
2169 void WebFrameWidgetImpl::DisableDeviceEmulation() {
2170 if (!device_emulator_)
2172 device_emulator_->DisableAndApply();
2173 device_emulator_ = nullptr;
2176 void WebFrameWidgetImpl::SetIsInertForSubFrame(bool inert) {
2177 DCHECK(ForSubframe());
2178 LocalRootImpl()->GetFrame()->SetIsInert(inert);
2181 absl::optional<gfx::Point>
2182 WebFrameWidgetImpl::GetAndResetContextMenuLocation() {
2183 return std::move(host_context_menu_location_);
2186 void WebFrameWidgetImpl::SetZoomLevel(double zoom_level) {
2187 // Override the zoom level with the testing one if necessary.
2188 if (zoom_level_for_testing_ != -INFINITY)
2189 zoom_level = zoom_level_for_testing_;
2191 // Set the layout shift exclusion window for the zoom level change.
2192 if (View()->ZoomLevel() != zoom_level)
2193 NotifyZoomLevelChanged(LocalRootImpl()->GetFrame());
2195 View()->SetZoomLevel(zoom_level);
2197 // Part of the UpdateVisualProperties dance we send the zoom level to
2198 // RemoteFrames that are below the local root for this widget.
2199 ForEachRemoteFrameControlledByWidget([zoom_level](RemoteFrame* remote_frame) {
2200 remote_frame->ZoomLevelChanged(zoom_level);
2204 void WebFrameWidgetImpl::SetAutoResizeMode(bool auto_resize,
2205 const gfx::Size& min_window_size,
2206 const gfx::Size& max_window_size,
2207 float device_scale_factor) {
2208 // Auto resize only applies to main frames.
2209 DCHECK(ForMainFrame());
2212 View()->EnableAutoResizeMode(
2213 gfx::ScaleToCeiledSize(min_window_size, device_scale_factor),
2214 gfx::ScaleToCeiledSize(max_window_size, device_scale_factor));
2215 } else if (AutoResizeMode()) {
2216 View()->DisableAutoResizeMode();
2220 void WebFrameWidgetImpl::DidAutoResize(const gfx::Size& size) {
2221 DCHECK(ForMainFrame());
2222 gfx::Size size_in_dips = widget_base_->BlinkSpaceToFlooredDIPs(size);
2225 // TODO(ccameron): Note that this destroys any information differentiating
2226 // |size| from the compositor's viewport size.
2227 gfx::Rect size_with_dsf = gfx::Rect(gfx::ScaleToCeiledSize(
2228 gfx::Rect(size_in_dips).size(),
2229 widget_base_->GetScreenInfo().device_scale_factor));
2230 widget_base_->LayerTreeHost()->RequestNewLocalSurfaceId();
2231 widget_base_->UpdateCompositorViewportRect(size_with_dsf);
2234 LocalFrame* WebFrameWidgetImpl::FocusedLocalFrameInWidget() const {
2236 // WebFrameWidget is created in the call to CreateFrame. The corresponding
2237 // RenderWidget, however, might not swap in right away (InstallNewDocument()
2238 // will lead to it swapping in). During this interval local_root_ is nullptr
2239 // (see https://crbug.com/792345).
2243 LocalFrame* frame = GetPage()->GetFocusController().FocusedFrame();
2244 return (frame && frame->LocalFrameRoot() == local_root_->GetFrame())
2249 WebLocalFrameImpl* WebFrameWidgetImpl::FocusedWebLocalFrameInWidget() const {
2250 return WebLocalFrameImpl::FromFrame(FocusedLocalFrameInWidget());
2253 bool WebFrameWidgetImpl::ScrollFocusedEditableElementIntoView() {
2254 Element* element = FocusedElement();
2258 EditContext* edit_context = element->GetDocument()
2260 ->GetInputMethodController()
2261 .GetActiveEditContext();
2263 if (!WebElement(element).IsEditable() && !edit_context)
2266 element->GetDocument().UpdateStyleAndLayout(DocumentUpdateReason::kSelection);
2268 if (!element->GetLayoutObject())
2271 // The page scale animation started by ZoomAndScrollToFocusedEditableRect
2272 // will scroll only the visual and layout viewports. Call ScrollRectToVisible
2273 // first to ensure the editable is visible within the document (i.e. scroll
2274 // it into view in any subscrollers). By setting `for_focused_editable`,
2275 // ScrollRectToVisible will stop bubbling when it reaches the layout viewport
2276 // so that can be animated by the PageScaleAnimation.
2277 mojom::blink::ScrollIntoViewParamsPtr params =
2278 ScrollAlignment::CreateScrollIntoViewParams(
2279 ScrollAlignment::CenterIfNeeded(), ScrollAlignment::CenterIfNeeded(),
2280 mojom::blink::ScrollType::kProgrammatic,
2281 /*make_visible_in_visual_viewport=*/false,
2282 mojom::blink::ScrollBehavior::kInstant);
2283 params->for_focused_editable = mojom::blink::FocusedEditableParams::New();
2285 // When deciding whether to zoom in on a focused text box, we should
2286 // decide not to zoom in if the user won't be able to zoom out. e.g if the
2287 // textbox is within a touch-action: none container the user can't zoom
2289 TouchAction action = touch_action_util::ComputeEffectiveTouchAction(*element);
2290 params->for_focused_editable->can_zoom =
2291 static_cast<int>(action) & static_cast<int>(TouchAction::kPinchZoom);
2293 PhysicalRect absolute_element_bounds;
2294 PhysicalRect absolute_caret_bounds;
2297 gfx::Rect control_bounds_in_physical_pixels;
2298 gfx::Rect selection_bounds_in_physical_pixels;
2299 edit_context->GetLayoutBounds(&control_bounds_in_physical_pixels,
2300 &selection_bounds_in_physical_pixels);
2302 absolute_element_bounds = PhysicalRect(control_bounds_in_physical_pixels);
2303 absolute_caret_bounds = PhysicalRect(selection_bounds_in_physical_pixels);
2305 absolute_element_bounds =
2306 PhysicalRect(element->GetLayoutObject()->AbsoluteBoundingBoxRect());
2307 absolute_caret_bounds = PhysicalRect(
2308 element->GetDocument().GetFrame()->Selection().ComputeRectToScroll(
2312 gfx::Vector2dF editable_offset_from_caret(absolute_element_bounds.offset -
2313 absolute_caret_bounds.offset);
2314 gfx::SizeF editable_size(absolute_element_bounds.size);
2316 if (editable_size.IsEmpty()) {
2320 params->for_focused_editable->relative_location = editable_offset_from_caret;
2321 params->for_focused_editable->size = editable_size;
2323 scroll_into_view_util::ScrollRectToVisible(
2324 *element->GetLayoutObject(), absolute_caret_bounds, std::move(params));
2329 void WebFrameWidgetImpl::ResetMeaningfulLayoutStateForMainFrame() {
2330 MainFrameData& data = main_data();
2331 data.should_dispatch_first_visually_non_empty_layout = true;
2332 data.should_dispatch_first_layout_after_finished_parsing = true;
2333 data.should_dispatch_first_layout_after_finished_loading = true;
2334 data.last_background_color.reset();
2336 #if BUILDFLAG(IS_EFL)
2337 if (widget_base_ && widget_base_->LayerTreeHost())
2338 widget_base_->LayerTreeHost()->ResetMeaningfulLayoutStateForMainFrame();
2342 void WebFrameWidgetImpl::InitializeCompositing(
2343 const display::ScreenInfos& screen_infos,
2344 const cc::LayerTreeSettings* settings) {
2345 InitializeCompositingInternal(screen_infos, settings, nullptr);
2348 void WebFrameWidgetImpl::InitializeCompositingFromPreviousWidget(
2349 const display::ScreenInfos& screen_infos,
2350 const cc::LayerTreeSettings* settings,
2351 WebFrameWidget& previous_widget) {
2352 InitializeCompositingInternal(screen_infos, settings, &previous_widget);
2355 void WebFrameWidgetImpl::InitializeCompositingInternal(
2356 const display::ScreenInfos& screen_infos,
2357 const cc::LayerTreeSettings* settings,
2358 WebFrameWidget* previous_widget) {
2359 DCHECK(View()->does_composite());
2360 DCHECK(!non_composited_client_); // Assure only one initialize is called.
2361 widget_base_->InitializeCompositing(
2362 *GetPage()->GetPageScheduler(), screen_infos, settings,
2363 input_handler_weak_ptr_factory_.GetWeakPtr(),
2364 previous_widget ? static_cast<WebFrameWidgetImpl*>(previous_widget)
2365 ->widget_base_.get()
2368 probe::DidInitializeFrameWidget(local_root_->GetFrame());
2370 // TODO(bokan): This seems wrong. Page may host multiple FrameWidgets so this
2371 // will call DidInitializeCompositing once per FrameWidget. It probably makes
2372 // sense to move LinkHighlight from Page to WidgetBase so initialization is
2373 // per-widget. See also: https://crbug.com/1344531.
2374 GetPage()->DidInitializeCompositing(*AnimationHost());
2377 void WebFrameWidgetImpl::InitializeNonCompositing(
2378 WebNonCompositedWidgetClient* client) {
2379 DCHECK(!non_composited_client_);
2381 DCHECK(!View()->does_composite());
2382 widget_base_->InitializeNonCompositing();
2383 non_composited_client_ = client;
2386 void WebFrameWidgetImpl::SetCompositorVisible(bool visible) {
2387 widget_base_->SetCompositorVisible(visible);
2390 gfx::Size WebFrameWidgetImpl::Size() {
2391 return size_.value_or(gfx::Size());
2394 void WebFrameWidgetImpl::Resize(const gfx::Size& new_size) {
2395 if (size_ && *size_ == new_size)
2398 if (ForMainFrame()) {
2400 View()->Resize(new_size);
2404 if (child_data().did_suspend_parsing) {
2405 child_data().did_suspend_parsing = false;
2406 LocalRootImpl()->GetFrame()->Loader().GetDocumentLoader()->ResumeParser();
2409 LocalFrameView* view = LocalRootImpl()->GetFrameView();
2414 view->SetLayoutSize(*size_);
2415 view->Resize(*size_);
2418 void WebFrameWidgetImpl::OnCommitRequested() {
2419 // This can be called during shutdown, in which case local_root_ will be
2421 if (!LocalRootImpl() || !LocalRootImpl()->GetFrame()) {
2424 if (auto* view = LocalRootImpl()->GetFrame()->View())
2425 view->OnCommitRequested();
2428 void WebFrameWidgetImpl::BeginMainFrame(base::TimeTicks last_frame_time) {
2429 TRACE_EVENT1("blink", "WebFrameWidgetImpl::BeginMainFrame", "frameTime",
2431 DCHECK(!last_frame_time.is_null());
2432 CHECK(LocalRootImpl());
2434 // The last_frame_time is created in the compositor thread, it's the time when
2435 // the compositor is ready for a new frame and starts preparing it. For the
2436 // purpose of animation frame timing, this is the desired time to start
2437 // rendering, equivalent to the time when a work task is posted.
2438 if (animation_frame_timing_monitor_) {
2439 animation_frame_timing_monitor_->SetDesiredRenderStartTime(last_frame_time);
2442 // Dirty bit on MouseEventManager is not cleared in OOPIFs after scroll
2443 // or layout changes. Ensure the hover state is recomputed if necessary.
2447 .RecomputeMouseHoverStateIfNeeded();
2449 absl::optional<LocalFrameUkmAggregator::ScopedUkmHierarchicalTimer> ukm_timer;
2450 if (WidgetBase::ShouldRecordBeginMainFrameMetrics()) {
2452 LocalRootImpl()->GetFrame()->View()->GetUkmAggregator()->GetScopedTimer(
2453 LocalFrameUkmAggregator::kAnimate));
2456 GetPage()->Animate(last_frame_time);
2457 // Animate can cause the local frame to detach.
2458 if (!LocalRootImpl())
2461 GetPage()->GetValidationMessageClient().LayoutOverlay();
2464 void WebFrameWidgetImpl::BeginCommitCompositorFrame() {
2465 if (commit_compositor_frame_start_time_.has_value()) {
2466 next_commit_compositor_frame_start_time_.emplace(base::TimeTicks::Now());
2468 commit_compositor_frame_start_time_.emplace(base::TimeTicks::Now());
2470 GetPage()->GetChromeClient().WillCommitCompositorFrame();
2471 probe::LayerTreePainted(LocalRootImpl()->GetFrame());
2472 if (ForTopMostMainFrame()) {
2473 Document* doc = local_root_->GetFrame()->GetDocument();
2474 if (doc->GetSettings()->GetViewportMetaEnabled() &&
2475 !LayerTreeHost()->IsMobileOptimized()) {
2476 UseCounter::Count(doc, WebFeature::kTapDelayEnabled);
2479 if (ForMainFrame()) {
2480 View()->DidCommitCompositorFrameForLocalMainFrame();
2481 View()->UpdatePreferredSize();
2482 if (!View()->MainFrameImpl()) {
2483 // Trying to track down why the view's idea of the main frame varies
2484 // from LocalRootImpl's.
2485 // TODO(https://crbug.com/1139104): Remove this.
2486 std::string reason = View()->GetNullFrameReasonForBug1139104();
2487 DCHECK(false) << reason;
2488 SCOPED_CRASH_KEY_STRING32("Crbug1139104", "NullFrameReason", reason);
2489 base::debug::DumpWithoutCrashing();
2494 void WebFrameWidgetImpl::EndCommitCompositorFrame(
2495 base::TimeTicks commit_start_time,
2496 base::TimeTicks commit_finish_time) {
2497 DCHECK(commit_compositor_frame_start_time_.has_value());
2501 ->GetUkmAggregator()
2502 ->RecordImplCompositorSample(commit_compositor_frame_start_time_.value(),
2503 commit_start_time, commit_finish_time);
2504 commit_compositor_frame_start_time_ =
2505 next_commit_compositor_frame_start_time_;
2506 next_commit_compositor_frame_start_time_.reset();
2509 void WebFrameWidgetImpl::ApplyViewportChanges(
2510 const ApplyViewportChangesArgs& args) {
2511 // Viewport changes only change the outermost main frame. Technically a
2512 // portal has a viewport but it cannot produce changes from the compositor
2513 // until activated so this should be correct for portals too.
2514 if (!LocalRootImpl()->GetFrame()->IsOutermostMainFrame())
2517 WebViewImpl* web_view = View();
2518 // TODO(https://crbug.com/1160652): Figure out if View is null.
2519 CHECK(widget_base_);
2521 web_view->ApplyViewportChanges(args);
2524 void WebFrameWidgetImpl::RecordManipulationTypeCounts(
2525 cc::ManipulationInfo info) {
2526 // Manipulation counts are only recorded for the main frame.
2527 if (!ForMainFrame())
2530 if ((info & cc::kManipulationInfoWheel) == cc::kManipulationInfoWheel) {
2531 UseCounter::Count(LocalRootImpl()->GetDocument(),
2532 WebFeature::kScrollByWheel);
2534 if ((info & cc::kManipulationInfoTouch) == cc::kManipulationInfoTouch) {
2535 UseCounter::Count(LocalRootImpl()->GetDocument(),
2536 WebFeature::kScrollByTouch);
2538 if ((info & cc::kManipulationInfoPinchZoom) ==
2539 cc::kManipulationInfoPinchZoom) {
2540 UseCounter::Count(LocalRootImpl()->GetDocument(), WebFeature::kPinchZoom);
2542 if ((info & cc::kManipulationInfoPrecisionTouchPad) ==
2543 cc::kManipulationInfoPrecisionTouchPad) {
2544 UseCounter::Count(LocalRootImpl()->GetDocument(),
2545 WebFeature::kScrollByPrecisionTouchPad);
2549 void WebFrameWidgetImpl::RecordDispatchRafAlignedInputTime(
2550 base::TimeTicks raf_aligned_input_start_time) {
2551 if (LocalRootImpl()) {
2552 LocalRootImpl()->GetFrame()->View()->GetUkmAggregator()->RecordTimerSample(
2553 LocalFrameUkmAggregator::kHandleInputEvents,
2554 raf_aligned_input_start_time, base::TimeTicks::Now());
2558 void WebFrameWidgetImpl::SetSuppressFrameRequestsWorkaroundFor704763Only(
2559 bool suppress_frame_requests) {
2560 GetPage()->Animator().SetSuppressFrameRequestsWorkaroundFor704763Only(
2561 suppress_frame_requests);
2564 void WebFrameWidgetImpl::CountDroppedPointerDownForEventTiming(unsigned count) {
2565 if (!local_root_ || !(local_root_->GetFrame()) ||
2566 !(local_root_->GetFrame()->DomWindow())) {
2569 WindowPerformance* performance = DOMWindowPerformance::performance(
2570 *(local_root_->GetFrame()->DomWindow()));
2572 performance->eventCounts()->AddMultipleEvents(event_type_names::kPointerdown,
2574 // We only count dropped touchstart that can trigger pointerdown.
2575 performance->eventCounts()->AddMultipleEvents(event_type_names::kTouchstart,
2577 // TouchEnd will not be dropped. But in touch event model only touch starts
2578 // can set the target and after that the touch event always goes to that
2579 // target. So if a touchstart has been dropped, the following touchend will
2580 // not be dispatched. Meanwhile, the pointerup can be captured in the
2581 // pointer_event_manager.
2582 performance->eventCounts()->AddMultipleEvents(event_type_names::kTouchend,
2586 std::unique_ptr<cc::BeginMainFrameMetrics>
2587 WebFrameWidgetImpl::GetBeginMainFrameMetrics() {
2588 if (!LocalRootImpl())
2591 return LocalRootImpl()
2594 ->GetUkmAggregator()
2595 ->GetBeginMainFrameMetrics();
2598 std::unique_ptr<cc::WebVitalMetrics> WebFrameWidgetImpl::GetWebVitalMetrics() {
2599 if (!LocalRootImpl())
2602 // This class should be called at most once per commit.
2603 WebPerformanceMetricsForReporting perf =
2604 LocalRootImpl()->PerformanceMetricsForReporting();
2605 auto metrics = std::make_unique<cc::WebVitalMetrics>();
2606 if (perf.FirstInputDelay().has_value()) {
2607 metrics->first_input_delay = perf.FirstInputDelay().value();
2608 metrics->has_fid = true;
2611 base::TimeTicks start = perf.NavigationStartAsMonotonicTime();
2612 base::TimeTicks largest_contentful_paint =
2613 perf.LargestContentfulDetailsForMetrics().paint_time;
2614 if (largest_contentful_paint >= start) {
2615 metrics->largest_contentful_paint = largest_contentful_paint - start;
2616 metrics->has_lcp = true;
2619 double layout_shift = LocalRootImpl()
2622 ->GetLayoutShiftTracker()
2624 if (layout_shift > 0.f) {
2625 metrics->layout_shift = layout_shift;
2626 metrics->has_cls = true;
2629 if (!metrics->HasValue())
2635 void WebFrameWidgetImpl::BeginUpdateLayers() {
2636 if (LocalRootImpl())
2637 update_layers_start_time_.emplace(base::TimeTicks::Now());
2640 void WebFrameWidgetImpl::EndUpdateLayers() {
2641 if (LocalRootImpl()) {
2642 DCHECK(update_layers_start_time_);
2643 LocalRootImpl()->GetFrame()->View()->GetUkmAggregator()->RecordTimerSample(
2644 LocalFrameUkmAggregator::kUpdateLayers,
2645 update_layers_start_time_.value(), base::TimeTicks::Now());
2646 probe::LayerTreeDidChange(LocalRootImpl()->GetFrame());
2648 update_layers_start_time_.reset();
2651 void WebFrameWidgetImpl::RecordStartOfFrameMetrics() {
2652 if (!LocalRootImpl())
2655 LocalRootImpl()->GetFrame()->View()->GetUkmAggregator()->BeginMainFrame();
2658 void WebFrameWidgetImpl::RecordEndOfFrameMetrics(
2659 base::TimeTicks frame_begin_time,
2660 cc::ActiveFrameSequenceTrackers trackers) {
2661 if (!LocalRootImpl())
2663 Document* document = LocalRootImpl()->GetFrame()->GetDocument();
2668 ->GetUkmAggregator()
2669 ->RecordEndOfFrameMetrics(frame_begin_time, base::TimeTicks::Now(),
2670 trackers, document->UkmSourceID(),
2671 document->UkmRecorder());
2674 void WebFrameWidgetImpl::WillHandleGestureEvent(const WebGestureEvent& event,
2676 possible_drag_event_info_.source = ui::mojom::blink::DragEventSource::kTouch;
2677 possible_drag_event_info_.location =
2678 gfx::ToFlooredPoint(event.PositionInScreen());
2680 bool handle_as_cursor_control = false;
2681 switch (event.GetType()) {
2682 case WebInputEvent::Type::kGestureScrollBegin: {
2683 if (event.data.scroll_begin.cursor_control) {
2684 swipe_to_move_cursor_activated_ = true;
2685 handle_as_cursor_control = true;
2689 case WebInputEvent::Type::kGestureScrollUpdate: {
2690 if (swipe_to_move_cursor_activated_)
2691 handle_as_cursor_control = true;
2694 case WebInputEvent::Type::kGestureScrollEnd: {
2695 if (swipe_to_move_cursor_activated_) {
2696 swipe_to_move_cursor_activated_ = false;
2697 handle_as_cursor_control = true;
2704 // TODO(crbug.com/1140106): Place cursor for scroll begin other than just move
2706 if (handle_as_cursor_control) {
2707 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
2708 if (focused_frame) {
2709 gfx::Point base(event.PositionInWidget().x(),
2710 event.PositionInWidget().y());
2711 focused_frame->MoveCaretSelection(base);
2717 void WebFrameWidgetImpl::WillHandleMouseEvent(const WebMouseEvent& event) {
2718 possible_drag_event_info_.source = ui::mojom::blink::DragEventSource::kMouse;
2719 possible_drag_event_info_.location =
2720 gfx::Point(event.PositionInScreen().x(), event.PositionInScreen().y());
2723 void WebFrameWidgetImpl::ObserveGestureEventAndResult(
2724 const WebGestureEvent& gesture_event,
2725 const gfx::Vector2dF& unused_delta,
2726 const cc::OverscrollBehavior& overscroll_behavior,
2727 bool event_processed) {
2728 if (!widget_base_->LayerTreeHost()->GetSettings().enable_elastic_overscroll)
2731 cc::InputHandlerScrollResult scroll_result;
2732 scroll_result.did_scroll = event_processed;
2733 scroll_result.did_overscroll_root = !unused_delta.IsZero();
2734 scroll_result.unused_scroll_delta = unused_delta;
2735 scroll_result.overscroll_behavior = overscroll_behavior;
2737 widget_base_->widget_input_handler_manager()->ObserveGestureEventOnMainThread(
2738 gesture_event, scroll_result);
2741 void WebFrameWidgetImpl::DidHandleKeyEvent() {
2742 ClearEditCommands();
2745 WebTextInputType WebFrameWidgetImpl::GetTextInputType() {
2746 if (ShouldDispatchImeEventsToPlugin()) {
2747 return GetFocusedPluginContainer()->GetPluginTextInputType();
2750 WebInputMethodController* controller = GetActiveWebInputMethodController();
2752 return WebTextInputType::kWebTextInputTypeNone;
2753 return controller->TextInputType();
2756 void WebFrameWidgetImpl::SetCursorVisibilityState(bool is_visible) {
2757 GetPage()->SetIsCursorVisible(is_visible);
2760 void WebFrameWidgetImpl::ApplyViewportChangesForTesting(
2761 const ApplyViewportChangesArgs& args) {
2762 widget_base_->ApplyViewportChanges(args);
2765 void WebFrameWidgetImpl::SetDisplayMode(mojom::blink::DisplayMode mode) {
2766 if (mode != display_mode_) {
2767 display_mode_ = mode;
2768 LocalFrame* frame = LocalRootImpl()->GetFrame();
2769 frame->MediaQueryAffectingValueChangedForLocalSubtree(
2770 MediaValueChange::kOther);
2774 void WebFrameWidgetImpl::SetWindowShowState(ui::WindowShowState state) {
2775 if (state == window_show_state_) {
2779 window_show_state_ = state;
2780 LocalFrame* frame = LocalRootImpl()->GetFrame();
2781 frame->MediaQueryAffectingValueChangedForLocalSubtree(
2782 MediaValueChange::kOther);
2785 void WebFrameWidgetImpl::SetResizable(bool resizable) {
2786 if (resizable_ == resizable) {
2790 resizable_ = resizable;
2791 LocalFrame* frame = LocalRootImpl()->GetFrame();
2792 frame->MediaQueryAffectingValueChangedForLocalSubtree(
2793 MediaValueChange::kOther);
2796 void WebFrameWidgetImpl::SetWindowSegments(
2797 const std::vector<gfx::Rect>& window_segments_param) {
2798 WebVector<gfx::Rect> window_segments(window_segments_param);
2799 if (!window_segments_.Equals(window_segments)) {
2800 window_segments_ = window_segments;
2801 LocalFrame* frame = LocalRootImpl()->GetFrame();
2802 frame->WindowSegmentsChanged(window_segments_);
2804 ForEachRemoteFrameControlledByWidget(
2805 [&window_segments = window_segments_param](RemoteFrame* remote_frame) {
2806 remote_frame->DidChangeRootWindowSegments(window_segments);
2811 void WebFrameWidgetImpl::SetCursor(const ui::Cursor& cursor) {
2812 widget_base_->SetCursor(cursor);
2815 bool WebFrameWidgetImpl::HandlingInputEvent() {
2816 return widget_base_->input_handler().handling_input_event();
2819 void WebFrameWidgetImpl::SetHandlingInputEvent(bool handling) {
2820 widget_base_->input_handler().set_handling_input_event(handling);
2823 void WebFrameWidgetImpl::ProcessInputEventSynchronouslyForTesting(
2824 const WebCoalescedInputEvent& event,
2825 WidgetBaseInputHandler::HandledEventCallback callback) {
2826 widget_base_->input_handler().HandleInputEvent(event, nullptr,
2827 std::move(callback));
2830 void WebFrameWidgetImpl::ProcessInputEventSynchronouslyForTesting(
2831 const WebCoalescedInputEvent& event) {
2832 ProcessInputEventSynchronouslyForTesting(event, base::DoNothing());
2835 WebInputEventResult WebFrameWidgetImpl::DispatchBufferedTouchEvents() {
2836 CHECK(LocalRootImpl());
2838 if (WebDevToolsAgentImpl* devtools = LocalRootImpl()->DevToolsAgentImpl())
2839 devtools->DispatchBufferedTouchEvents();
2841 return LocalRootImpl()
2844 .DispatchBufferedTouchEvents();
2847 WebInputEventResult WebFrameWidgetImpl::HandleInputEvent(
2848 const WebCoalescedInputEvent& coalesced_event) {
2849 const WebInputEvent& input_event = coalesced_event.Event();
2850 TRACE_EVENT1("input,rail", "WebFrameWidgetImpl::HandleInputEvent", "type",
2851 WebInputEvent::GetName(input_event.GetType()));
2852 DCHECK(!WebInputEvent::IsTouchEventType(input_event.GetType()));
2853 CHECK(LocalRootImpl());
2855 // Clients shouldn't be dispatching events to a provisional frame but this
2856 // can happen. Ensure that event handling can assume we're in a committed
2858 if (IsProvisional())
2859 return WebInputEventResult::kHandledSuppressed;
2861 // If a drag-and-drop operation is in progress, ignore input events except
2862 // PointerCancel and GestureLongPress.
2863 if (doing_drag_and_drop_ &&
2864 input_event.GetType() != WebInputEvent::Type::kPointerCancel &&
2865 input_event.GetType() != WebInputEvent::Type::kGestureLongPress) {
2866 return WebInputEventResult::kHandledSuppressed;
2869 // Don't handle events once we've started shutting down or when the page is in
2872 GetPage()->GetPageLifecycleState()->is_in_back_forward_cache) {
2873 return WebInputEventResult::kNotHandled;
2876 if (WebDevToolsAgentImpl* devtools = LocalRootImpl()->DevToolsAgentImpl()) {
2877 auto result = devtools->HandleInputEvent(input_event);
2878 if (result != WebInputEventResult::kNotHandled)
2882 // Report the event to be NOT processed by WebKit, so that the browser can
2883 // handle it appropriately.
2884 if (ShouldIgnoreInputEvents()) {
2885 return WebInputEventResult::kNotHandled;
2888 base::AutoReset<const WebInputEvent*> current_event_change(
2889 &CurrentInputEvent::current_input_event_, &input_event);
2890 UIEventWithKeyState::ClearNewTabModifierSetFromIsolatedWorld();
2892 if (GetPage()->GetPointerLockController().IsPointerLocked() &&
2893 WebInputEvent::IsMouseEventType(input_event.GetType())) {
2894 PointerLockMouseEvent(coalesced_event);
2895 return WebInputEventResult::kHandledSystem;
2898 /// These metrics are only captured for the main frame.
2899 if (ForMainFrame()) {
2900 Document& main_frame_document = *LocalRootImpl()->GetFrame()->GetDocument();
2902 if (input_event.GetType() != WebInputEvent::Type::kMouseMove) {
2903 FirstMeaningfulPaintDetector::From(main_frame_document)
2904 .NotifyInputEvent();
2907 if (input_event.GetType() != WebInputEvent::Type::kMouseMove &&
2908 input_event.GetType() != WebInputEvent::Type::kMouseEnter &&
2909 input_event.GetType() != WebInputEvent::Type::kMouseLeave) {
2910 InteractiveDetector* interactive_detector(
2911 InteractiveDetector::From(main_frame_document));
2912 if (interactive_detector) {
2913 interactive_detector->OnInvalidatingInputEvent(input_event.TimeStamp());
2918 NotifyInputObservers(coalesced_event);
2920 // Notify the focus frame of the input. Note that the other frames are not
2921 // notified as input is only handled by the focused frame.
2922 Frame* frame = FocusedCoreFrame();
2923 if (auto* local_frame = DynamicTo<LocalFrame>(frame)) {
2924 if (auto* content_capture_manager =
2925 local_frame->LocalFrameRoot().GetOrResetContentCaptureManager()) {
2926 content_capture_manager->NotifyInputEvent(input_event.GetType(),
2931 // Skip the pointerrawupdate for mouse capture case.
2932 if (mouse_capture_element_ &&
2933 input_event.GetType() == WebInputEvent::Type::kPointerRawUpdate)
2934 return WebInputEventResult::kHandledSystem;
2936 if (mouse_capture_element_ &&
2937 WebInputEvent::IsMouseEventType(input_event.GetType()))
2938 return HandleCapturedMouseEvent(coalesced_event);
2940 // FIXME: This should take in the intended frame, not the local frame
2942 return WidgetEventHandler::HandleInputEvent(coalesced_event,
2943 LocalRootImpl()->GetFrame());
2946 WebInputEventResult WebFrameWidgetImpl::HandleCapturedMouseEvent(
2947 const WebCoalescedInputEvent& coalesced_event) {
2948 const WebInputEvent& input_event = coalesced_event.Event();
2949 TRACE_EVENT1("input", "captured mouse event", "type", input_event.GetType());
2950 // Save |mouse_capture_element_| since |MouseCaptureLost()| will clear it.
2951 HTMLPlugInElement* element = mouse_capture_element_;
2953 // Not all platforms call mouseCaptureLost() directly.
2954 if (input_event.GetType() == WebInputEvent::Type::kMouseUp) {
2955 SetMouseCapture(false);
2959 AtomicString event_type;
2960 switch (input_event.GetType()) {
2961 case WebInputEvent::Type::kMouseEnter:
2962 event_type = event_type_names::kMouseover;
2964 case WebInputEvent::Type::kMouseMove:
2965 event_type = event_type_names::kMousemove;
2967 case WebInputEvent::Type::kPointerRawUpdate:
2968 // There will be no mouse event for rawupdate events.
2969 event_type = event_type_names::kPointerrawupdate;
2971 case WebInputEvent::Type::kMouseLeave:
2972 event_type = event_type_names::kMouseout;
2974 case WebInputEvent::Type::kMouseDown:
2975 event_type = event_type_names::kMousedown;
2976 LocalFrame::NotifyUserActivation(
2977 element->GetDocument().GetFrame(),
2978 mojom::blink::UserActivationNotificationType::kInteraction);
2980 case WebInputEvent::Type::kMouseUp:
2981 event_type = event_type_names::kMouseup;
2987 WebMouseEvent transformed_event =
2988 TransformWebMouseEvent(LocalRootImpl()->GetFrameView(),
2989 static_cast<const WebMouseEvent&>(input_event));
2990 if (LocalFrame* frame = element->GetDocument().GetFrame()) {
2991 frame->GetEventHandler().HandleTargetedMouseEvent(
2992 element, transformed_event, event_type,
2993 TransformWebMouseEventVector(
2994 LocalRootImpl()->GetFrameView(),
2995 coalesced_event.GetCoalescedEventsPointers()),
2996 TransformWebMouseEventVector(
2997 LocalRootImpl()->GetFrameView(),
2998 coalesced_event.GetPredictedEventsPointers()));
3000 return WebInputEventResult::kHandledSystem;
3003 void WebFrameWidgetImpl::UpdateTextInputState() {
3004 widget_base_->UpdateTextInputState();
3007 void WebFrameWidgetImpl::UpdateSelectionBounds() {
3008 widget_base_->UpdateSelectionBounds();
3011 void WebFrameWidgetImpl::ShowVirtualKeyboard() {
3012 widget_base_->ShowVirtualKeyboard();
3015 void WebFrameWidgetImpl::FlushInputProcessedCallback() {
3016 widget_base_->FlushInputProcessedCallback();
3019 void WebFrameWidgetImpl::CancelCompositionForPepper() {
3020 widget_base_->CancelCompositionForPepper();
3023 void WebFrameWidgetImpl::RequestMouseLock(
3024 bool has_transient_user_activation,
3025 bool request_unadjusted_movement,
3026 mojom::blink::WidgetInputHandlerHost::RequestMouseLockCallback callback) {
3027 mojom::blink::WidgetInputHandlerHost* host =
3028 widget_base_->widget_input_handler_manager()->GetWidgetInputHandlerHost();
3030 // If we don't have a host just leave the callback uncalled. This simulates
3031 // the browser indefinitely postponing the mouse request which is valid.
3032 // Note that |callback| is not a mojo bound callback (until it is passed
3033 // into the mojo interface) and can be destructed without invoking the
3034 // callback. It does share the same signature as the mojo definition
3037 host->RequestMouseLock(has_transient_user_activation,
3038 request_unadjusted_movement, std::move(callback));
3042 void WebFrameWidgetImpl::MouseCaptureLost() {
3043 TRACE_EVENT_NESTABLE_ASYNC_END0("input", "capturing mouse",
3044 TRACE_ID_LOCAL(this));
3045 mouse_capture_element_ = nullptr;
3048 void WebFrameWidgetImpl::ApplyVisualProperties(
3049 const VisualProperties& visual_properties) {
3050 widget_base_->UpdateVisualProperties(visual_properties);
3053 bool WebFrameWidgetImpl::IsFullscreenGranted() {
3054 return is_fullscreen_granted_;
3057 bool WebFrameWidgetImpl::PinchGestureActiveInMainFrame() {
3058 return is_pinch_gesture_active_in_mainframe_;
3061 float WebFrameWidgetImpl::PageScaleInMainFrame() {
3062 return page_scale_factor_in_mainframe_;
3065 void WebFrameWidgetImpl::UpdateSurfaceAndScreenInfo(
3066 const viz::LocalSurfaceId& new_local_surface_id,
3067 const gfx::Rect& compositor_viewport_pixel_rect,
3068 const display::ScreenInfos& new_screen_infos) {
3069 widget_base_->UpdateSurfaceAndScreenInfo(
3070 new_local_surface_id, compositor_viewport_pixel_rect, new_screen_infos);
3073 void WebFrameWidgetImpl::UpdateScreenInfo(
3074 const display::ScreenInfos& new_screen_infos) {
3075 widget_base_->UpdateScreenInfo(new_screen_infos);
3078 void WebFrameWidgetImpl::UpdateSurfaceAndCompositorRect(
3079 const viz::LocalSurfaceId& new_local_surface_id,
3080 const gfx::Rect& compositor_viewport_pixel_rect) {
3081 widget_base_->UpdateSurfaceAndCompositorRect(new_local_surface_id,
3082 compositor_viewport_pixel_rect);
3085 void WebFrameWidgetImpl::UpdateCompositorViewportRect(
3086 const gfx::Rect& compositor_viewport_pixel_rect) {
3087 widget_base_->UpdateCompositorViewportRect(compositor_viewport_pixel_rect);
3090 const display::ScreenInfo& WebFrameWidgetImpl::GetScreenInfo() {
3091 return widget_base_->GetScreenInfo();
3094 const display::ScreenInfos& WebFrameWidgetImpl::GetScreenInfos() {
3095 return widget_base_->screen_infos();
3098 const display::ScreenInfo& WebFrameWidgetImpl::GetOriginalScreenInfo() {
3099 if (device_emulator_)
3100 return device_emulator_->GetOriginalScreenInfo();
3101 return widget_base_->GetScreenInfo();
3104 const display::ScreenInfos& WebFrameWidgetImpl::GetOriginalScreenInfos() {
3105 if (device_emulator_)
3106 return device_emulator_->original_screen_infos();
3107 return widget_base_->screen_infos();
3110 gfx::Rect WebFrameWidgetImpl::WindowRect() {
3111 return widget_base_->WindowRect();
3114 gfx::Rect WebFrameWidgetImpl::ViewRect() {
3115 return widget_base_->ViewRect();
3118 void WebFrameWidgetImpl::SetScreenRects(const gfx::Rect& widget_screen_rect,
3119 const gfx::Rect& window_screen_rect) {
3120 widget_base_->SetScreenRects(widget_screen_rect, window_screen_rect);
3123 gfx::Size WebFrameWidgetImpl::VisibleViewportSizeInDIPs() {
3124 return widget_base_->VisibleViewportSizeInDIPs();
3127 void WebFrameWidgetImpl::SetPendingWindowRect(
3128 const gfx::Rect& window_screen_rect) {
3129 widget_base_->SetPendingWindowRect(window_screen_rect);
3132 void WebFrameWidgetImpl::AckPendingWindowRect() {
3133 widget_base_->AckPendingWindowRect();
3136 bool WebFrameWidgetImpl::IsHidden() const {
3137 return widget_base_->is_hidden();
3140 WebString WebFrameWidgetImpl::GetLastToolTipTextForTesting() const {
3141 return GetPage()->GetChromeClient().GetLastToolTipTextForTesting();
3144 float WebFrameWidgetImpl::GetEmulatorScale() {
3145 if (device_emulator_)
3146 return device_emulator_->scale();
3150 void WebFrameWidgetImpl::IntrinsicSizingInfoChanged(
3151 mojom::blink::IntrinsicSizingInfoPtr sizing_info) {
3152 DCHECK(ForSubframe());
3153 GetAssociatedFrameWidgetHost()->IntrinsicSizingInfoChanged(
3154 std::move(sizing_info));
3157 void WebFrameWidgetImpl::AutoscrollStart(const gfx::PointF& position) {
3158 GetAssociatedFrameWidgetHost()->AutoscrollStart(std::move(position));
3161 void WebFrameWidgetImpl::AutoscrollFling(const gfx::Vector2dF& velocity) {
3162 GetAssociatedFrameWidgetHost()->AutoscrollFling(std::move(velocity));
3165 void WebFrameWidgetImpl::AutoscrollEnd() {
3166 GetAssociatedFrameWidgetHost()->AutoscrollEnd();
3169 void WebFrameWidgetImpl::DidMeaningfulLayout(WebMeaningfulLayout layout_type) {
3170 if (layout_type == blink::WebMeaningfulLayout::kVisuallyNonEmpty) {
3171 NotifyPresentationTime(WTF::BindOnce(
3172 &WebFrameWidgetImpl::PresentationCallbackForMeaningfulLayout,
3173 WrapWeakPersistent(this)));
3176 #if BUILDFLAG(IS_EFL)
3177 if (widget_base_ && widget_base_->LayerTreeHost()) {
3178 if (layout_type == blink::WebMeaningfulLayout::kVisuallyNonEmpty)
3179 widget_base_->LayerTreeHost()->SetDidFirstNonEmptyLayout();
3180 else if (layout_type == blink::WebMeaningfulLayout::kFinishedParsing)
3181 widget_base_->LayerTreeHost()->SetDidFinishDocumentParsing();
3185 ForEachLocalFrameControlledByWidget(
3186 local_root_->GetFrame(), [layout_type](WebLocalFrameImpl* local_frame) {
3187 local_frame->Client()->DidMeaningfulLayout(layout_type);
3191 void WebFrameWidgetImpl::PresentationCallbackForMeaningfulLayout(
3192 base::TimeTicks first_paint_time) {
3193 // |local_root_| may be null if the widget has shut down between when this
3194 // callback was requested and when it was resolved by the compositor.
3196 local_root_->ViewImpl()->DidFirstVisuallyNonEmptyPaint();
3199 widget_base_->DidFirstVisuallyNonEmptyPaint(first_paint_time);
3201 #if BUILDFLAG(IS_EFL)
3202 if (widget_base_ && widget_base_->LayerTreeHost())
3203 widget_base_->LayerTreeHost()->SetDidTriggerFirstNonEmptyLayoutPaint();
3207 void WebFrameWidgetImpl::RequestAnimationAfterDelay(
3208 const base::TimeDelta& delay) {
3209 widget_base_->RequestAnimationAfterDelay(delay);
3212 void WebFrameWidgetImpl::SetRootLayer(scoped_refptr<cc::Layer> layer) {
3213 if (!View()->does_composite()) {
3214 DCHECK(ForMainFrame());
3219 // Set up some initial state before we are setting the layer.
3220 if (ForSubframe() && layer) {
3221 // Child local roots will always have a transparent background color.
3222 widget_base_->LayerTreeHost()->set_background_color(SkColors::kTransparent);
3223 // Pass the limits even though this is for subframes, as the limits will
3224 // be needed in setting the raster scale.
3225 SetPageScaleStateAndLimits(1.f, false /* is_pinch_gesture_active */,
3226 View()->MinimumPageScaleFactor(),
3227 View()->MaximumPageScaleFactor());
3230 bool root_layer_exists = !!layer;
3231 if (widget_base_->WillBeDestroyed()) {
3234 widget_base_->LayerTreeHost()->SetRootLayer(std::move(layer));
3237 // Notify the WebView that we did set a layer.
3238 if (ForMainFrame()) {
3239 View()->DidChangeRootLayer(root_layer_exists);
3243 base::WeakPtr<AnimationWorkletMutatorDispatcherImpl>
3244 WebFrameWidgetImpl::EnsureCompositorMutatorDispatcher(
3245 scoped_refptr<base::SingleThreadTaskRunner> mutator_task_runner) {
3246 if (!mutator_task_runner_) {
3247 mutator_task_runner_ = std::move(mutator_task_runner);
3248 widget_base_->LayerTreeHost()->SetLayerTreeMutator(
3249 AnimationWorkletMutatorDispatcherImpl::CreateCompositorThreadClient(
3250 mutator_dispatcher_, mutator_task_runner_));
3253 DCHECK(mutator_task_runner_);
3254 return mutator_dispatcher_;
3257 HitTestResult WebFrameWidgetImpl::CoreHitTestResultAt(
3258 const gfx::PointF& point_in_viewport) {
3259 LocalFrameView* view = LocalRootImpl()->GetFrameView();
3260 gfx::PointF point_in_root_frame(view->ViewportToFrame(point_in_viewport));
3261 return HitTestResultForRootFramePos(point_in_root_frame);
3264 cc::AnimationHost* WebFrameWidgetImpl::AnimationHost() const {
3265 return widget_base_->AnimationHost();
3268 cc::AnimationTimeline* WebFrameWidgetImpl::ScrollAnimationTimeline() const {
3269 return widget_base_->ScrollAnimationTimeline();
3272 base::WeakPtr<PaintWorkletPaintDispatcher>
3273 WebFrameWidgetImpl::EnsureCompositorPaintDispatcher(
3274 scoped_refptr<base::SingleThreadTaskRunner>* paint_task_runner) {
3275 // We check paint_task_runner_ not paint_dispatcher_ because the dispatcher is
3276 // a base::WeakPtr that should only be used on the compositor thread.
3277 if (!paint_task_runner_) {
3278 widget_base_->LayerTreeHost()->SetPaintWorkletLayerPainter(
3279 PaintWorkletPaintDispatcher::CreateCompositorThreadPainter(
3280 &paint_dispatcher_));
3281 paint_task_runner_ = Thread::CompositorThread()->GetTaskRunner();
3283 DCHECK(paint_task_runner_);
3284 *paint_task_runner = paint_task_runner_;
3285 return paint_dispatcher_;
3288 void WebFrameWidgetImpl::SetDelegatedInkMetadata(
3289 std::unique_ptr<gfx::DelegatedInkMetadata> metadata) {
3290 widget_base_->LayerTreeHost()->SetDelegatedInkMetadata(std::move(metadata));
3293 // Enables measuring and reporting both presentation times and swap times in
3295 class ReportTimeSwapPromise : public cc::SwapPromise {
3297 ReportTimeSwapPromise(WebFrameWidgetImpl::PromiseCallbacks callbacks,
3298 scoped_refptr<base::SingleThreadTaskRunner> task_runner,
3299 WebFrameWidgetImpl* widget)
3300 : promise_callbacks_(std::move(callbacks)),
3301 task_runner_(std::move(task_runner)),
3302 widget_(MakeCrossThreadWeakHandle(widget)) {}
3304 ReportTimeSwapPromise(const ReportTimeSwapPromise&) = delete;
3305 ReportTimeSwapPromise& operator=(const ReportTimeSwapPromise&) = delete;
3307 ~ReportTimeSwapPromise() override = default;
3309 void DidActivate() override {}
3311 void WillSwap(viz::CompositorFrameMetadata* metadata) override {
3312 DCHECK_GT(metadata->frame_token, 0u);
3313 // The interval between the current swap and its presentation time is
3314 // reported in UMA (see corresponding code in DidSwap() below).
3315 frame_token_ = metadata->frame_token;
3318 void DidSwap() override {
3319 DCHECK_GT(frame_token_, 0u);
3320 PostCrossThreadTask(
3321 *task_runner_, FROM_HERE,
3322 CrossThreadBindOnce(&RunCallbackAfterSwap,
3323 MakeUnwrappingCrossThreadWeakHandle(widget_),
3324 base::TimeTicks::Now(),
3325 std::move(promise_callbacks_), frame_token_));
3328 DidNotSwapAction DidNotSwap(DidNotSwapReason reason,
3329 base::TimeTicks timestamp) override {
3330 if (reason != DidNotSwapReason::SWAP_FAILS &&
3331 reason != DidNotSwapReason::COMMIT_NO_UPDATE) {
3332 return DidNotSwapAction::KEEP_ACTIVE;
3335 DidNotSwapAction action = DidNotSwapAction::BREAK_PROMISE;
3336 WebFrameWidgetImpl::PromiseCallbacks promise_callbacks_on_failure = {
3337 .swap_time_callback = std::move(promise_callbacks_.swap_time_callback),
3338 .presentation_time_callback =
3339 std::move(promise_callbacks_.presentation_time_callback)};
3341 #if BUILDFLAG(IS_APPLE)
3342 if (reason == DidNotSwapReason::COMMIT_FAILS &&
3343 promise_callbacks_.core_animation_error_code_callback) {
3344 action = DidNotSwapAction::KEEP_ACTIVE;
3346 promise_callbacks_on_failure.core_animation_error_code_callback =
3347 std::move(promise_callbacks_.core_animation_error_code_callback);
3351 if (!promise_callbacks_on_failure.IsEmpty()) {
3352 ReportSwapAndPresentationFailureOnTaskRunner(
3353 task_runner_, std::move(promise_callbacks_on_failure), timestamp);
3358 int64_t GetTraceId() const override { return 0; }
3361 static void RunCallbackAfterSwap(
3362 WebFrameWidgetImpl* widget,
3363 base::TimeTicks swap_time,
3364 WebFrameWidgetImpl::PromiseCallbacks callbacks,
3366 // If the widget was collected or the widget wasn't collected yet, but
3367 // it was closed don't schedule a presentation callback.
3368 if (widget && widget->widget_base_) {
3369 widget->widget_base_->AddPresentationCallback(
3371 WTF::BindOnce(&RunCallbackAfterPresentation,
3372 std::move(callbacks.presentation_time_callback),
3374 ReportTime(std::move(callbacks.swap_time_callback), swap_time);
3376 #if BUILDFLAG(IS_APPLE)
3377 if (callbacks.core_animation_error_code_callback) {
3378 widget->widget_base_->AddCoreAnimationErrorCodeCallback(
3380 std::move(callbacks.core_animation_error_code_callback));
3384 ReportTime(std::move(callbacks.swap_time_callback), swap_time);
3385 ReportTime(std::move(callbacks.presentation_time_callback), swap_time);
3386 #if BUILDFLAG(IS_APPLE)
3387 ReportErrorCode(std::move(callbacks.core_animation_error_code_callback),
3388 gfx::kCALayerUnknownNoWidget);
3393 static void RunCallbackAfterPresentation(
3394 base::OnceCallback<void(base::TimeTicks)> presentation_time_callback,
3395 base::TimeTicks swap_time,
3396 base::TimeTicks presentation_time) {
3397 DCHECK(!swap_time.is_null());
3398 bool presentation_time_is_valid =
3399 !presentation_time.is_null() && (presentation_time > swap_time);
3400 UMA_HISTOGRAM_BOOLEAN("PageLoad.Internal.Renderer.PresentationTime.Valid",
3401 presentation_time_is_valid);
3402 ReportTime(std::move(presentation_time_callback),
3403 presentation_time_is_valid ? presentation_time : swap_time);
3406 static void ReportTime(base::OnceCallback<void(base::TimeTicks)> callback,
3407 base::TimeTicks time) {
3409 std::move(callback).Run(time);
3412 #if BUILDFLAG(IS_APPLE)
3413 static void ReportErrorCode(
3414 base::OnceCallback<void(gfx::CALayerResult)> callback,
3415 gfx::CALayerResult error_code) {
3417 std::move(callback).Run(error_code);
3421 static void ReportSwapAndPresentationFailureOnTaskRunner(
3422 scoped_refptr<base::SingleThreadTaskRunner> task_runner,
3423 WebFrameWidgetImpl::PromiseCallbacks callbacks,
3424 base::TimeTicks failure_time) {
3425 if (!task_runner->BelongsToCurrentThread()) {
3426 PostCrossThreadTask(
3427 *task_runner, FROM_HERE,
3428 CrossThreadBindOnce(&ReportSwapAndPresentationFailureOnTaskRunner,
3429 task_runner, std::move(callbacks), failure_time));
3433 ReportTime(std::move(callbacks.swap_time_callback), failure_time);
3434 ReportTime(std::move(callbacks.presentation_time_callback), failure_time);
3435 #if BUILDFLAG(IS_APPLE)
3436 ReportErrorCode(std::move(callbacks.core_animation_error_code_callback),
3437 gfx::kCALayerUnknownDidNotSwap);
3441 WebFrameWidgetImpl::PromiseCallbacks promise_callbacks_;
3443 scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
3444 CrossThreadWeakHandle<WebFrameWidgetImpl> widget_;
3445 uint32_t frame_token_ = 0;
3448 void WebFrameWidgetImpl::NotifySwapAndPresentationTimeForTesting(
3449 PromiseCallbacks callbacks) {
3450 NotifySwapAndPresentationTime(std::move(callbacks));
3453 void WebFrameWidgetImpl::NotifyPresentationTimeInBlink(
3454 base::OnceCallback<void(base::TimeTicks)> presentation_callback) {
3455 NotifySwapAndPresentationTime(
3456 {.presentation_time_callback = std::move(presentation_callback)});
3459 void WebFrameWidgetImpl::NotifyPresentationTime(
3460 base::OnceCallback<void(base::TimeTicks)> presentation_callback) {
3461 NotifySwapAndPresentationTime(
3462 {.presentation_time_callback = std::move(presentation_callback)});
3465 #if BUILDFLAG(IS_APPLE)
3466 void WebFrameWidgetImpl::NotifyCoreAnimationErrorCode(
3467 base::OnceCallback<void(gfx::CALayerResult)>
3468 core_animation_error_code_callback) {
3469 NotifySwapAndPresentationTime(
3470 {.core_animation_error_code_callback =
3471 std::move(core_animation_error_code_callback)});
3475 void WebFrameWidgetImpl::NotifySwapAndPresentationTime(
3476 PromiseCallbacks callbacks) {
3477 if (!View()->does_composite())
3480 widget_base_->LayerTreeHost()->QueueSwapPromise(
3481 std::make_unique<ReportTimeSwapPromise>(std::move(callbacks),
3482 widget_base_->LayerTreeHost()
3483 ->GetTaskRunnerProvider()
3484 ->MainThreadTaskRunner(),
3488 void WebFrameWidgetImpl::WaitForDebuggerWhenShown() {
3489 local_root_->WaitForDebuggerWhenShown();
3492 void WebFrameWidgetImpl::SetTextZoomFactor(float text_zoom_factor) {
3493 local_root_->GetFrame()->SetTextZoomFactor(text_zoom_factor);
3496 float WebFrameWidgetImpl::TextZoomFactor() {
3497 return local_root_->GetFrame()->TextZoomFactor();
3500 void WebFrameWidgetImpl::SetMainFrameOverlayColor(SkColor color) {
3501 DCHECK(!local_root_->Parent());
3502 local_root_->GetFrame()->SetMainFrameColorOverlay(color);
3505 void WebFrameWidgetImpl::AddEditCommandForNextKeyEvent(const WebString& name,
3506 const WebString& value) {
3507 edit_commands_.push_back(mojom::blink::EditCommand::New(name, value));
3510 bool WebFrameWidgetImpl::HandleCurrentKeyboardEvent() {
3511 if (edit_commands_.empty()) {
3514 WebLocalFrame* frame = FocusedWebLocalFrameInWidget();
3516 frame = local_root_;
3517 bool did_execute_command = false;
3518 // Executing an edit command can run JS and we can end up reassigning
3519 // `edit_commands_` so move it to a stack variable before iterating on it.
3520 Vector<mojom::blink::EditCommandPtr> edit_commands =
3521 std::move(edit_commands_);
3522 for (const auto& command : edit_commands) {
3523 // In gtk and cocoa, it's possible to bind multiple edit commands to one
3524 // key (but it's the exception). Once one edit command is not executed, it
3525 // seems safest to not execute the rest.
3526 if (!frame->ExecuteCommand(command->name, command->value))
3528 did_execute_command = true;
3531 return did_execute_command;
3534 void WebFrameWidgetImpl::ClearEditCommands() {
3535 edit_commands_ = Vector<mojom::blink::EditCommandPtr>();
3538 WebTextInputInfo WebFrameWidgetImpl::TextInputInfo() {
3539 WebInputMethodController* controller = GetActiveWebInputMethodController();
3541 return WebTextInputInfo();
3542 return controller->TextInputInfo();
3545 ui::mojom::blink::VirtualKeyboardVisibilityRequest
3546 WebFrameWidgetImpl::GetLastVirtualKeyboardVisibilityRequest() {
3547 WebInputMethodController* controller = GetActiveWebInputMethodController();
3549 return ui::mojom::blink::VirtualKeyboardVisibilityRequest::NONE;
3550 return controller->GetLastVirtualKeyboardVisibilityRequest();
3553 bool WebFrameWidgetImpl::ShouldSuppressKeyboardForFocusedElement() {
3554 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
3557 return focused_frame->ShouldSuppressKeyboardForFocusedElement();
3560 void WebFrameWidgetImpl::GetEditContextBoundsInWindow(
3561 absl::optional<gfx::Rect>* edit_context_control_bounds,
3562 absl::optional<gfx::Rect>* edit_context_selection_bounds) {
3563 WebInputMethodController* controller = GetActiveWebInputMethodController();
3566 gfx::Rect control_bounds;
3567 gfx::Rect selection_bounds;
3568 controller->GetLayoutBounds(&control_bounds, &selection_bounds);
3569 *edit_context_control_bounds =
3570 widget_base_->BlinkSpaceToEnclosedDIPs(control_bounds);
3571 if (controller->IsEditContextActive()) {
3572 *edit_context_selection_bounds =
3573 widget_base_->BlinkSpaceToEnclosedDIPs(selection_bounds);
3577 int32_t WebFrameWidgetImpl::ComputeWebTextInputNextPreviousFlags() {
3578 WebInputMethodController* controller = GetActiveWebInputMethodController();
3581 return controller->ComputeWebTextInputNextPreviousFlags();
3584 void WebFrameWidgetImpl::ResetVirtualKeyboardVisibilityRequest() {
3585 WebInputMethodController* controller = GetActiveWebInputMethodController();
3588 controller->SetVirtualKeyboardVisibilityRequest(
3589 ui::mojom::blink::VirtualKeyboardVisibilityRequest::NONE);
3593 bool WebFrameWidgetImpl::GetSelectionBoundsInWindow(
3596 gfx::Rect* bounding_box,
3597 base::i18n::TextDirection* focus_dir,
3598 base::i18n::TextDirection* anchor_dir,
3599 bool* is_anchor_first) {
3600 if (ShouldDispatchImeEventsToPlugin()) {
3601 // TODO(kinaba) http://crbug.com/101101
3602 // Current Pepper IME API does not handle selection bounds. So we simply
3603 // use the caret position as an empty range for now. It will be updated
3604 // after Pepper API equips features related to surrounding text retrieval.
3605 gfx::Rect pepper_caret_in_dips = widget_base_->BlinkSpaceToEnclosedDIPs(
3606 GetFocusedPluginContainer()->GetPluginCaretBounds());
3607 if (pepper_caret_in_dips == *focus && pepper_caret_in_dips == *anchor)
3609 *focus = pepper_caret_in_dips;
3613 gfx::Rect focus_root_frame;
3614 gfx::Rect anchor_root_frame;
3615 gfx::Rect bounding_box_root_frame;
3616 CalculateSelectionBounds(focus_root_frame, anchor_root_frame,
3617 &bounding_box_root_frame);
3618 gfx::Rect focus_rect_in_dips =
3619 widget_base_->BlinkSpaceToEnclosedDIPs(gfx::Rect(focus_root_frame));
3620 gfx::Rect anchor_rect_in_dips =
3621 widget_base_->BlinkSpaceToEnclosedDIPs(gfx::Rect(anchor_root_frame));
3622 gfx::Rect bounding_box_in_dips = widget_base_->BlinkSpaceToEnclosedDIPs(
3623 gfx::Rect(bounding_box_root_frame));
3625 // if the bounds are the same return false.
3626 if (focus_rect_in_dips == *focus && anchor_rect_in_dips == *anchor)
3628 *focus = focus_rect_in_dips;
3629 *anchor = anchor_rect_in_dips;
3630 *bounding_box = bounding_box_in_dips;
3632 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
3635 focused_frame->SelectionTextDirection(*focus_dir, *anchor_dir);
3636 *is_anchor_first = focused_frame->IsSelectionAnchorFirst();
3640 void WebFrameWidgetImpl::ClearTextInputState() {
3641 widget_base_->ClearTextInputState();
3644 bool WebFrameWidgetImpl::IsPasting() {
3645 return widget_base_->is_pasting();
3648 bool WebFrameWidgetImpl::HandlingSelectRange() {
3649 return widget_base_->handling_select_range();
3652 void WebFrameWidgetImpl::SetFocus(bool focus) {
3653 widget_base_->SetFocus(
3654 focus ? mojom::blink::FocusState::kFocused
3655 : View()->IsActive()
3656 ? mojom::blink::FocusState::kNotFocusedAndActive
3657 : mojom::blink::FocusState::kNotFocusedAndNotActive);
3660 bool WebFrameWidgetImpl::HasFocus() {
3661 return widget_base_->has_focus();
3664 void WebFrameWidgetImpl::UpdateTooltipUnderCursor(const String& tooltip_text,
3665 TextDirection dir) {
3666 widget_base_->UpdateTooltipUnderCursor(tooltip_text, dir);
3669 void WebFrameWidgetImpl::UpdateTooltipFromKeyboard(const String& tooltip_text,
3671 const gfx::Rect& bounds) {
3672 widget_base_->UpdateTooltipFromKeyboard(tooltip_text, dir, bounds);
3675 void WebFrameWidgetImpl::ClearKeyboardTriggeredTooltip() {
3676 widget_base_->ClearKeyboardTriggeredTooltip();
3679 void WebFrameWidgetImpl::DidOverscroll(
3680 const gfx::Vector2dF& overscroll_delta,
3681 const gfx::Vector2dF& accumulated_overscroll,
3682 const gfx::PointF& position,
3683 const gfx::Vector2dF& velocity) {
3684 #if BUILDFLAG(IS_MAC)
3685 // On OSX the user can disable the elastic overscroll effect. If that's the
3686 // case, don't forward the overscroll notification.
3687 if (!widget_base_->LayerTreeHost()->GetSettings().enable_elastic_overscroll)
3691 cc::OverscrollBehavior overscroll_behavior =
3692 widget_base_->LayerTreeHost()->overscroll_behavior();
3693 if (!widget_base_->input_handler().DidOverscrollFromBlink(
3694 overscroll_delta, accumulated_overscroll, position, velocity,
3695 overscroll_behavior))
3698 // If we're currently handling an event, stash the overscroll data such that
3699 // it can be bundled in the event ack.
3700 if (mojom::blink::WidgetInputHandlerHost* host =
3701 widget_base_->widget_input_handler_manager()
3702 ->GetWidgetInputHandlerHost()) {
3703 host->DidOverscroll(mojom::blink::DidOverscrollParams::New(
3704 accumulated_overscroll, overscroll_delta, velocity, position,
3705 overscroll_behavior));
3709 void WebFrameWidgetImpl::InjectScrollbarGestureScroll(
3710 const gfx::Vector2dF& delta,
3711 ui::ScrollGranularity granularity,
3712 cc::ElementId scrollable_area_element_id,
3713 blink::WebInputEvent::Type injected_type) {
3714 // create a GestureScroll Event and post it to the compositor thread
3715 // TODO(crbug.com/1126098) use original input event's timestamp.
3716 // TODO(crbug.com/1082590) ensure continuity in scroll metrics collection
3717 base::TimeTicks now = base::TimeTicks::Now();
3718 std::unique_ptr<WebGestureEvent> gesture_event =
3719 WebGestureEvent::GenerateInjectedScrollbarGestureScroll(
3720 injected_type, now, gfx::PointF(0, 0), delta, granularity);
3721 if (injected_type == WebInputEvent::Type::kGestureScrollBegin) {
3722 gesture_event->data.scroll_begin.scrollable_area_element_id =
3723 scrollable_area_element_id.GetInternalValue();
3724 gesture_event->data.scroll_begin.main_thread_hit_tested_reasons =
3725 cc::MainThreadScrollingReason::kScrollbarScrolling;
3728 // Notifies TestWebFrameWidget of the injected event. Does nothing outside
3729 // of unit tests. This would happen in WidgetBase::QueueSyntheticEvent if
3730 // scroll unification were not enabled.
3731 WillQueueSyntheticEvent(
3732 WebCoalescedInputEvent(*gesture_event, ui::LatencyInfo()));
3734 widget_base_->widget_input_handler_manager()
3735 ->DispatchScrollGestureToCompositor(std::move(gesture_event));
3738 void WebFrameWidgetImpl::DidChangeCursor(const ui::Cursor& cursor) {
3739 widget_base_->SetCursor(cursor);
3742 bool WebFrameWidgetImpl::SetComposition(
3744 const Vector<ui::ImeTextSpan>& ime_text_spans,
3745 const gfx::Range& replacement_range,
3746 int selection_start,
3747 int selection_end) {
3748 WebInputMethodController* controller = GetActiveWebInputMethodController();
3752 return controller->SetComposition(
3753 text, ime_text_spans,
3754 replacement_range.IsValid()
3755 ? WebRange(base::checked_cast<int>(replacement_range.start()),
3756 base::checked_cast<int>(replacement_range.length()))
3758 selection_start, selection_end);
3761 void WebFrameWidgetImpl::CommitText(
3763 const Vector<ui::ImeTextSpan>& ime_text_spans,
3764 const gfx::Range& replacement_range,
3765 int relative_cursor_pos) {
3766 WebInputMethodController* controller = GetActiveWebInputMethodController();
3769 controller->CommitText(
3770 text, ime_text_spans,
3771 replacement_range.IsValid()
3772 ? WebRange(base::checked_cast<int>(replacement_range.start()),
3773 base::checked_cast<int>(replacement_range.length()))
3775 relative_cursor_pos);
3778 void WebFrameWidgetImpl::FinishComposingText(bool keep_selection) {
3779 WebInputMethodController* controller = GetActiveWebInputMethodController();
3782 controller->FinishComposingText(
3783 keep_selection ? WebInputMethodController::kKeepSelection
3784 : WebInputMethodController::kDoNotKeepSelection);
3787 bool WebFrameWidgetImpl::IsProvisional() {
3788 return LocalRoot()->IsProvisional();
3791 cc::ElementId WebFrameWidgetImpl::GetScrollableContainerIdAt(
3792 const gfx::PointF& point) {
3793 gfx::PointF hit_test_point = point;
3794 LocalFrameView* view = LocalRootImpl()->GetFrameView();
3795 hit_test_point.Scale(1 / view->InputEventsScaleFactor());
3796 return HitTestResultForRootFramePos(hit_test_point).GetScrollableContainer();
3799 bool WebFrameWidgetImpl::ShouldHandleImeEvents() {
3800 if (ForMainFrame()) {
3803 // TODO(ekaramad): main frame widget returns true only if it has focus.
3804 // We track page focus in all WebViews on the page but the WebFrameWidgets
3805 // corresponding to child local roots do not get the update. For now, this
3806 // method returns true when the WebFrameWidget is for a child local frame,
3807 // i.e., IME events will be processed regardless of page focus. We should
3808 // revisit this after page focus for OOPIFs has been fully resolved
3809 // (https://crbug.com/689777).
3810 return LocalRootImpl();
3814 void WebFrameWidgetImpl::SetEditCommandsForNextKeyEvent(
3815 Vector<mojom::blink::EditCommandPtr> edit_commands) {
3816 edit_commands_ = std::move(edit_commands);
3819 void WebFrameWidgetImpl::FocusChangeComplete() {
3820 blink::WebLocalFrame* focused = LocalRoot()->View()->FocusedFrame();
3822 if (focused && focused->AutofillClient())
3823 focused->AutofillClient()->DidCompleteFocusChangeInFrame();
3826 void WebFrameWidgetImpl::ShowVirtualKeyboardOnElementFocus() {
3827 widget_base_->ShowVirtualKeyboardOnElementFocus();
3830 #if BUILDFLAG(IS_EFL)
3831 void WebFrameWidgetImpl::DidUpdateTextOfFocusedElementByNonUserInput() {
3832 widget_base_->DidUpdateTextOfFocusedElementByNonUserInput();
3835 void WebFrameWidgetImpl::ProcessTouchAction(WebTouchAction touch_action) {
3836 widget_base_->ProcessTouchAction(touch_action);
3839 void WebFrameWidgetImpl::SetPanAction(mojom::blink::PanAction pan_action) {
3840 if (!widget_base_->widget_input_handler_manager())
3842 mojom::blink::WidgetInputHandlerHost* host =
3843 widget_base_->widget_input_handler_manager()->GetWidgetInputHandlerHost();
3846 host->SetPanAction(pan_action);
3849 void WebFrameWidgetImpl::DidHandleGestureEvent(const WebGestureEvent& event) {
3850 #if BUILDFLAG(IS_ANDROID) || defined(USE_AURA) || BUILDFLAG(IS_IOS)
3851 if (event.GetType() == WebInputEvent::Type::kGestureTap) {
3852 widget_base_->ShowVirtualKeyboard();
3853 } else if (event.GetType() == WebInputEvent::Type::kGestureLongPress) {
3854 WebInputMethodController* controller = GetActiveWebInputMethodController();
3855 if (!controller || controller->TextInputInfo().value.IsEmpty())
3856 widget_base_->UpdateTextInputState();
3858 widget_base_->ShowVirtualKeyboard();
3860 #elif BUILDFLAG(IS_EFL)
3864 if ((event.GetType() == WebInputEvent::Type::kGestureTap) ||
3865 (event.GetType() == WebInputEvent::Type::kGestureLongPress)) {
3866 widget_base_->ShowVirtualKeyboard();
3871 void WebFrameWidgetImpl::SetHasPointerRawUpdateEventHandlers(
3872 bool has_handlers) {
3873 widget_base_->widget_input_handler_manager()
3874 ->input_event_queue()
3875 ->HasPointerRawUpdateEventHandlers(has_handlers);
3878 void WebFrameWidgetImpl::SetNeedsLowLatencyInput(bool needs_low_latency) {
3879 widget_base_->widget_input_handler_manager()
3880 ->input_event_queue()
3881 ->SetNeedsLowLatency(needs_low_latency);
3884 void WebFrameWidgetImpl::RequestUnbufferedInputEvents() {
3885 widget_base_->widget_input_handler_manager()
3886 ->input_event_queue()
3887 ->RequestUnbufferedInputEvents();
3890 void WebFrameWidgetImpl::SetNeedsUnbufferedInputForDebugger(bool unbuffered) {
3891 widget_base_->widget_input_handler_manager()
3892 ->input_event_queue()
3893 ->SetNeedsUnbufferedInputForDebugger(unbuffered);
3896 void WebFrameWidgetImpl::DidNavigate() {
3897 // The input handler wants to know about navigation so that it can
3898 // suppress input until the newly navigated page has a committed frame.
3899 // It also resets the state for UMA reporting of input arrival with respect
3900 // to document lifecycle.
3901 if (!widget_base_->widget_input_handler_manager())
3903 widget_base_->widget_input_handler_manager()->DidNavigate();
3906 void WebFrameWidgetImpl::FlushInputForTesting(base::OnceClosure done_callback) {
3907 widget_base_->widget_input_handler_manager()->FlushEventQueuesForTesting(
3908 std::move(done_callback));
3911 void WebFrameWidgetImpl::SetMouseCapture(bool capture) {
3912 if (mojom::blink::WidgetInputHandlerHost* host =
3913 widget_base_->widget_input_handler_manager()
3914 ->GetWidgetInputHandlerHost()) {
3915 host->SetMouseCapture(capture);
3919 gfx::Range WebFrameWidgetImpl::CompositionRange() {
3920 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
3921 if (!focused_frame || ShouldDispatchImeEventsToPlugin())
3922 return gfx::Range::InvalidRange();
3924 blink::WebInputMethodController* controller =
3925 focused_frame->GetInputMethodController();
3926 WebRange web_range = controller->CompositionRange();
3927 if (web_range.IsNull())
3928 return gfx::Range::InvalidRange();
3929 return gfx::Range(web_range.StartOffset(), web_range.EndOffset());
3932 void WebFrameWidgetImpl::GetCompositionCharacterBoundsInWindow(
3933 Vector<gfx::Rect>* bounds_in_dips) {
3934 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
3935 if (!focused_frame || ShouldDispatchImeEventsToPlugin())
3937 blink::WebInputMethodController* controller =
3938 focused_frame->GetInputMethodController();
3939 blink::WebVector<gfx::Rect> bounds_from_blink;
3940 if (!controller->GetCompositionCharacterBounds(bounds_from_blink))
3943 for (auto& rect : bounds_from_blink) {
3944 bounds_in_dips->push_back(widget_base_->BlinkSpaceToEnclosedDIPs(rect));
3950 void GetLineBounds(Vector<gfx::QuadF>& line_quads,
3951 TextControlInnerEditorElement* inner_editor) {
3952 for (const Node& node : NodeTraversal::DescendantsOf(*inner_editor)) {
3953 if (!node.GetLayoutObject() || !node.GetLayoutObject()->IsText()) {
3956 node.GetLayoutObject()->AbsoluteQuads(line_quads,
3957 kApplyRemoteMainFrameTransform);
3963 Vector<gfx::Rect> WebFrameWidgetImpl::CalculateVisibleLineBoundsOnScreen() {
3964 Vector<gfx::Rect> bounds_in_dips;
3965 Element* focused_element = FocusedElement();
3966 if (!focused_element) {
3967 return bounds_in_dips;
3969 TextControlElement* text_control = ToTextControlOrNull(focused_element);
3970 if (!text_control || text_control->IsDisabledOrReadOnly() ||
3971 text_control->Value().empty() || !text_control->GetLayoutObject()) {
3972 return bounds_in_dips;
3975 Vector<gfx::QuadF> bounds_from_blink;
3976 GetLineBounds(bounds_from_blink, text_control->InnerEditorElement());
3978 gfx::Rect screen = GetPage()->GetVisualViewport().VisibleContentRect();
3979 for (auto& quad : bounds_from_blink) {
3980 gfx::Rect bounding_box = gfx::ToRoundedRect(quad.BoundingBox());
3981 bounding_box.Intersect(screen);
3982 if (bounding_box.IsEmpty()) {
3986 bounds_in_dips.push_back(
3987 focused_element->GetLayoutObject()->GetFrameView()->FrameToScreen(
3990 return bounds_in_dips;
3993 Vector<gfx::Rect>& WebFrameWidgetImpl::GetVisibleLineBoundsOnScreen() {
3994 return input_visible_line_bounds_;
3997 void WebFrameWidgetImpl::UpdateLineBounds() {
3998 Vector<gfx::Rect> line_bounds = CalculateVisibleLineBoundsOnScreen();
3999 if (line_bounds == input_visible_line_bounds_) {
4002 input_visible_line_bounds_.swap(line_bounds);
4003 if (mojom::blink::WidgetInputHandlerHost* host =
4004 widget_base_->widget_input_handler_manager()
4005 ->GetWidgetInputHandlerHost()) {
4006 host->ImeCompositionRangeChanged(gfx::Range::InvalidRange(), absl::nullopt,
4007 input_visible_line_bounds_);
4011 void WebFrameWidgetImpl::AddImeTextSpansToExistingText(
4014 const Vector<ui::ImeTextSpan>& ime_text_spans) {
4015 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
4018 focused_frame->AddImeTextSpansToExistingText(ime_text_spans, start, end);
4021 Vector<ui::mojom::blink::ImeTextSpanInfoPtr>
4022 WebFrameWidgetImpl::GetImeTextSpansInfo(
4023 const WebVector<ui::ImeTextSpan>& ime_text_spans) {
4024 auto* focused_frame = FocusedWebLocalFrameInWidget();
4026 return Vector<ui::mojom::blink::ImeTextSpanInfoPtr>();
4028 Vector<ui::mojom::blink::ImeTextSpanInfoPtr> ime_text_spans_info;
4030 for (const auto& ime_text_span : ime_text_spans) {
4032 auto length = base::checked_cast<wtf_size_t>(ime_text_span.end_offset -
4033 ime_text_span.start_offset);
4034 focused_frame->FirstRectForCharacterRange(
4035 base::checked_cast<wtf_size_t>(ime_text_span.start_offset), length,
4038 ime_text_spans_info.push_back(ui::mojom::blink::ImeTextSpanInfo::New(
4039 ime_text_span, widget_base_->BlinkSpaceToEnclosedDIPs(rect)));
4041 return ime_text_spans_info;
4044 void WebFrameWidgetImpl::ClearImeTextSpansByType(uint32_t start,
4046 ui::ImeTextSpan::Type type) {
4047 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
4050 focused_frame->ClearImeTextSpansByType(type, start, end);
4053 void WebFrameWidgetImpl::SetCompositionFromExistingText(
4056 const Vector<ui::ImeTextSpan>& ime_text_spans) {
4057 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
4060 focused_frame->SetCompositionFromExistingText(start, end, ime_text_spans);
4063 void WebFrameWidgetImpl::ExtendSelectionAndDelete(int32_t before,
4065 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
4068 focused_frame->ExtendSelectionAndDelete(before, after);
4071 void WebFrameWidgetImpl::ExtendSelectionAndReplace(
4074 const String& replacement_text) {
4075 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
4076 if (!focused_frame) {
4079 focused_frame->ExtendSelectionAndReplace(base::checked_cast<int>(before),
4080 base::checked_cast<int>(after),
4084 void WebFrameWidgetImpl::DeleteSurroundingText(int32_t before, int32_t after) {
4085 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
4088 focused_frame->DeleteSurroundingText(before, after);
4091 void WebFrameWidgetImpl::DeleteSurroundingTextInCodePoints(int32_t before,
4093 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
4096 focused_frame->DeleteSurroundingTextInCodePoints(before, after);
4099 void WebFrameWidgetImpl::SetEditableSelectionOffsets(int32_t start,
4101 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
4104 focused_frame->SetEditableSelectionOffsets(start, end);
4107 void WebFrameWidgetImpl::ExecuteEditCommand(const String& command,
4108 const String& value) {
4109 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
4112 focused_frame->ExecuteCommand(command, value);
4115 void WebFrameWidgetImpl::Undo() {
4116 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
4119 focused_frame->ExecuteCommand(WebString::FromLatin1("Undo"));
4122 void WebFrameWidgetImpl::Redo() {
4123 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
4126 focused_frame->ExecuteCommand(WebString::FromLatin1("Redo"));
4129 void WebFrameWidgetImpl::Cut() {
4130 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
4133 focused_frame->ExecuteCommand(WebString::FromLatin1("Cut"));
4136 void WebFrameWidgetImpl::Copy() {
4137 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
4140 focused_frame->ExecuteCommand(WebString::FromLatin1("Copy"));
4143 void WebFrameWidgetImpl::CopyToFindPboard() {
4144 #if BUILDFLAG(IS_MAC)
4145 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
4148 To<WebLocalFrameImpl>(focused_frame)->CopyToFindPboard();
4152 void WebFrameWidgetImpl::CenterSelection() {
4153 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
4154 if (!focused_frame) {
4157 To<WebLocalFrameImpl>(focused_frame)->CenterSelection();
4160 void WebFrameWidgetImpl::Paste() {
4161 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
4164 focused_frame->ExecuteCommand(WebString::FromLatin1("Paste"));
4167 void WebFrameWidgetImpl::PasteAndMatchStyle() {
4168 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
4171 focused_frame->ExecuteCommand(WebString::FromLatin1("PasteAndMatchStyle"));
4174 void WebFrameWidgetImpl::Delete() {
4175 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
4178 focused_frame->ExecuteCommand(WebString::FromLatin1("Delete"));
4181 void WebFrameWidgetImpl::SelectAll() {
4182 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
4185 focused_frame->ExecuteCommand(WebString::FromLatin1("SelectAll"));
4188 void WebFrameWidgetImpl::CollapseSelection() {
4189 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
4192 const blink::WebRange& range =
4193 focused_frame->GetInputMethodController()->GetSelectionOffsets();
4197 focused_frame->SelectRange(blink::WebRange(range.EndOffset(), 0),
4198 blink::WebLocalFrame::kHideSelectionHandle,
4199 mojom::blink::SelectionMenuBehavior::kHide,
4200 blink::WebLocalFrame::kSelectionDoNotSetFocus);
4203 void WebFrameWidgetImpl::Replace(const String& word) {
4204 auto* focused_frame = FocusedWebLocalFrameInWidget();
4207 if (!focused_frame->HasSelection()) {
4208 focused_frame->SelectAroundCaret(mojom::blink::SelectionGranularity::kWord,
4209 /*should_show_handle=*/false,
4210 /*should_show_context_menu=*/false);
4212 focused_frame->ReplaceSelection(word);
4213 // If the resulting selection is not actually a change in selection, we do not
4214 // need to explicitly notify about the selection change.
4215 focused_frame->Client()->SyncSelectionIfRequired(
4216 blink::SyncCondition::kNotForced);
4219 void WebFrameWidgetImpl::ReplaceMisspelling(const String& word) {
4220 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
4223 if (!focused_frame->HasSelection())
4225 focused_frame->ReplaceMisspelledRange(word);
4228 void WebFrameWidgetImpl::SelectRange(const gfx::Point& base_in_dips,
4229 const gfx::Point& extent_in_dips) {
4230 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
4233 focused_frame->SelectRange(
4234 widget_base_->DIPsToRoundedBlinkSpace(base_in_dips),
4235 widget_base_->DIPsToRoundedBlinkSpace(extent_in_dips));
4238 void WebFrameWidgetImpl::AdjustSelectionByCharacterOffset(
4241 mojom::blink::SelectionMenuBehavior selection_menu_behavior) {
4242 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
4245 blink::WebRange range =
4246 focused_frame->GetInputMethodController()->GetSelectionOffsets();
4250 // Sanity checks to disallow empty and out of range selections.
4251 if (start - end > range.length() || range.StartOffset() + start < 0)
4254 // A negative adjust amount moves the selection towards the beginning of
4255 // the document, a positive amount moves the selection towards the end of
4257 focused_frame->SelectRange(blink::WebRange(range.StartOffset() + start,
4258 range.length() + end - start),
4259 blink::WebLocalFrame::kPreserveHandleVisibility,
4260 selection_menu_behavior,
4261 blink::WebLocalFrame::kSelectionSetFocus);
4264 void WebFrameWidgetImpl::MoveRangeSelectionExtent(
4265 const gfx::Point& extent_in_dips) {
4266 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
4269 focused_frame->MoveRangeSelectionExtent(
4270 widget_base_->DIPsToRoundedBlinkSpace(extent_in_dips));
4273 void WebFrameWidgetImpl::ScrollFocusedEditableNodeIntoView() {
4274 WebLocalFrameImpl* local_frame = FocusedWebLocalFrameInWidget();
4278 // OnSynchronizeVisualProperties does not call DidChangeVisibleViewport
4279 // on OOPIFs. Since we are starting a new scroll operation now, call
4280 // DidChangeVisibleViewport to ensure that we don't assume the element
4281 // is already in view and ignore the scroll.
4282 local_frame->ResetHasScrolledFocusedEditableIntoView();
4283 local_frame->ScrollFocusedEditableElementIntoView();
4286 void WebFrameWidgetImpl::WaitForPageScaleAnimationForTesting(
4287 WaitForPageScaleAnimationForTestingCallback callback) {
4288 DCHECK(ForMainFrame());
4289 DCHECK(LocalRootImpl()->GetFrame()->IsOutermostMainFrame());
4290 page_scale_animation_for_testing_callback_ = std::move(callback);
4293 void WebFrameWidgetImpl::ZoomToFindInPageRect(
4294 const gfx::Rect& rect_in_root_frame) {
4295 if (ForMainFrame()) {
4296 View()->ZoomToFindInPageRect(rect_in_root_frame);
4298 GetAssociatedFrameWidgetHost()->ZoomToFindInPageRectInMainFrame(
4299 rect_in_root_frame);
4303 void WebFrameWidgetImpl::MoveCaret(const gfx::Point& point_in_dips) {
4304 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
4307 focused_frame->MoveCaretSelection(
4308 widget_base_->DIPsToRoundedBlinkSpace(point_in_dips));
4311 void WebFrameWidgetImpl::SelectAroundCaret(
4312 mojom::blink::SelectionGranularity granularity,
4313 bool should_show_handle,
4314 bool should_show_context_menu,
4315 SelectAroundCaretCallback callback) {
4316 auto* focused_frame = FocusedWebLocalFrameInWidget();
4317 if (!focused_frame) {
4318 std::move(callback).Run(std::move(nullptr));
4322 int extended_start_adjust = 0;
4323 int extended_end_adjust = 0;
4324 int word_start_adjust = 0;
4325 int word_end_adjust = 0;
4326 blink::WebRange initial_range = focused_frame->SelectionRange();
4327 SetHandlingInputEvent(true);
4329 if (initial_range.IsNull()) {
4330 std::move(callback).Run(std::move(nullptr));
4334 // If the requested granularity is not word, still calculate the hypothetical
4335 // word selection offsets. This is needed for contextual search to support
4336 // legacy semantics for the word that was tapped.
4337 blink::WebRange word_range;
4338 if (granularity != mojom::blink::SelectionGranularity::kWord) {
4339 word_range = focused_frame->GetWordSelectionRangeAroundCaret();
4342 // Select around the caret at the specified |granularity|.
4343 if (!focused_frame->SelectAroundCaret(granularity, should_show_handle,
4344 should_show_context_menu)) {
4345 std::move(callback).Run(std::move(nullptr));
4349 blink::WebRange extended_range = focused_frame->SelectionRange();
4350 DCHECK(!extended_range.IsNull());
4351 extended_start_adjust =
4352 extended_range.StartOffset() - initial_range.StartOffset();
4353 extended_end_adjust = extended_range.EndOffset() - initial_range.EndOffset();
4355 if (granularity == mojom::blink::SelectionGranularity::kWord) {
4356 // Since the requested granularity was word, simply set the word offset
4357 // to be the same as the extended offset values.
4358 word_start_adjust = extended_start_adjust;
4359 word_end_adjust = extended_end_adjust;
4361 // Calculate the word offset compared to the initial selection (caret).
4362 DCHECK(!word_range.IsNull());
4363 word_start_adjust = word_range.StartOffset() - initial_range.StartOffset();
4364 word_end_adjust = word_range.EndOffset() - initial_range.EndOffset();
4367 SetHandlingInputEvent(false);
4368 auto result = mojom::blink::SelectAroundCaretResult::New();
4369 result->extended_start_adjust = extended_start_adjust;
4370 result->extended_end_adjust = extended_end_adjust;
4371 result->word_start_adjust = word_start_adjust;
4372 result->word_end_adjust = word_end_adjust;
4373 std::move(callback).Run(std::move(result));
4376 void WebFrameWidgetImpl::ForEachRemoteFrameControlledByWidget(
4377 base::FunctionRef<void(RemoteFrame*)> callback) {
4378 ForEachRemoteFrameChildrenControlledByWidget(local_root_->GetFrame(),
4382 void WebFrameWidgetImpl::CalculateSelectionBounds(
4383 gfx::Rect& anchor_root_frame,
4384 gfx::Rect& focus_root_frame,
4385 gfx::Rect* bounding_box_in_root_frame) {
4386 const LocalFrame* local_frame = FocusedLocalFrameInWidget();
4392 auto& selection = local_frame->Selection();
4393 if (!selection.ComputeAbsoluteBounds(anchor, focus))
4396 // Apply the visual viewport for main frames this will apply the page scale.
4397 // For subframes it will just be a 1:1 transformation and the browser
4398 // will then apply later transformations to these rects.
4399 VisualViewport& visual_viewport = GetPage()->GetVisualViewport();
4400 anchor_root_frame = visual_viewport.RootFrameToViewport(
4401 local_frame->View()->ConvertToRootFrame(anchor));
4402 focus_root_frame = visual_viewport.RootFrameToViewport(
4403 local_frame->View()->ConvertToRootFrame(focus));
4405 // Calculate the bounding box of the selection area.
4406 if (bounding_box_in_root_frame) {
4408 CreateRange(selection.GetSelectionInDOMTree().ComputeRange());
4409 const gfx::Rect bounding_box = ToEnclosingRect(range->BoundingRect());
4411 *bounding_box_in_root_frame = visual_viewport.RootFrameToViewport(
4412 local_frame->View()->ConvertToRootFrame(bounding_box));
4416 const viz::LocalSurfaceId& WebFrameWidgetImpl::LocalSurfaceIdFromParent() {
4417 return widget_base_->local_surface_id_from_parent();
4420 cc::LayerTreeHost* WebFrameWidgetImpl::LayerTreeHost() {
4421 return widget_base_->LayerTreeHost();
4424 cc::LayerTreeHost* WebFrameWidgetImpl::LayerTreeHostForTesting() const {
4425 return widget_base_->LayerTreeHost();
4428 ScreenMetricsEmulator* WebFrameWidgetImpl::DeviceEmulator() {
4429 return device_emulator_.Get();
4432 bool WebFrameWidgetImpl::AutoResizeMode() {
4433 return View()->AutoResizeMode();
4436 void WebFrameWidgetImpl::SetScreenMetricsEmulationParameters(
4438 const DeviceEmulationParams& params) {
4440 View()->ActivateDevToolsTransform(params);
4442 View()->DeactivateDevToolsTransform();
4445 void WebFrameWidgetImpl::SetScreenInfoAndSize(
4446 const display::ScreenInfos& screen_infos,
4447 const gfx::Size& widget_size_in_dips,
4448 const gfx::Size& visible_viewport_size_in_dips) {
4449 // Emulation happens on regular main frames which don't use auto-resize mode.
4450 DCHECK(!AutoResizeMode());
4452 UpdateScreenInfo(screen_infos);
4453 widget_base_->SetVisibleViewportSizeInDIPs(visible_viewport_size_in_dips);
4454 Resize(widget_base_->DIPsToCeiledBlinkSpace(widget_size_in_dips));
4457 float WebFrameWidgetImpl::GetCompositingScaleFactor() {
4458 return compositing_scale_factor_;
4461 const cc::LayerTreeDebugState& WebFrameWidgetImpl::GetLayerTreeDebugState() {
4462 return widget_base_->LayerTreeHost()->GetDebugState();
4465 void WebFrameWidgetImpl::SetLayerTreeDebugState(
4466 const cc::LayerTreeDebugState& state) {
4467 widget_base_->LayerTreeHost()->SetDebugState(state);
4470 void WebFrameWidgetImpl::NotifyCompositingScaleFactorChanged(
4471 float compositing_scale_factor) {
4472 compositing_scale_factor_ = compositing_scale_factor;
4474 // Update the scale factor for remote frames which in turn depends on the
4475 // compositing scale factor set in the widget.
4476 ForEachRemoteFrameControlledByWidget([](RemoteFrame* remote_frame) {
4477 // Only RemoteFrames with a local parent frame participate in compositing
4478 // (and thus have a view).
4479 if (remote_frame->View())
4480 remote_frame->View()->UpdateCompositingScaleFactor();
4484 void WebFrameWidgetImpl::NotifyPageScaleFactorChanged(
4485 float page_scale_factor,
4486 bool is_pinch_gesture_active) {
4487 // Store the value to give to any new RemoteFrame that will be created as a
4488 // descendant of this widget.
4489 page_scale_factor_in_mainframe_ = page_scale_factor;
4490 is_pinch_gesture_active_in_mainframe_ = is_pinch_gesture_active;
4491 // Push the page scale factor down to any child RemoteFrames.
4492 // TODO(danakj): This ends up setting the page scale factor in the
4493 // RenderWidgetHost of the child WebFrameWidgetImpl, so that it can bounce
4494 // the value down to its WebFrameWidgetImpl. Since this is essentially a
4495 // global value per-page, we could instead store it once in the browser
4496 // (such as in RenderViewHost) and distribute it to each WebFrameWidgetImpl
4498 ForEachRemoteFrameControlledByWidget(
4499 [page_scale_factor, is_pinch_gesture_active](RemoteFrame* remote_frame) {
4500 remote_frame->PageScaleFactorChanged(page_scale_factor,
4501 is_pinch_gesture_active);
4505 void WebFrameWidgetImpl::SetPageScaleStateAndLimits(
4506 float page_scale_factor,
4507 bool is_pinch_gesture_active,
4510 widget_base_->LayerTreeHost()->SetPageScaleFactorAndLimits(page_scale_factor,
4513 // Only propagate page scale from the main frame.
4514 if (ForMainFrame()) {
4515 // If page scale hasn't changed, then just return without notifying
4516 // the remote frames.
4517 if (page_scale_factor == page_scale_factor_in_mainframe_ &&
4518 is_pinch_gesture_active == is_pinch_gesture_active_in_mainframe_) {
4522 NotifyPageScaleFactorChanged(page_scale_factor, is_pinch_gesture_active);
4526 void WebFrameWidgetImpl::UpdateViewportDescription(
4527 const ViewportDescription& viewport) {
4528 bool is_device_width = viewport.max_width.IsDeviceWidth();
4529 bool is_zoom_at_least_one = viewport.zoom >= 1.0 || viewport.min_zoom >= 1;
4530 widget_base_->LayerTreeHost()->UpdateViewportIsMobileOptimized(
4531 (is_device_width && is_zoom_at_least_one) ||
4532 (is_device_width && !viewport.zoom_is_explicit) ||
4533 (viewport.max_width.IsAuto() && is_zoom_at_least_one));
4536 bool WebFrameWidgetImpl::UpdateScreenRects(
4537 const gfx::Rect& widget_screen_rect,
4538 const gfx::Rect& window_screen_rect) {
4539 if (!device_emulator_)
4541 device_emulator_->OnUpdateScreenRects(widget_screen_rect, window_screen_rect);
4545 #if BUILDFLAG(IS_EFL)
4546 void WebFrameWidgetImpl::GetContentSnapshot(const gfx::Rect& snapshot_rect,
4547 float page_scale_factor,
4548 SkBitmap* snapshot) {
4549 WebView* view = View();
4550 if (!view || !view->MainFrame()) {
4551 LOG(ERROR) << "SoftBitmap:Capture Invalid view";
4555 if (view->HasAcceleratedCanvasWithinViewport()) {
4557 << "SoftBitmap:Capture avoided for WebGl/Cavas2D content on viewport";
4561 if (view->MainFrameWidget()->Size().IsEmpty()) {
4562 LOG(ERROR) << "SoftBitmap:Capture Invalid size";
4566 snapshot->allocPixels(SkImageInfo::MakeN32Premul(snapshot_rect.width(),
4567 snapshot_rect.height()));
4568 SkCanvas canvas(*snapshot);
4569 if (!view->PaintSoftBitmap(&canvas, snapshot_rect)) {
4570 LOG(ERROR) << "SoftBitmap:Capture PaintSoftBitmap failed";
4574 *snapshot = skia::ImageOperations::Resize(
4575 *snapshot, skia::ImageOperations::RESIZE_GOOD,
4576 page_scale_factor * snapshot->width(),
4577 page_scale_factor * snapshot->height());
4580 SkColor WebFrameWidgetImpl::GetBackgroundColor() {
4581 SkColor bg_color = View()->BackgroundColor();
4585 gfx::RectF WebFrameWidgetImpl::UpdateFocusedNodeBounds() {
4586 Element* element = FocusedElement();
4588 return gfx::RectF();
4590 WebElement web_element = WebElement(element);
4592 if (!web_element.IsNull() && web_element.IsElementNode()) {
4593 gfx::RectF focused_node_bounds_scaled = gfx::ScaleRect(
4594 gfx::RectF(web_element.BoundsInWidget()), View()->PageScaleFactor());
4595 return focused_node_bounds_scaled;
4597 return gfx::RectF();
4600 void WebFrameWidgetImpl::SetLongPollingGlobalTimeout(uint64_t timeout) {
4601 WebView* view = View();
4603 view->SetLongPollingGlobalTimeout(timeout);
4606 bool WebFrameWidgetImpl::QueryInputType() {
4607 Element* element = FocusedElement();
4611 auto* input_element = DynamicTo<HTMLInputElement>(element);
4612 if (input_element && input_element->type() == input_type_names::kPassword)
4618 void WebFrameWidgetImpl::SelectClosestWord(uint32_t x, uint32_t y) {
4622 blink::WebFrame* main_frame = View()->MainFrame();
4626 SetHandlingInputEvent(true);
4627 main_frame->SelectClosestWord(x, y);
4628 SetHandlingInputEvent(false);
4631 void WebFrameWidgetImpl::SelectFocusedLink() {
4632 Element* element = FocusedElement();
4636 WebElement web_element = WebElement(element);
4637 if (web_element.IsNull() || web_element.IsEditable() ||
4638 web_element.HasHTMLTagName("select")) {
4642 gfx::Rect box_rect = web_element.BoundsInWidget();
4643 if (box_rect.IsEmpty())
4649 float page_scale = View()->PageScaleFactor();
4650 int focused_x = (box_rect.x() + box_rect.width() / 2) / page_scale;
4651 int focused_y = (box_rect.y() + box_rect.height() / 2) / page_scale;
4653 SelectClosestWord(focused_x, focused_y);
4656 gfx::Rect WebFrameWidgetImpl::RequestSelectionRect() {
4660 return gfx::Rect(View()->CurrentSelectionRect());
4663 void WebFrameWidgetImpl::ResetLastInteractedElements() {
4664 #if defined(TIZEN_AUTOFILL_FW)
4668 if (auto* frame = View()->FocusedFrame())
4669 frame->ResetLastInteractedElements();
4673 void WebFrameWidgetImpl::PrintToPdf(uint32_t width,
4675 const base::FilePath& filename) {
4676 WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget();
4677 if (!focused_frame || !focused_frame->Client())
4680 focused_frame->Client()->PrintToPdf(
4681 width, height, filename,
4682 content::RenderFrame::FromWebFrame(focused_frame));
4685 void WebFrameWidgetImpl::SetMainFrameScrollbarVisible(bool visible) {
4686 blink::WebView* view = View();
4687 if (!view || !view->MainFrame() || !view->MainFrame()->ToWebLocalFrame())
4690 view->MainFrame()->ToWebLocalFrame()->ChangeScrollbarVisibility(visible);
4693 bool WebFrameWidgetImpl::RequestMainFrameScrollbarVisible(bool& visible) {
4694 blink::WebView* view = View();
4695 if (!view || !view->MainFrame() || !view->MainFrame()->ToWebLocalFrame())
4698 auto local_frame = view->MainFrame()->ToWebLocalFrame();
4699 visible = local_frame->HasHorizontalScrollbar() ||
4700 local_frame->HasVerticalScrollbar();
4704 #if BUILDFLAG(IS_TIZEN_TV)
4705 void WebFrameWidgetImpl::SetFloatVideoWindowState(bool enabled) {
4706 View()->SetFloatVideoWindowState(enabled);
4709 void WebFrameWidgetImpl::SuspendNetworkLoading() {
4710 View()->SuspendNetworkLoading();
4713 void WebFrameWidgetImpl::ResumeNetworkLoading() {
4714 View()->ResumeNetworkLoading();
4716 #endif // IS_TIZEN_TV
4719 #if BUILDFLAG(IS_TIZEN)
4720 void WebFrameWidgetImpl::SetMaxRefreshRate(uint32_t max_refresh_rate) {
4721 widget_base_->SetMaxRefreshRate(max_refresh_rate);
4725 #if BUILDFLAG(IS_TIZEN)
4726 void WebFrameWidgetImpl::DidChangeLoadState(bool is_loading) {
4727 widget_base_->LayerTreeHost()->DidChangeLoadState(is_loading);
4731 void WebFrameWidgetImpl::OrientationChanged() {
4732 local_root_->SendOrientationChangeEvent();
4735 #if BUILDFLAG(IS_TIZEN)
4736 void WebFrameWidgetImpl::PauseScheduledTasks() {
4737 View()->PauseScheduledTasks();
4740 void WebFrameWidgetImpl::UnPauseScheduledTasks() {
4741 View()->UnpauseScheduledTasks();
4745 void WebFrameWidgetImpl::DidUpdateSurfaceAndScreen(
4746 const display::ScreenInfos& previous_original_screen_infos) {
4747 display::ScreenInfo screen_info = widget_base_->GetScreenInfo();
4748 View()->SetZoomFactorForDeviceScaleFactor(screen_info.device_scale_factor);
4750 if (ShouldAutoDetermineCompositingToLCDTextSetting()) {
4751 // This causes compositing state to be modified which dirties the
4752 // document lifecycle. Android Webview relies on the document
4753 // lifecycle being clean after the RenderWidget is initialized, in
4754 // order to send IPCs that query and change compositing state. So
4755 // WebFrameWidgetImpl::Resize() must come after this call, as it runs the
4756 // entire document lifecycle.
4757 View()->GetSettings()->SetLCDTextPreference(
4758 widget_base_->ComputeLCDTextPreference());
4761 // When the device scale changes, the size and position of the popup would
4762 // need to be adjusted, which we can't do. Just close the popup, which is
4763 // also consistent with page zoom and resize behavior.
4764 display::ScreenInfos original_screen_infos = GetOriginalScreenInfos();
4765 if (previous_original_screen_infos.current().device_scale_factor !=
4766 original_screen_infos.current().device_scale_factor) {
4767 View()->CancelPagePopup();
4770 const bool window_screen_has_changed =
4771 !Screen::AreWebExposedScreenPropertiesEqual(
4772 previous_original_screen_infos.current(),
4773 original_screen_infos.current());
4775 // Update Screens interface data before firing any events. The API is designed
4776 // to offer synchronous access to the most up-to-date cached screen
4777 // information when a change event is fired. It is not required but it
4778 // is convenient to have all ScreenDetailed objects be up to date when any
4779 // window.screen events are fired as well.
4780 ForEachLocalFrameControlledByWidget(
4781 LocalRootImpl()->GetFrame(),
4782 [&original_screen_infos,
4783 window_screen_has_changed](WebLocalFrameImpl* local_frame) {
4784 auto* screen = local_frame->GetFrame()->DomWindow()->screen();
4785 screen->UpdateDisplayId(original_screen_infos.current().display_id);
4786 CoreInitializer::GetInstance().DidUpdateScreens(
4787 *local_frame->GetFrame(), original_screen_infos);
4788 if (window_screen_has_changed)
4789 screen->DispatchEvent(*Event::Create(event_type_names::kChange));
4792 if (previous_original_screen_infos != original_screen_infos) {
4793 // Propagate changes down to child local root RenderWidgets and
4794 // BrowserPlugins in other frame trees/processes.
4795 ForEachRemoteFrameControlledByWidget(
4796 [&original_screen_infos](RemoteFrame* remote_frame) {
4797 remote_frame->DidChangeScreenInfos(original_screen_infos);
4802 gfx::Rect WebFrameWidgetImpl::ViewportVisibleRect() {
4803 if (ForMainFrame()) {
4804 return widget_base_->CompositorViewportRect();
4806 return child_data().compositor_visible_rect;
4810 absl::optional<display::mojom::blink::ScreenOrientation>
4811 WebFrameWidgetImpl::ScreenOrientationOverride() {
4812 return View()->ScreenOrientationOverride();
4815 void WebFrameWidgetImpl::WasHidden() {
4816 ForEachLocalFrameControlledByWidget(local_root_->GetFrame(),
4817 [](WebLocalFrameImpl* local_frame) {
4818 local_frame->Client()->WasHidden();
4821 if (animation_frame_timing_monitor_) {
4822 animation_frame_timing_monitor_->Shutdown();
4823 animation_frame_timing_monitor_.Clear();
4827 void WebFrameWidgetImpl::WasShown(bool was_evicted) {
4828 ForEachLocalFrameControlledByWidget(local_root_->GetFrame(),
4829 [](WebLocalFrameImpl* local_frame) {
4830 local_frame->Client()->WasShown();
4833 ForEachRemoteFrameControlledByWidget(
4834 // On eviction, the last SurfaceId is invalidated. We need to
4835 // allocate a new id.
4836 &RemoteFrame::ResendVisualProperties);
4839 CHECK(local_root_ && local_root_->GetFrame());
4840 if (!animation_frame_timing_monitor_ &&
4841 RuntimeEnabledFeatures::LongAnimationFrameMonitoringEnabled(
4842 local_root_->GetFrame()->DomWindow())) {
4843 animation_frame_timing_monitor_ =
4844 MakeGarbageCollected<AnimationFrameTimingMonitor>(
4845 *this, local_root_->GetFrame()->GetProbeSink());
4849 void WebFrameWidgetImpl::RunPaintBenchmark(int repeat_count,
4850 cc::PaintBenchmarkResult& result) {
4851 if (!ForMainFrame())
4853 if (auto* frame_view = LocalRootImpl()->GetFrameView())
4854 frame_view->RunPaintBenchmark(repeat_count, result);
4857 void WebFrameWidgetImpl::NotifyInputObservers(
4858 const WebCoalescedInputEvent& coalesced_event) {
4859 LocalFrame* frame = FocusedLocalFrameInWidget();
4863 LocalFrameView* frame_view = frame->View();
4867 const WebInputEvent& input_event = coalesced_event.Event();
4868 auto& paint_timing_detector = frame_view->GetPaintTimingDetector();
4870 if (paint_timing_detector.NeedToNotifyInputOrScroll())
4871 paint_timing_detector.NotifyInputEvent(input_event.GetType());
4874 Frame* WebFrameWidgetImpl::FocusedCoreFrame() const {
4875 return GetPage() ? GetPage()->GetFocusController().FocusedOrMainFrame()
4879 Element* WebFrameWidgetImpl::FocusedElement() const {
4880 LocalFrame* frame = GetPage()->GetFocusController().FocusedFrame();
4884 Document* document = frame->GetDocument();
4888 return document->FocusedElement();
4891 HitTestResult WebFrameWidgetImpl::HitTestResultForRootFramePos(
4892 const gfx::PointF& pos_in_root_frame) {
4893 gfx::PointF doc_point =
4894 LocalRootImpl()->GetFrame()->View()->ConvertFromRootFrame(
4896 HitTestLocation location(doc_point);
4897 HitTestResult result =
4898 LocalRootImpl()->GetFrame()->View()->HitTestWithThrottlingAllowed(
4899 location, HitTestRequest::kReadOnly | HitTestRequest::kActive);
4903 KURL WebFrameWidgetImpl::GetURLForDebugTrace() {
4904 WebFrame* main_frame = View()->MainFrame();
4905 if (main_frame->IsWebLocalFrame())
4906 return main_frame->ToWebLocalFrame()->GetDocument().Url();
4910 float WebFrameWidgetImpl::GetTestingDeviceScaleFactorOverride() {
4911 return device_scale_factor_for_testing_;
4914 void WebFrameWidgetImpl::ReleaseMouseLockAndPointerCaptureForTesting() {
4915 GetPage()->GetPointerLockController().ExitPointerLock();
4919 const viz::FrameSinkId& WebFrameWidgetImpl::GetFrameSinkId() {
4920 // It is valid to create a WebFrameWidget with an invalid frame sink id for
4921 // printing and placeholders. But if we go to use it, it should be valid.
4922 DCHECK(frame_sink_id_.is_valid());
4923 return frame_sink_id_;
4926 WebHitTestResult WebFrameWidgetImpl::HitTestResultAt(const gfx::PointF& point) {
4927 return CoreHitTestResultAt(point);
4930 void WebFrameWidgetImpl::SetZoomLevelForTesting(double zoom_level) {
4931 DCHECK(ForMainFrame());
4932 DCHECK_NE(zoom_level, -INFINITY);
4933 zoom_level_for_testing_ = zoom_level;
4934 SetZoomLevel(zoom_level);
4937 void WebFrameWidgetImpl::ResetZoomLevelForTesting() {
4938 DCHECK(ForMainFrame());
4939 zoom_level_for_testing_ = -INFINITY;
4943 void WebFrameWidgetImpl::SetDeviceScaleFactorForTesting(float factor) {
4944 DCHECK(ForMainFrame());
4945 DCHECK_GE(factor, 0.f);
4947 // Stash the window size before we adjust the scale factor, as subsequent
4948 // calls to convert will use the new scale factor.
4949 gfx::Size size_in_dips = widget_base_->BlinkSpaceToFlooredDIPs(Size());
4950 device_scale_factor_for_testing_ = factor;
4952 // Receiving a 0 is used to reset between tests, it removes the override in
4953 // order to listen to the browser for the next test.
4957 // We are changing the device scale factor from the renderer, so allocate a
4958 // new viz::LocalSurfaceId to avoid surface invariants violations in tests.
4959 widget_base_->LayerTreeHost()->RequestNewLocalSurfaceId();
4961 display::ScreenInfos screen_infos = widget_base_->screen_infos();
4962 screen_infos.mutable_current().device_scale_factor = factor;
4963 gfx::Size size_with_dsf = gfx::ScaleToCeiledSize(size_in_dips, factor);
4964 widget_base_->UpdateCompositorViewportAndScreenInfo(gfx::Rect(size_with_dsf),
4966 if (!AutoResizeMode()) {
4967 // This picks up the new device scale factor as
4968 // `UpdateCompositorViewportAndScreenInfo()` has applied a new value.
4969 Resize(widget_base_->DIPsToCeiledBlinkSpace(size_in_dips));
4973 FrameWidgetTestHelper*
4974 WebFrameWidgetImpl::GetFrameWidgetTestHelperForTesting() {
4978 void WebFrameWidgetImpl::PrepareForFinalLifecyclUpdateForTesting() {
4979 ForEachLocalFrameControlledByWidget(
4980 LocalRootImpl()->GetFrame(), [](WebLocalFrameImpl* local_frame) {
4981 LocalFrame* core_frame = local_frame->GetFrame();
4982 // A frame in the frame tree is fully attached and must always have a
4985 Document* document = core_frame->GetDocument();
4986 // Similarly, a fully attached frame must always have a document.
4989 // In a web test, a rendering update may not have occurred before the
4990 // test finishes so ensure the transition moves out of rendering
4992 if (RuntimeEnabledFeatures::ViewTransitionOnNavigationEnabled()) {
4993 if (auto* transition =
4994 ViewTransitionUtils::GetTransition(*document)) {
4995 transition->ActivateFromSnapshot();
5001 void WebFrameWidgetImpl::SetMayThrottleIfUndrawnFrames(
5002 bool may_throttle_if_undrawn_frames) {
5003 if (!View()->does_composite())
5005 widget_base_->LayerTreeHost()->SetMayThrottleIfUndrawnFrames(
5006 may_throttle_if_undrawn_frames);
5009 int WebFrameWidgetImpl::GetVirtualKeyboardResizeHeight() const {
5010 DCHECK(!virtual_keyboard_resize_height_physical_px_ || ForTopMostMainFrame());
5011 return virtual_keyboard_resize_height_physical_px_;
5014 void WebFrameWidgetImpl::SetVirtualKeyboardResizeHeightForTesting(int height) {
5015 virtual_keyboard_resize_height_physical_px_ = height;
5018 bool WebFrameWidgetImpl::GetMayThrottleIfUndrawnFramesForTesting() {
5019 return widget_base_->LayerTreeHost()
5020 ->GetMayThrottleIfUndrawnFramesForTesting();
5023 WebPlugin* WebFrameWidgetImpl::GetFocusedPluginContainer() {
5024 LocalFrame* focused_frame = FocusedLocalFrameInWidget();
5027 if (auto* container = focused_frame->GetWebPluginContainer())
5028 return container->Plugin();
5032 bool WebFrameWidgetImpl::HasPendingPageScaleAnimation() {
5033 return LayerTreeHost()->HasPendingPageScaleAnimation();
5036 void WebFrameWidgetImpl::SetSourceURLForCompositor(ukm::SourceId source_id,
5038 LayerTreeHost()->SetSourceURL(source_id, GURL(url));
5041 base::ReadOnlySharedMemoryRegion
5042 WebFrameWidgetImpl::CreateSharedMemoryForSmoothnessUkm() {
5043 return LayerTreeHost()->CreateSharedMemoryForSmoothnessUkm();
5046 bool WebFrameWidgetImpl::CanComposeInline() {
5047 if (auto* plugin = GetFocusedPluginContainer())
5048 return plugin->CanComposeInline();
5052 bool WebFrameWidgetImpl::ShouldDispatchImeEventsToPlugin() {
5053 if (auto* plugin = GetFocusedPluginContainer())
5054 return plugin->ShouldDispatchImeEventsToPlugin();
5058 void WebFrameWidgetImpl::ImeSetCompositionForPlugin(
5060 const Vector<ui::ImeTextSpan>& ime_text_spans,
5061 const gfx::Range& replacement_range,
5062 int selection_start,
5063 int selection_end) {
5064 if (auto* plugin = GetFocusedPluginContainer()) {
5065 plugin->ImeSetCompositionForPlugin(
5067 std::vector<ui::ImeTextSpan>(ime_text_spans.begin(),
5068 ime_text_spans.end()),
5069 replacement_range, selection_start, selection_end);
5073 void WebFrameWidgetImpl::ImeCommitTextForPlugin(
5075 const Vector<ui::ImeTextSpan>& ime_text_spans,
5076 const gfx::Range& replacement_range,
5077 int relative_cursor_pos) {
5078 if (auto* plugin = GetFocusedPluginContainer()) {
5079 plugin->ImeCommitTextForPlugin(
5081 std::vector<ui::ImeTextSpan>(ime_text_spans.begin(),
5082 ime_text_spans.end()),
5083 replacement_range, relative_cursor_pos);
5087 void WebFrameWidgetImpl::ImeFinishComposingTextForPlugin(bool keep_selection) {
5088 if (auto* plugin = GetFocusedPluginContainer())
5089 plugin->ImeFinishComposingTextForPlugin(keep_selection);
5092 void WebFrameWidgetImpl::SetWindowRect(const gfx::Rect& requested_rect,
5093 const gfx::Rect& adjusted_rect) {
5094 DCHECK(ForMainFrame());
5095 SetPendingWindowRect(adjusted_rect);
5096 View()->SendWindowRectToMainFrameHost(
5097 requested_rect, WTF::BindOnce(&WebFrameWidgetImpl::AckPendingWindowRect,
5098 WrapWeakPersistent(this)));
5101 void WebFrameWidgetImpl::SetWindowRectSynchronouslyForTesting(
5102 const gfx::Rect& new_window_rect) {
5103 DCHECK(ForMainFrame());
5104 SetWindowRectSynchronously(new_window_rect);
5107 void WebFrameWidgetImpl::SetWindowRectSynchronously(
5108 const gfx::Rect& new_window_rect) {
5109 // This method is only call in tests, and it applies the |new_window_rect| to
5111 // a) widget size (in |size_|)
5112 // b) blink viewport (in |visible_viewport_size_|)
5113 // c) compositor viewport (in cc::LayerTreeHost)
5114 // Normally the browser controls these three things independently, but this is
5115 // used in tests to control the size from the renderer.
5117 // We are resizing the window from the renderer, so allocate a new
5118 // viz::LocalSurfaceId to avoid surface invariants violations in tests.
5119 widget_base_->LayerTreeHost()->RequestNewLocalSurfaceId();
5121 gfx::Rect compositor_viewport_pixel_rect(gfx::ScaleToCeiledSize(
5122 new_window_rect.size(),
5123 widget_base_->GetScreenInfo().device_scale_factor));
5124 widget_base_->UpdateSurfaceAndScreenInfo(
5125 widget_base_->local_surface_id_from_parent(),
5126 compositor_viewport_pixel_rect, widget_base_->screen_infos());
5128 Resize(new_window_rect.size());
5129 widget_base_->SetScreenRects(new_window_rect, new_window_rect);
5132 void WebFrameWidgetImpl::DidCreateLocalRootView() {
5133 // If this WebWidget still hasn't received its size from the embedder, block
5134 // the parser. This is necessary, because the parser can cause layout to
5135 // happen, which needs to be done with the correct size.
5136 if (ForSubframe() && !size_) {
5137 child_data().did_suspend_parsing = true;
5138 LocalRootImpl()->GetFrame()->Loader().GetDocumentLoader()->BlockParser();
5142 bool WebFrameWidgetImpl::ShouldAutoDetermineCompositingToLCDTextSetting() {
5146 void WebFrameWidgetImpl::NotifyZoomLevelChanged(LocalFrame* root) {
5148 Document* document = root->GetDocument();
5150 if (LocalFrameView* view = document->View())
5151 view->GetLayoutShiftTracker().NotifyZoomLevelChanged();
5155 #if BUILDFLAG(IS_EFL)
5156 void WebFrameWidgetImpl::NotifyKeyEvent(WebInputEvent::Type type,
5158 GetAssociatedFrameWidgetHost()->HandleKeyEvent(type, processed);
5162 #if BUILDFLAG(IS_TIZEN)
5163 void WebFrameWidgetImpl::SetDrawsTransparentBackground(
5164 bool draws_transparent_background) {
5165 WebViewImpl* webview = View();
5169 SkColor backgroundColor = draws_transparent_background
5170 ? static_cast<SkColor>(0x00000000)
5171 : static_cast<SkColor>(0xFFFFFFFF);
5173 webview->SetPageBaseBackgroundColor(absl::make_optional(backgroundColor));
5174 // set transparent bg for Render process
5175 if (draws_transparent_background) {
5176 widget_base_->LayerTreeHost()->set_background_color(SkColors::kTransparent);
5180 void WebFrameWidgetImpl::SetBackgroundColor(int32_t red,
5184 WebViewImpl* webview = View();
5188 SkColor backgroundColor = SkColorSetARGB(alpha, red, green, blue);
5189 webview->SetPageBaseBackgroundColor(absl::make_optional(backgroundColor));
5193 } // namespace blink