input_handler.cc 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249
  1. // Copyright 2020 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "cc/input/input_handler.h"
  5. #include <utility>
  6. #include <vector>
  7. #include "base/notreached.h"
  8. #include "build/build_config.h"
  9. #include "cc/base/features.h"
  10. #include "cc/input/scroll_elasticity_helper.h"
  11. #include "cc/input/scroll_utils.h"
  12. #include "cc/input/scrollbar_controller.h"
  13. #include "cc/input/snap_selection_strategy.h"
  14. #include "cc/layers/viewport.h"
  15. #include "cc/trees/compositor_commit_data.h"
  16. #include "cc/trees/latency_info_swap_promise_monitor.h"
  17. #include "cc/trees/layer_tree_host_impl.h"
  18. #include "cc/trees/layer_tree_impl.h"
  19. #include "cc/trees/layer_tree_settings.h"
  20. #include "cc/trees/property_tree.h"
  21. #include "cc/trees/scroll_node.h"
  22. #include "ui/gfx/geometry/point.h"
  23. #include "ui/gfx/geometry/point_conversions.h"
  24. #include "ui/gfx/geometry/point_f.h"
  25. #include "ui/gfx/geometry/vector2d_f.h"
  26. namespace cc {
  27. namespace {
  28. enum SlowScrollMetricThread { MAIN_THREAD, CC_THREAD };
  29. void RecordCompositorSlowScrollMetric(ui::ScrollInputType type,
  30. SlowScrollMetricThread scroll_thread) {
  31. bool scroll_on_main_thread = (scroll_thread == MAIN_THREAD);
  32. if (type == ui::ScrollInputType::kWheel) {
  33. UMA_HISTOGRAM_BOOLEAN("Renderer4.CompositorWheelScrollUpdateThread",
  34. scroll_on_main_thread);
  35. } else if (type == ui::ScrollInputType::kTouchscreen) {
  36. UMA_HISTOGRAM_BOOLEAN("Renderer4.CompositorTouchScrollUpdateThread",
  37. scroll_on_main_thread);
  38. }
  39. }
  40. } // namespace
  41. InputHandlerCommitData::InputHandlerCommitData() = default;
  42. InputHandlerCommitData::~InputHandlerCommitData() = default;
  43. // static
  44. base::WeakPtr<InputHandler> InputHandler::Create(
  45. CompositorDelegateForInput& compositor_delegate) {
  46. auto input_handler = std::make_unique<InputHandler>(compositor_delegate);
  47. base::WeakPtr<InputHandler> input_handler_weak = input_handler->AsWeakPtr();
  48. compositor_delegate.BindToInputHandler(std::move(input_handler));
  49. return input_handler_weak;
  50. }
  51. InputHandler::InputHandler(CompositorDelegateForInput& compositor_delegate)
  52. : compositor_delegate_(compositor_delegate),
  53. scrollbar_controller_(std::make_unique<ScrollbarController>(
  54. &compositor_delegate_.GetImplDeprecated())) {}
  55. InputHandler::~InputHandler() = default;
  56. //
  57. // =========== InputHandler Interface
  58. //
  59. base::WeakPtr<InputHandler> InputHandler::AsWeakPtr() const {
  60. return weak_factory_.GetWeakPtr();
  61. }
  62. void InputHandler::BindToClient(InputHandlerClient* client) {
  63. DCHECK(input_handler_client_ == nullptr);
  64. input_handler_client_ = client;
  65. input_handler_client_->SetPrefersReducedMotion(prefers_reduced_motion_);
  66. }
  67. InputHandler::ScrollStatus InputHandler::ScrollBegin(ScrollState* scroll_state,
  68. ui::ScrollInputType type) {
  69. DCHECK(scroll_state);
  70. DCHECK(scroll_state->delta_x() == 0 && scroll_state->delta_y() == 0);
  71. InputHandler::ScrollStatus scroll_status;
  72. scroll_status.main_thread_scrolling_reasons =
  73. MainThreadScrollingReason::kNotScrollingOnMain;
  74. TRACE_EVENT0("cc", "InputHandler::ScrollBegin");
  75. // If this ScrollBegin is non-animated then ensure we cancel any ongoing
  76. // animated scrolls.
  77. // TODO(bokan): This preserves existing behavior when we had diverging
  78. // paths for animated and non-animated scrolls but we should probably
  79. // decide when it best makes sense to cancel a scroll animation (maybe
  80. // ScrollBy is a better place to do it).
  81. if (scroll_state->delta_granularity() ==
  82. ui::ScrollGranularity::kScrollByPrecisePixel) {
  83. compositor_delegate_.GetImplDeprecated()
  84. .mutator_host()
  85. ->ScrollAnimationAbort();
  86. scroll_animating_snap_target_ids_ = TargetSnapAreaElementIds();
  87. }
  88. if (CurrentlyScrollingNode() && type == latched_scroll_type_) {
  89. // It's possible we haven't yet cleared the CurrentlyScrollingNode if we
  90. // received a GSE but we're still animating the last scroll. If that's the
  91. // case, we'll simply un-defer the GSE and continue latching to the same
  92. // node.
  93. DCHECK(deferred_scroll_end_);
  94. deferred_scroll_end_ = false;
  95. return scroll_status;
  96. }
  97. ScrollNode* scrolling_node = nullptr;
  98. bool scroll_on_main_thread = false;
  99. // TODO(bokan): ClearCurrentlyScrollingNode shouldn't happen in ScrollBegin,
  100. // this should only happen in ScrollEnd. We should DCHECK here that the state
  101. // is cleared instead. https://crbug.com/1016229
  102. ClearCurrentlyScrollingNode();
  103. ElementId target_element_id = scroll_state->target_element_id();
  104. ScrollTree& scroll_tree = GetScrollTree();
  105. bool unification_enabled =
  106. base::FeatureList::IsEnabled(features::kScrollUnification);
  107. if (target_element_id && !scroll_state->is_main_thread_hit_tested()) {
  108. TRACE_EVENT_INSTANT0("cc", "Latched scroll node provided",
  109. TRACE_EVENT_SCOPE_THREAD);
  110. // If the caller passed in an element_id we can skip all the hit-testing
  111. // bits and provide a node straight-away.
  112. scrolling_node = scroll_tree.FindNodeFromElementId(target_element_id);
  113. // In unified scrolling, if we found a node we get to scroll it.
  114. if (!unification_enabled) {
  115. // We still need to confirm the targeted node exists and can scroll on
  116. // the compositor.
  117. if (scrolling_node) {
  118. scroll_status = TryScroll(scroll_tree, scrolling_node);
  119. if (IsMainThreadScrolling(scroll_status, scrolling_node))
  120. scroll_on_main_thread = true;
  121. }
  122. }
  123. } else {
  124. ScrollNode* starting_node = nullptr;
  125. if (target_element_id) {
  126. TRACE_EVENT_INSTANT0("cc", "Unlatched scroll node provided",
  127. TRACE_EVENT_SCOPE_THREAD);
  128. // We had an element id but we should still perform the walk up the
  129. // scroll tree from the targeted node to latch to a scroller that can
  130. // scroll in the given direction. This mode is only used when scroll
  131. // unification is enabled and the targeted scroller comes back from a
  132. // main thread hit test.
  133. DCHECK(scroll_state->data()->is_main_thread_hit_tested);
  134. DCHECK(unification_enabled);
  135. starting_node = scroll_tree.FindNodeFromElementId(target_element_id);
  136. if (!starting_node) {
  137. // The main thread sent us an element_id that the compositor doesn't
  138. // have a scroll node for. This can happen in some racy conditions, a
  139. // freshly created scroller hasn't yet been committed or a
  140. // scroller-destroying commit beats the hit test back to the compositor
  141. // thread. However, these cases shouldn't be user perceptible.
  142. scroll_status.main_thread_scrolling_reasons =
  143. MainThreadScrollingReason::kNoScrollingLayer;
  144. scroll_status.thread = InputHandler::ScrollThread::SCROLL_IGNORED;
  145. return scroll_status;
  146. }
  147. } else { // !target_element_id
  148. TRACE_EVENT_INSTANT0("cc", "Hit Testing for ScrollNode",
  149. TRACE_EVENT_SCOPE_THREAD);
  150. gfx::Point viewport_point(scroll_state->position_x(),
  151. scroll_state->position_y());
  152. gfx::PointF device_viewport_point =
  153. gfx::ScalePoint(gfx::PointF(viewport_point),
  154. compositor_delegate_.DeviceScaleFactor());
  155. if (unification_enabled) {
  156. if (scroll_state->data()->is_main_thread_hit_tested) {
  157. // The client should have discarded the scroll when the hit test came
  158. // back with an invalid element id. If we somehow get here, we should
  159. // drop the scroll as continuing could cause us to infinitely bounce
  160. // back and forth between here and hit testing on the main thread.
  161. NOTREACHED();
  162. scroll_status.main_thread_scrolling_reasons =
  163. MainThreadScrollingReason::kNoScrollingLayer;
  164. scroll_status.thread = InputHandler::ScrollThread::SCROLL_IGNORED;
  165. return scroll_status;
  166. }
  167. // Touch dragging the scrollbar requires falling back to main-thread
  168. // scrolling.
  169. // TODO(bokan): This could be trivially handled in the compositor by
  170. // the new ScrollbarController and should be removed.
  171. {
  172. LayerImpl* first_scrolling_layer_or_scrollbar =
  173. ActiveTree().FindFirstScrollingLayerOrScrollbarThatIsHitByPoint(
  174. device_viewport_point);
  175. if (IsTouchDraggingScrollbar(first_scrolling_layer_or_scrollbar,
  176. type)) {
  177. TRACE_EVENT_INSTANT0("cc", "Scrollbar Scrolling",
  178. TRACE_EVENT_SCOPE_THREAD);
  179. scroll_status.thread =
  180. InputHandler::ScrollThread::SCROLL_ON_MAIN_THREAD;
  181. scroll_status.main_thread_scrolling_reasons =
  182. MainThreadScrollingReason::kScrollbarScrolling;
  183. return scroll_status;
  184. }
  185. }
  186. ScrollHitTestResult scroll_hit_test =
  187. HitTestScrollNode(device_viewport_point);
  188. if (!scroll_hit_test.hit_test_successful) {
  189. // This result tells the client that the compositor doesn't have
  190. // enough information to target this scroll. The client should
  191. // perform a hit test in Blink and call this method again, with the
  192. // ElementId of the hit-tested scroll node.
  193. TRACE_EVENT_INSTANT0("cc", "Request Main Thread Hit Test",
  194. TRACE_EVENT_SCOPE_THREAD);
  195. scroll_status.thread =
  196. InputHandler::ScrollThread::SCROLL_ON_IMPL_THREAD;
  197. scroll_status.needs_main_thread_hit_test = true;
  198. return scroll_status;
  199. }
  200. starting_node = scroll_hit_test.scroll_node;
  201. } else { // !unification_enabled
  202. LayerImpl* layer_impl =
  203. ActiveTree().FindLayerThatIsHitByPoint(device_viewport_point);
  204. if (layer_impl) {
  205. LayerImpl* first_scrolling_layer_or_scrollbar =
  206. ActiveTree().FindFirstScrollingLayerOrScrollbarThatIsHitByPoint(
  207. device_viewport_point);
  208. // Touch dragging the scrollbar requires falling back to main-thread
  209. // scrolling.
  210. if (IsTouchDraggingScrollbar(first_scrolling_layer_or_scrollbar,
  211. type)) {
  212. TRACE_EVENT_INSTANT0("cc", "Scrollbar Scrolling",
  213. TRACE_EVENT_SCOPE_THREAD);
  214. scroll_status.thread =
  215. InputHandler::ScrollThread::SCROLL_ON_MAIN_THREAD;
  216. scroll_status.main_thread_scrolling_reasons =
  217. MainThreadScrollingReason::kScrollbarScrolling;
  218. return scroll_status;
  219. } else if (!IsInitialScrollHitTestReliable(
  220. layer_impl, first_scrolling_layer_or_scrollbar)) {
  221. TRACE_EVENT_INSTANT0("cc", "Failed Hit Test",
  222. TRACE_EVENT_SCOPE_THREAD);
  223. scroll_status.thread =
  224. InputHandler::ScrollThread::SCROLL_ON_MAIN_THREAD;
  225. scroll_status.main_thread_scrolling_reasons =
  226. MainThreadScrollingReason::kFailedHitTest;
  227. return scroll_status;
  228. }
  229. }
  230. starting_node = FindScrollNodeForCompositedScrolling(
  231. device_viewport_point, layer_impl, &scroll_on_main_thread,
  232. &scroll_status.main_thread_scrolling_reasons);
  233. }
  234. }
  235. // The above finds the ScrollNode that's hit by the given point but we
  236. // still need to walk up the scroll tree looking for the first node that
  237. // can consume delta from the scroll state.
  238. scrolling_node = FindNodeToLatch(scroll_state, starting_node, type);
  239. }
  240. if (scroll_on_main_thread) {
  241. // Under scroll unification we can request a main thread hit test, but we
  242. // should never send scrolls to the main thread.
  243. DCHECK(!unification_enabled);
  244. RecordCompositorSlowScrollMetric(type, MAIN_THREAD);
  245. scroll_status.thread = InputHandler::ScrollThread::SCROLL_ON_MAIN_THREAD;
  246. return scroll_status;
  247. } else if (!scrolling_node) {
  248. // TODO(crbug.com/1155663): Make sure to set main_thread_scrolling_reasons
  249. // only when ScrollStatus.thread is set to
  250. // InputHander::ScrollThread::SCROLL_ON_MAIN_THREAD
  251. scroll_status.main_thread_scrolling_reasons =
  252. MainThreadScrollingReason::kNoScrollingLayer;
  253. if (compositor_delegate_.GetSettings().is_for_embedded_frame) {
  254. // OOPIFs or fenced frames never have a viewport scroll node so if we
  255. // can't scroll we need to be bubble up to the parent frame. This happens
  256. // by returning SCROLL_IGNORED.
  257. TRACE_EVENT_INSTANT0("cc",
  258. "Ignored - No ScrollNode (OOPIF or FencedFrame)",
  259. TRACE_EVENT_SCOPE_THREAD);
  260. } else {
  261. // If we didn't hit a layer above we'd usually fallback to the
  262. // viewport scroll node. However, there may not be one if a scroll
  263. // is received before the root layer has been attached. Chrome now
  264. // drops input until the first commit is received so this probably
  265. // can't happen in a typical browser session but there may still be
  266. // configurations where input is allowed prior to a commit.
  267. TRACE_EVENT_INSTANT0("cc", "Ignored - No ScrollNode",
  268. TRACE_EVENT_SCOPE_THREAD);
  269. }
  270. scroll_status.thread = InputHandler::ScrollThread::SCROLL_IGNORED;
  271. return scroll_status;
  272. }
  273. DCHECK_EQ(scroll_status.main_thread_scrolling_reasons,
  274. MainThreadScrollingReason::kNotScrollingOnMain);
  275. DCHECK_EQ(scroll_status.thread,
  276. InputHandler::ScrollThread::SCROLL_ON_IMPL_THREAD);
  277. DCHECK(scrolling_node);
  278. ActiveTree().SetCurrentlyScrollingNode(scrolling_node);
  279. if (unification_enabled)
  280. scroll_status.main_thread_repaint_reasons =
  281. scroll_tree.GetMainThreadRepaintReasons(*scrolling_node);
  282. DidLatchToScroller(*scroll_state, type);
  283. // If the viewport is scrolling and it cannot consume any delta hints, the
  284. // scroll event will need to get bubbled if the viewport is for a guest or
  285. // oopif.
  286. if (GetViewport().ShouldScroll(*CurrentlyScrollingNode()) &&
  287. !GetViewport().CanScroll(*CurrentlyScrollingNode(), *scroll_state)) {
  288. // TODO(crbug.com/1155758): This is a temporary workaround for GuestViews
  289. // as they create viewport nodes and want to bubble scroll if the
  290. // viewport cannot scroll in the given delta directions. There should be
  291. // a parameter to ThreadInputHandler to specify whether unused delta is
  292. // consumed by the viewport or bubbles to the parent.
  293. scroll_status.viewport_cannot_scroll = true;
  294. }
  295. return scroll_status;
  296. }
  297. InputHandler::ScrollStatus InputHandler::RootScrollBegin(
  298. ScrollState* scroll_state,
  299. ui::ScrollInputType type) {
  300. TRACE_EVENT0("cc", "InputHandler::RootScrollBegin");
  301. if (!OuterViewportScrollNode()) {
  302. InputHandler::ScrollStatus scroll_status;
  303. scroll_status.thread = InputHandler::ScrollThread::SCROLL_IGNORED;
  304. scroll_status.main_thread_scrolling_reasons =
  305. MainThreadScrollingReason::kNoScrollingLayer;
  306. return scroll_status;
  307. }
  308. scroll_state->data()->set_current_native_scrolling_element(
  309. OuterViewportScrollNode()->element_id);
  310. InputHandler::ScrollStatus scroll_status = ScrollBegin(scroll_state, type);
  311. // Since we provided an ElementId, there should never be a need to perform a
  312. // hit test.
  313. DCHECK(!scroll_status.needs_main_thread_hit_test);
  314. return scroll_status;
  315. }
  316. InputHandlerScrollResult InputHandler::ScrollUpdate(
  317. ScrollState* scroll_state,
  318. base::TimeDelta delayed_by) {
  319. DCHECK(scroll_state);
  320. // The current_native_scrolling_element should only be set for ScrollBegin.
  321. DCHECK(!scroll_state->data()->current_native_scrolling_element());
  322. TRACE_EVENT2("cc", "InputHandler::ScrollUpdate", "dx",
  323. scroll_state->delta_x(), "dy", scroll_state->delta_y());
  324. if (!CurrentlyScrollingNode())
  325. return InputHandlerScrollResult();
  326. const ScrollNode& scroll_node = *CurrentlyScrollingNode();
  327. last_scroll_update_state_ = *scroll_state;
  328. // Snap on update if interacting with the scrollbar track or arrow buttons.
  329. // Interactions with the scrollbar thumb have kScrollByPrecisePixel
  330. // granularity.
  331. if (scroll_state->is_scrollbar_interaction() &&
  332. scroll_state->delta_granularity() !=
  333. ui::ScrollGranularity::kScrollByPrecisePixel) {
  334. AdjustScrollDeltaForScrollbarSnap(scroll_state);
  335. }
  336. gfx::Vector2dF resolvedScrollDelta = ResolveScrollGranularityToPixels(
  337. scroll_node,
  338. gfx::Vector2dF(scroll_state->delta_x(), scroll_state->delta_y()),
  339. scroll_state->delta_granularity());
  340. scroll_state->data()->delta_x = resolvedScrollDelta.x();
  341. scroll_state->data()->delta_y = resolvedScrollDelta.y();
  342. // The decision of whether or not we'll animate a scroll comes down to
  343. // whether the granularity is specified in precise pixels or not. Thus we
  344. // need to preserve a precise granularity if that's what was specified; all
  345. // others are animated and so can be resolved to regular pixels.
  346. if (scroll_state->delta_granularity() !=
  347. ui::ScrollGranularity::kScrollByPrecisePixel) {
  348. scroll_state->data()->delta_granularity =
  349. ui::ScrollGranularity::kScrollByPixel;
  350. }
  351. compositor_delegate_.AccumulateScrollDeltaForTracing(
  352. gfx::Vector2dF(scroll_state->delta_x(), scroll_state->delta_y()));
  353. compositor_delegate_.WillScrollContent(scroll_node.element_id);
  354. float initial_top_controls_offset = compositor_delegate_.GetImplDeprecated()
  355. .browser_controls_manager()
  356. ->ControlsTopOffset();
  357. ScrollLatchedScroller(scroll_state, delayed_by);
  358. bool did_scroll_x = scroll_state->caused_scroll_x();
  359. bool did_scroll_y = scroll_state->caused_scroll_y();
  360. did_scroll_x_for_scroll_gesture_ |= did_scroll_x;
  361. did_scroll_y_for_scroll_gesture_ |= did_scroll_y;
  362. delta_consumed_for_scroll_gesture_ |=
  363. scroll_state->delta_consumed_for_scroll_sequence();
  364. bool did_scroll_content = did_scroll_x || did_scroll_y;
  365. if (did_scroll_content) {
  366. bool is_animated_scroll = ShouldAnimateScroll(*scroll_state);
  367. compositor_delegate_.DidScrollContent(scroll_node.element_id,
  368. is_animated_scroll);
  369. } else {
  370. overscroll_delta_for_main_thread_ +=
  371. gfx::Vector2dF(scroll_state->delta_x(), scroll_state->delta_y());
  372. }
  373. SetNeedsCommit();
  374. // Scrolling along an axis resets accumulated root overscroll for that axis.
  375. if (did_scroll_x)
  376. accumulated_root_overscroll_.set_x(0);
  377. if (did_scroll_y)
  378. accumulated_root_overscroll_.set_y(0);
  379. gfx::Vector2dF unused_root_delta;
  380. if (GetViewport().ShouldScroll(scroll_node)) {
  381. unused_root_delta =
  382. gfx::Vector2dF(scroll_state->delta_x(), scroll_state->delta_y());
  383. }
  384. // When inner viewport is unscrollable, disable overscrolls.
  385. if (auto* inner_viewport_scroll_node = InnerViewportScrollNode()) {
  386. unused_root_delta =
  387. UserScrollableDelta(*inner_viewport_scroll_node, unused_root_delta);
  388. }
  389. accumulated_root_overscroll_ += unused_root_delta;
  390. bool did_scroll_top_controls =
  391. initial_top_controls_offset != compositor_delegate_.GetImplDeprecated()
  392. .browser_controls_manager()
  393. ->ControlsTopOffset();
  394. InputHandlerScrollResult scroll_result;
  395. scroll_result.did_scroll = did_scroll_content || did_scroll_top_controls;
  396. scroll_result.did_overscroll_root = !unused_root_delta.IsZero();
  397. scroll_result.accumulated_root_overscroll = accumulated_root_overscroll_;
  398. scroll_result.unused_scroll_delta = unused_root_delta;
  399. scroll_result.overscroll_behavior =
  400. scroll_state->is_scroll_chain_cut()
  401. ? OverscrollBehavior(OverscrollBehavior::Type::kNone)
  402. : ActiveTree().overscroll_behavior();
  403. if (scroll_result.did_scroll) {
  404. // Scrolling can change the root scroll offset, so inform the synchronous
  405. // input handler.
  406. UpdateRootLayerStateForSynchronousInputHandler();
  407. }
  408. scroll_result.current_visual_offset = GetVisualScrollOffset(scroll_node);
  409. float scale_factor = ActiveTree().page_scale_factor_for_scroll();
  410. scroll_result.current_visual_offset.Scale(scale_factor);
  411. if (base::FeatureList::IsEnabled(features::kScrollUnification) &&
  412. !GetScrollTree().CanRealizeScrollsOnCompositor(scroll_node)) {
  413. scroll_result.needs_main_thread_repaint = true;
  414. }
  415. // Run animations which need to respond to updated scroll offset.
  416. compositor_delegate_.GetImplDeprecated().mutator_host()->TickScrollAnimations(
  417. compositor_delegate_.GetImplDeprecated()
  418. .CurrentBeginFrameArgs()
  419. .frame_time,
  420. GetScrollTree());
  421. return scroll_result;
  422. }
  423. void InputHandler::AdjustScrollDeltaForScrollbarSnap(
  424. ScrollState* scroll_state) {
  425. ScrollNode* scroll_node = CurrentlyScrollingNode();
  426. if (!scroll_node || !scroll_node->snap_container_data)
  427. return;
  428. // Ideally, scrollbar track and arrow interactions would have
  429. // kScrollByPage and kScrollByLine, respectively. Currently, both have
  430. // kScrollByPixel granularity.
  431. // TODO(crbug.com/959441): Update snap strategy once the granularity is
  432. // properly set. Currently, track and arrow scrolls both use a direction
  433. // strategy; however, the track should be using an "end and direction"
  434. // strategy.
  435. gfx::PointF current_position = GetVisualScrollOffset(*scroll_node);
  436. const SnapContainerData& data = scroll_node->snap_container_data.value();
  437. std::unique_ptr<SnapSelectionStrategy> strategy =
  438. SnapSelectionStrategy::CreateForDirection(
  439. current_position,
  440. gfx::Vector2dF(scroll_state->delta_x(), scroll_state->delta_y()),
  441. true);
  442. gfx::PointF snap_position;
  443. TargetSnapAreaElementIds snap_target_ids;
  444. if (!data.FindSnapPosition(*strategy, &snap_position, &snap_target_ids))
  445. return;
  446. scroll_state->data()->delta_x = snap_position.x() - current_position.x();
  447. scroll_state->data()->delta_y = snap_position.y() - current_position.y();
  448. }
  449. void InputHandler::ScrollEnd(bool should_snap) {
  450. scrollbar_controller_->ResetState();
  451. if (!CurrentlyScrollingNode())
  452. return;
  453. // Note that if we deferred the scroll end then we should not snap. We will
  454. // snap once we deliver the deferred scroll end.
  455. if (compositor_delegate_.GetImplDeprecated()
  456. .mutator_host()
  457. ->ImplOnlyScrollAnimatingElement()) {
  458. DCHECK(!deferred_scroll_end_);
  459. deferred_scroll_end_ = true;
  460. return;
  461. }
  462. if (should_snap && SnapAtScrollEnd(SnapReason::kGestureScrollEnd)) {
  463. deferred_scroll_end_ = true;
  464. return;
  465. }
  466. DCHECK(latched_scroll_type_.has_value());
  467. compositor_delegate_.GetImplDeprecated()
  468. .browser_controls_manager()
  469. ->ScrollEnd();
  470. ClearCurrentlyScrollingNode();
  471. deferred_scroll_end_ = false;
  472. scroll_gesture_did_end_ = true;
  473. SetNeedsCommit();
  474. }
  475. void InputHandler::RecordScrollBegin(
  476. ui::ScrollInputType input_type,
  477. ScrollBeginThreadState scroll_start_state) {
  478. auto tracker_type = GetTrackerTypeForScroll(input_type);
  479. DCHECK_NE(tracker_type, FrameSequenceTrackerType::kMaxType);
  480. // The main-thread is the 'scrolling thread' if:
  481. // (1) the scroll is driven by the main thread, or
  482. // (2) the scroll is driven by the compositor, but blocked on the main
  483. // thread.
  484. // Otherwise, the compositor-thread is the 'scrolling thread'.
  485. // TODO(crbug.com/1060712): We should also count 'main thread' as the
  486. // 'scrolling thread' if the layer being scrolled has scroll-event handlers.
  487. FrameInfo::SmoothEffectDrivingThread scrolling_thread;
  488. switch (scroll_start_state) {
  489. case ScrollBeginThreadState::kScrollingOnCompositor:
  490. scrolling_thread = FrameInfo::SmoothEffectDrivingThread::kCompositor;
  491. break;
  492. case ScrollBeginThreadState::kScrollingOnMain:
  493. case ScrollBeginThreadState::kScrollingOnCompositorBlockedOnMain:
  494. scrolling_thread = FrameInfo::SmoothEffectDrivingThread::kMain;
  495. break;
  496. }
  497. compositor_delegate_.GetImplDeprecated().frame_trackers().StartScrollSequence(
  498. tracker_type, scrolling_thread);
  499. }
  500. void InputHandler::RecordScrollEnd(ui::ScrollInputType input_type) {
  501. compositor_delegate_.GetImplDeprecated().frame_trackers().StopSequence(
  502. GetTrackerTypeForScroll(input_type));
  503. }
  504. InputHandlerPointerResult InputHandler::MouseMoveAt(
  505. const gfx::Point& viewport_point) {
  506. InputHandlerPointerResult result;
  507. if (compositor_delegate_.GetSettings()
  508. .compositor_threaded_scrollbar_scrolling) {
  509. result =
  510. scrollbar_controller_->HandlePointerMove(gfx::PointF(viewport_point));
  511. }
  512. // Early out if there are no animation controllers and avoid the hit test.
  513. // This happens on platforms without animated scrollbars.
  514. if (!compositor_delegate_.HasAnimatedScrollbars())
  515. return result;
  516. gfx::PointF device_viewport_point = gfx::ScalePoint(
  517. gfx::PointF(viewport_point), compositor_delegate_.DeviceScaleFactor());
  518. ScrollHitTestResult hit_test = HitTestScrollNode(device_viewport_point);
  519. ScrollNode* scroll_node = hit_test.scroll_node;
  520. // The hit test can fail in some cases, e.g. we don't know if a region of a
  521. // squashed layer has content or is empty.
  522. if (!hit_test.hit_test_successful || !scroll_node)
  523. return result;
  524. // Scrollbars for the viewport are registered with the outer viewport layer.
  525. if (scroll_node->scrolls_inner_viewport)
  526. scroll_node = OuterViewportScrollNode();
  527. ElementId scroll_element_id = scroll_node->element_id;
  528. ScrollbarAnimationController* new_animation_controller =
  529. compositor_delegate_.GetImplDeprecated()
  530. .ScrollbarAnimationControllerForElementId(scroll_element_id);
  531. if (scroll_element_id != scroll_element_id_mouse_currently_over_) {
  532. ScrollbarAnimationController* old_animation_controller =
  533. compositor_delegate_.GetImplDeprecated()
  534. .ScrollbarAnimationControllerForElementId(
  535. scroll_element_id_mouse_currently_over_);
  536. if (old_animation_controller)
  537. old_animation_controller->DidMouseLeave();
  538. scroll_element_id_mouse_currently_over_ = scroll_element_id;
  539. }
  540. if (!new_animation_controller)
  541. return result;
  542. new_animation_controller->DidMouseMove(device_viewport_point);
  543. return result;
  544. }
  545. PointerResultType InputHandler::HitTest(const gfx::PointF& viewport_point) {
  546. return compositor_delegate_.GetSettings()
  547. .compositor_threaded_scrollbar_scrolling
  548. ? scrollbar_controller_->HitTest(viewport_point)
  549. : PointerResultType::kUnhandled;
  550. }
  551. InputHandlerPointerResult InputHandler::MouseDown(
  552. const gfx::PointF& viewport_point,
  553. bool shift_modifier) {
  554. ScrollbarAnimationController* animation_controller =
  555. compositor_delegate_.GetImplDeprecated()
  556. .ScrollbarAnimationControllerForElementId(
  557. scroll_element_id_mouse_currently_over_);
  558. if (animation_controller) {
  559. animation_controller->DidMouseDown();
  560. scroll_element_id_mouse_currently_captured_ =
  561. scroll_element_id_mouse_currently_over_;
  562. }
  563. InputHandlerPointerResult result;
  564. if (compositor_delegate_.GetSettings()
  565. .compositor_threaded_scrollbar_scrolling) {
  566. result = scrollbar_controller_->HandlePointerDown(viewport_point,
  567. shift_modifier);
  568. }
  569. return result;
  570. }
  571. InputHandlerPointerResult InputHandler::MouseUp(
  572. const gfx::PointF& viewport_point) {
  573. if (scroll_element_id_mouse_currently_captured_) {
  574. ScrollbarAnimationController* animation_controller =
  575. compositor_delegate_.GetImplDeprecated()
  576. .ScrollbarAnimationControllerForElementId(
  577. scroll_element_id_mouse_currently_captured_);
  578. scroll_element_id_mouse_currently_captured_ = ElementId();
  579. if (animation_controller)
  580. animation_controller->DidMouseUp();
  581. }
  582. InputHandlerPointerResult result;
  583. if (compositor_delegate_.GetSettings()
  584. .compositor_threaded_scrollbar_scrolling)
  585. result = scrollbar_controller_->HandlePointerUp(viewport_point);
  586. return result;
  587. }
  588. void InputHandler::MouseLeave() {
  589. compositor_delegate_.DidMouseLeave();
  590. scroll_element_id_mouse_currently_over_ = ElementId();
  591. }
  592. ElementId InputHandler::FindFrameElementIdAtPoint(
  593. const gfx::PointF& viewport_point) {
  594. gfx::PointF device_viewport_point = gfx::ScalePoint(
  595. gfx::PointF(viewport_point), compositor_delegate_.DeviceScaleFactor());
  596. return ActiveTree().FindFrameElementIdAtPoint(device_viewport_point);
  597. }
  598. void InputHandler::RequestUpdateForSynchronousInputHandler() {
  599. UpdateRootLayerStateForSynchronousInputHandler();
  600. }
  601. void InputHandler::SetSynchronousInputHandlerRootScrollOffset(
  602. const gfx::PointF& root_content_offset) {
  603. TRACE_EVENT2("cc", "InputHandler::SetSynchronousInputHandlerRootScrollOffset",
  604. "offset_x", root_content_offset.x(), "offset_y",
  605. root_content_offset.y());
  606. gfx::Vector2dF physical_delta =
  607. root_content_offset - GetViewport().TotalScrollOffset();
  608. physical_delta.Scale(ActiveTree().page_scale_factor_for_scroll());
  609. bool changed = !GetViewport()
  610. .ScrollBy(physical_delta,
  611. /*viewport_point=*/gfx::Point(),
  612. /*is_direct_manipulation=*/false,
  613. /*affect_browser_controls=*/false,
  614. /*scroll_outer_viewport=*/true)
  615. .consumed_delta.IsZero();
  616. if (!changed)
  617. return;
  618. compositor_delegate_.DidScrollContent(OuterViewportScrollNode()->element_id,
  619. /*is_animated_scroll=*/false);
  620. SetNeedsCommit();
  621. // After applying the synchronous input handler's scroll offset, tell it what
  622. // we ended up with.
  623. UpdateRootLayerStateForSynchronousInputHandler();
  624. compositor_delegate_.SetNeedsFullViewportRedraw();
  625. }
  626. void InputHandler::PinchGestureBegin(const gfx::Point& anchor,
  627. ui::ScrollInputType source) {
  628. DCHECK(source == ui::ScrollInputType::kTouchscreen ||
  629. source == ui::ScrollInputType::kWheel);
  630. pinch_gesture_active_ = true;
  631. pinch_gesture_end_should_clear_scrolling_node_ = !CurrentlyScrollingNode();
  632. TRACE_EVENT_INSTANT1("cc", "SetCurrentlyScrollingNode PinchGestureBegin",
  633. TRACE_EVENT_SCOPE_THREAD, "isNull",
  634. OuterViewportScrollNode() ? false : true);
  635. // Some unit tests don't setup viewport scroll nodes but do initiate a pinch
  636. // zoom gesture. Ideally, those tests should either create the viewport
  637. // scroll nodes or avoid simulating a pinch gesture.
  638. if (OuterViewportScrollNode()) {
  639. ActiveTree().SetCurrentlyScrollingNode(OuterViewportScrollNode());
  640. ScrollStateData scroll_state_data;
  641. scroll_state_data.position_x = anchor.x();
  642. scroll_state_data.position_y = anchor.y();
  643. scroll_state_data.is_beginning = true;
  644. scroll_state_data.delta_granularity =
  645. ui::ScrollGranularity::kScrollByPrecisePixel;
  646. scroll_state_data.is_direct_manipulation =
  647. source == ui::ScrollInputType::kTouchscreen;
  648. ScrollState state(scroll_state_data);
  649. DidLatchToScroller(state, source);
  650. }
  651. compositor_delegate_.GetImplDeprecated()
  652. .browser_controls_manager()
  653. ->PinchBegin();
  654. compositor_delegate_.DidStartPinchZoom();
  655. }
  656. void InputHandler::PinchGestureUpdate(float magnify_delta,
  657. const gfx::Point& anchor) {
  658. TRACE_EVENT0("cc", "InputHandler::PinchGestureUpdate");
  659. if (!InnerViewportScrollNode())
  660. return;
  661. has_pinch_zoomed_ = true;
  662. GetViewport().PinchUpdate(magnify_delta, anchor);
  663. SetNeedsCommit();
  664. compositor_delegate_.DidUpdatePinchZoom();
  665. // Pinching can change the root scroll offset, so inform the synchronous input
  666. // handler.
  667. UpdateRootLayerStateForSynchronousInputHandler();
  668. }
  669. void InputHandler::PinchGestureEnd(const gfx::Point& anchor) {
  670. // Some tests create a pinch gesture without creating a viewport scroll node.
  671. // In those cases, PinchGestureBegin will not latch to a scroll node.
  672. DCHECK(latched_scroll_type_.has_value() || !CurrentlyScrollingNode());
  673. bool snap_to_min = latched_scroll_type_.has_value() &&
  674. latched_scroll_type_ == ui::ScrollInputType::kWheel;
  675. pinch_gesture_active_ = false;
  676. if (pinch_gesture_end_should_clear_scrolling_node_) {
  677. pinch_gesture_end_should_clear_scrolling_node_ = false;
  678. ClearCurrentlyScrollingNode();
  679. }
  680. GetViewport().PinchEnd(anchor, snap_to_min);
  681. compositor_delegate_.GetImplDeprecated()
  682. .browser_controls_manager()
  683. ->PinchEnd();
  684. SetNeedsCommit();
  685. compositor_delegate_.DidEndPinchZoom();
  686. }
  687. void InputHandler::SetNeedsAnimateInput() {
  688. compositor_delegate_.GetImplDeprecated().SetNeedsAnimateInput();
  689. }
  690. bool InputHandler::IsCurrentlyScrollingViewport() const {
  691. auto* node = CurrentlyScrollingNode();
  692. if (!node)
  693. return false;
  694. return GetViewport().ShouldScroll(*node);
  695. }
  696. EventListenerProperties InputHandler::GetEventListenerProperties(
  697. EventListenerClass event_class) const {
  698. return ActiveTree().event_listener_properties(event_class);
  699. }
  700. bool InputHandler::HasBlockingWheelEventHandlerAt(
  701. const gfx::Point& viewport_point) const {
  702. gfx::PointF device_viewport_point = gfx::ScalePoint(
  703. gfx::PointF(viewport_point), compositor_delegate_.DeviceScaleFactor());
  704. LayerImpl* layer_impl_with_wheel_event_handler =
  705. ActiveTree().FindLayerThatIsHitByPointInWheelEventHandlerRegion(
  706. device_viewport_point);
  707. return layer_impl_with_wheel_event_handler;
  708. }
  709. InputHandler::TouchStartOrMoveEventListenerType
  710. InputHandler::EventListenerTypeForTouchStartOrMoveAt(
  711. const gfx::Point& viewport_point,
  712. TouchAction* out_touch_action) {
  713. gfx::PointF device_viewport_point = gfx::ScalePoint(
  714. gfx::PointF(viewport_point), compositor_delegate_.DeviceScaleFactor());
  715. LayerImpl* layer_impl_with_touch_handler =
  716. ActiveTree().FindLayerThatIsHitByPointInTouchHandlerRegion(
  717. device_viewport_point);
  718. if (layer_impl_with_touch_handler == nullptr) {
  719. if (out_touch_action)
  720. *out_touch_action = TouchAction::kAuto;
  721. return InputHandler::TouchStartOrMoveEventListenerType::NO_HANDLER;
  722. }
  723. if (out_touch_action) {
  724. gfx::Transform layer_screen_space_transform =
  725. layer_impl_with_touch_handler->ScreenSpaceTransform();
  726. gfx::Transform inverse_layer_screen_space(
  727. gfx::Transform::kSkipInitialization);
  728. bool can_be_inversed =
  729. layer_screen_space_transform.GetInverse(&inverse_layer_screen_space);
  730. // Getting here indicates that |layer_impl_with_touch_handler| is non-null,
  731. // which means that the |hit| in FindClosestMatchingLayer() is true, which
  732. // indicates that the inverse is available.
  733. DCHECK(can_be_inversed);
  734. bool clipped = false;
  735. gfx::Point3F planar_point = MathUtil::ProjectPoint3D(
  736. inverse_layer_screen_space, device_viewport_point, &clipped);
  737. gfx::PointF hit_test_point_in_layer_space =
  738. gfx::PointF(planar_point.x(), planar_point.y());
  739. const auto& region = layer_impl_with_touch_handler->touch_action_region();
  740. gfx::Point point = gfx::ToRoundedPoint(hit_test_point_in_layer_space);
  741. *out_touch_action = region.GetAllowedTouchAction(point);
  742. }
  743. if (!CurrentlyScrollingNode())
  744. return InputHandler::TouchStartOrMoveEventListenerType::HANDLER;
  745. // Check if the touch start (or move) hits on the current scrolling layer or
  746. // its descendant. layer_impl_with_touch_handler is the layer hit by the
  747. // pointer and has an event handler, otherwise it is null. We want to compare
  748. // the most inner layer we are hitting on which may not have an event listener
  749. // with the actual scrolling layer.
  750. LayerImpl* layer_impl =
  751. ActiveTree().FindLayerThatIsHitByPoint(device_viewport_point);
  752. bool is_ancestor = IsScrolledBy(layer_impl, CurrentlyScrollingNode());
  753. return is_ancestor ? InputHandler::TouchStartOrMoveEventListenerType::
  754. HANDLER_ON_SCROLLING_LAYER
  755. : InputHandler::TouchStartOrMoveEventListenerType::HANDLER;
  756. }
  757. std::unique_ptr<LatencyInfoSwapPromiseMonitor>
  758. InputHandler::CreateLatencyInfoSwapPromiseMonitor(ui::LatencyInfo* latency) {
  759. return compositor_delegate_.GetImplDeprecated()
  760. .CreateLatencyInfoSwapPromiseMonitor(latency);
  761. }
  762. std::unique_ptr<EventsMetricsManager::ScopedMonitor>
  763. InputHandler::GetScopedEventMetricsMonitor(
  764. EventsMetricsManager::ScopedMonitor::DoneCallback done_callback) {
  765. return compositor_delegate_.GetImplDeprecated().GetScopedEventMetricsMonitor(
  766. std::move(done_callback));
  767. }
  768. ScrollElasticityHelper* InputHandler::CreateScrollElasticityHelper() {
  769. DCHECK(!scroll_elasticity_helper_);
  770. if (compositor_delegate_.GetSettings().enable_elastic_overscroll) {
  771. scroll_elasticity_helper_.reset(
  772. ScrollElasticityHelper::CreateForLayerTreeHostImpl(
  773. &compositor_delegate_.GetImplDeprecated()));
  774. }
  775. return scroll_elasticity_helper_.get();
  776. }
  777. void InputHandler::DestroyScrollElasticityHelper() {
  778. // Remove any stretch before destroying helper.
  779. scroll_elasticity_helper_->SetStretchAmount(gfx::Vector2dF());
  780. scroll_elasticity_helper_.reset();
  781. }
  782. bool InputHandler::GetScrollOffsetForLayer(ElementId element_id,
  783. gfx::PointF* offset) {
  784. ScrollTree& scroll_tree = GetScrollTree();
  785. ScrollNode* scroll_node = scroll_tree.FindNodeFromElementId(element_id);
  786. if (!scroll_node)
  787. return false;
  788. *offset = scroll_tree.current_scroll_offset(element_id);
  789. return true;
  790. }
  791. bool InputHandler::ScrollLayerTo(ElementId element_id,
  792. const gfx::PointF& offset) {
  793. ScrollTree& scroll_tree = GetScrollTree();
  794. ScrollNode* scroll_node = scroll_tree.FindNodeFromElementId(element_id);
  795. if (!scroll_node)
  796. return false;
  797. scroll_tree.ScrollBy(*scroll_node,
  798. offset - scroll_tree.current_scroll_offset(element_id),
  799. &ActiveTree());
  800. return true;
  801. }
  802. bool InputHandler::ScrollingShouldSwitchtoMainThread() {
  803. DCHECK(!base::FeatureList::IsEnabled(features::kScrollUnification));
  804. ScrollTree& scroll_tree = GetScrollTree();
  805. ScrollNode* scroll_node = scroll_tree.CurrentlyScrollingNode();
  806. if (!scroll_node)
  807. return true;
  808. for (; scroll_tree.parent(scroll_node);
  809. scroll_node = scroll_tree.parent(scroll_node)) {
  810. if (!!scroll_node->main_thread_scrolling_reasons)
  811. return true;
  812. }
  813. return false;
  814. }
  815. bool InputHandler::GetSnapFlingInfoAndSetAnimatingSnapTarget(
  816. const gfx::Vector2dF& natural_displacement_in_viewport,
  817. gfx::PointF* out_initial_position,
  818. gfx::PointF* out_target_position) {
  819. ScrollNode* scroll_node = CurrentlyScrollingNode();
  820. if (!scroll_node || !scroll_node->snap_container_data.has_value())
  821. return false;
  822. const SnapContainerData& data = scroll_node->snap_container_data.value();
  823. float scale_factor = ActiveTree().page_scale_factor_for_scroll();
  824. gfx::Vector2dF natural_displacement_in_content =
  825. gfx::ScaleVector2d(natural_displacement_in_viewport, 1.f / scale_factor);
  826. gfx::PointF current_offset = GetVisualScrollOffset(*scroll_node);
  827. *out_initial_position = current_offset;
  828. // CC side always uses fractional scroll deltas.
  829. bool use_fractional_offsets = true;
  830. TargetSnapAreaElementIds snap_target_ids;
  831. std::unique_ptr<SnapSelectionStrategy> strategy =
  832. SnapSelectionStrategy::CreateForEndAndDirection(
  833. current_offset, natural_displacement_in_content,
  834. use_fractional_offsets);
  835. if (!data.FindSnapPosition(*strategy, out_target_position, &snap_target_ids))
  836. return false;
  837. scroll_animating_snap_target_ids_ = snap_target_ids;
  838. out_target_position->Scale(scale_factor);
  839. out_initial_position->Scale(scale_factor);
  840. return true;
  841. }
  842. void InputHandler::ScrollEndForSnapFling(bool did_finish) {
  843. ScrollNode* scroll_node = CurrentlyScrollingNode();
  844. // When a snap fling animation reaches its intended target then we update the
  845. // scrolled node's snap targets. This also ensures blink learns about the new
  846. // snap targets for this scrolling element.
  847. if (did_finish && scroll_node &&
  848. scroll_node->snap_container_data.has_value()) {
  849. scroll_node->snap_container_data.value().SetTargetSnapAreaElementIds(
  850. scroll_animating_snap_target_ids_);
  851. updated_snapped_elements_[scroll_node->element_id] =
  852. scroll_animating_snap_target_ids_;
  853. SetNeedsCommit();
  854. }
  855. scroll_animating_snap_target_ids_ = TargetSnapAreaElementIds();
  856. ScrollEnd(false /* should_snap */);
  857. }
  858. void InputHandler::NotifyInputEvent() {
  859. compositor_delegate_.GetImplDeprecated().NotifyInputEvent();
  860. }
  861. //
  862. // =========== InputDelegateForCompositor Interface
  863. //
  864. void InputHandler::ProcessCommitDeltas(CompositorCommitData* commit_data) {
  865. DCHECK(commit_data);
  866. if (ActiveTree().LayerListIsEmpty())
  867. return;
  868. ElementId inner_viewport_scroll_element_id =
  869. InnerViewportScrollNode() ? InnerViewportScrollNode()->element_id
  870. : ElementId();
  871. base::flat_map<ElementId, TargetSnapAreaElementIds> snapped_elements;
  872. updated_snapped_elements_.swap(snapped_elements);
  873. // Scroll commit data is stored in the scroll tree so it has its own method
  874. // for getting it.
  875. // TODO(bokan): It's a bug that CollectScrollDeltas is here, it means the
  876. // compositor cannot commit scroll changes without an InputHandler which it
  877. // should be able to. To move it back, we'll need to split out the
  878. // |snapped_elements| part of ScrollTree::CollectScrollDeltas though which is
  879. // an input responsibility.
  880. GetScrollTree().CollectScrollDeltas(
  881. commit_data, inner_viewport_scroll_element_id,
  882. compositor_delegate_.GetSettings().commit_fractional_scroll_deltas,
  883. snapped_elements);
  884. // Record and reset scroll source flags.
  885. DCHECK(!commit_data->manipulation_info);
  886. if (has_scrolled_by_wheel_)
  887. commit_data->manipulation_info |= kManipulationInfoWheel;
  888. if (has_scrolled_by_touch_)
  889. commit_data->manipulation_info |= kManipulationInfoTouch;
  890. if (has_scrolled_by_precisiontouchpad_)
  891. commit_data->manipulation_info |= kManipulationInfoPrecisionTouchPad;
  892. if (has_pinch_zoomed_)
  893. commit_data->manipulation_info |= kManipulationInfoPinchZoom;
  894. if (has_scrolled_by_scrollbar_)
  895. commit_data->manipulation_info |= kManipulationInfoScrollbar;
  896. has_scrolled_by_wheel_ = false;
  897. has_scrolled_by_touch_ = false;
  898. has_scrolled_by_precisiontouchpad_ = false;
  899. has_pinch_zoomed_ = false;
  900. has_scrolled_by_scrollbar_ = false;
  901. commit_data->scroll_gesture_did_end = scroll_gesture_did_end_;
  902. scroll_gesture_did_end_ = false;
  903. commit_data->overscroll_delta = overscroll_delta_for_main_thread_;
  904. overscroll_delta_for_main_thread_ = gfx::Vector2dF();
  905. // Use the |last_latched_scroller_| rather than the
  906. // |CurrentlyScrollingNode| since the latter may be cleared by a GSE before
  907. // we've committed these values to the main thread.
  908. // TODO(bokan): This is wrong - if we also started a scroll this frame then
  909. // this will clear this value for that scroll. https://crbug.com/1116780.
  910. commit_data->scroll_latched_element_id = last_latched_scroller_;
  911. if (commit_data->scroll_gesture_did_end)
  912. last_latched_scroller_ = ElementId();
  913. }
  914. void InputHandler::TickAnimations(base::TimeTicks monotonic_time) {
  915. if (input_handler_client_) {
  916. // This does not set did_animate, because if the InputHandlerClient
  917. // changes anything it will be through the InputHandler interface which
  918. // does SetNeedsRedraw.
  919. input_handler_client_->Animate(monotonic_time);
  920. }
  921. }
  922. void InputHandler::WillShutdown() {
  923. if (input_handler_client_) {
  924. input_handler_client_.ExtractAsDangling()->WillShutdown();
  925. }
  926. if (scroll_elasticity_helper_)
  927. scroll_elasticity_helper_.reset();
  928. }
  929. void InputHandler::WillDraw() {
  930. if (input_handler_client_)
  931. input_handler_client_->ReconcileElasticOverscrollAndRootScroll();
  932. }
  933. void InputHandler::WillBeginImplFrame(const viz::BeginFrameArgs& args) {
  934. if (input_handler_client_) {
  935. scrollbar_controller_->WillBeginImplFrame();
  936. input_handler_client_->DeliverInputForBeginFrame(args);
  937. }
  938. }
  939. void InputHandler::DidCommit() {
  940. // In high latency mode commit cannot finish within the same frame. We need to
  941. // flush input here to make sure they got picked up by |PrepareTiles()|.
  942. if (input_handler_client_ && compositor_delegate_.IsInHighLatencyMode())
  943. input_handler_client_->DeliverInputForHighLatencyMode();
  944. }
  945. void InputHandler::DidActivatePendingTree() {
  946. // The previous scrolling node might no longer exist in the new tree.
  947. if (!CurrentlyScrollingNode())
  948. ClearCurrentlyScrollingNode();
  949. // Activation can change the root scroll offset, so inform the synchronous
  950. // input handler.
  951. UpdateRootLayerStateForSynchronousInputHandler();
  952. }
  953. void InputHandler::RootLayerStateMayHaveChanged() {
  954. UpdateRootLayerStateForSynchronousInputHandler();
  955. }
  956. void InputHandler::DidRegisterScrollbar(ElementId scroll_element_id,
  957. ScrollbarOrientation orientation) {
  958. scrollbar_controller_->DidRegisterScrollbar(scroll_element_id, orientation);
  959. }
  960. void InputHandler::DidUnregisterScrollbar(ElementId scroll_element_id,
  961. ScrollbarOrientation orientation) {
  962. scrollbar_controller_->DidUnregisterScrollbar(scroll_element_id, orientation);
  963. }
  964. void InputHandler::ScrollOffsetAnimationFinished() {
  965. TRACE_EVENT0("cc", "InputHandler::ScrollOffsetAnimationFinished");
  966. // ScrollOffsetAnimationFinished is called in two cases:
  967. // 1- smooth scrolling animation is over (IsAnimatingForSnap == false).
  968. // 2- snap scroll animation is over (IsAnimatingForSnap == true).
  969. //
  970. // Only for case (1) we should check and run snap scroll animation if needed.
  971. if (!IsAnimatingForSnap() &&
  972. SnapAtScrollEnd(SnapReason::kScrollOffsetAnimationFinished))
  973. return;
  974. // The end of a scroll offset animation means that the scrolling node is at
  975. // the target offset.
  976. ScrollNode* scroll_node = CurrentlyScrollingNode();
  977. if (scroll_node && scroll_node->snap_container_data.has_value()) {
  978. scroll_node->snap_container_data.value().SetTargetSnapAreaElementIds(
  979. scroll_animating_snap_target_ids_);
  980. updated_snapped_elements_[scroll_node->element_id] =
  981. scroll_animating_snap_target_ids_;
  982. SetNeedsCommit();
  983. }
  984. scroll_animating_snap_target_ids_ = TargetSnapAreaElementIds();
  985. // Call scrollEnd with the deferred scroll end state when the scroll animation
  986. // completes after GSE arrival.
  987. if (deferred_scroll_end_) {
  988. ScrollEnd(/*should_snap=*/false);
  989. return;
  990. }
  991. }
  992. void InputHandler::SetPrefersReducedMotion(bool prefers_reduced_motion) {
  993. if (prefers_reduced_motion_ == prefers_reduced_motion)
  994. return;
  995. prefers_reduced_motion_ = prefers_reduced_motion;
  996. if (input_handler_client_)
  997. input_handler_client_->SetPrefersReducedMotion(prefers_reduced_motion_);
  998. }
  999. bool InputHandler::IsCurrentlyScrolling() const {
  1000. return CurrentlyScrollingNode();
  1001. }
  1002. ActivelyScrollingType InputHandler::GetActivelyScrollingType() const {
  1003. if (!CurrentlyScrollingNode())
  1004. return ActivelyScrollingType::kNone;
  1005. if (!last_scroll_update_state_)
  1006. return ActivelyScrollingType::kNone;
  1007. if (!delta_consumed_for_scroll_gesture_)
  1008. return ActivelyScrollingType::kNone;
  1009. if (ShouldAnimateScroll(last_scroll_update_state_.value()))
  1010. return ActivelyScrollingType::kAnimated;
  1011. return ActivelyScrollingType::kPrecise;
  1012. }
  1013. ScrollNode* InputHandler::CurrentlyScrollingNode() {
  1014. return GetScrollTree().CurrentlyScrollingNode();
  1015. }
  1016. const ScrollNode* InputHandler::CurrentlyScrollingNode() const {
  1017. return GetScrollTree().CurrentlyScrollingNode();
  1018. }
  1019. ScrollTree& InputHandler::GetScrollTree() {
  1020. return compositor_delegate_.GetScrollTree();
  1021. }
  1022. ScrollTree& InputHandler::GetScrollTree() const {
  1023. return compositor_delegate_.GetScrollTree();
  1024. }
  1025. ScrollNode* InputHandler::InnerViewportScrollNode() const {
  1026. return ActiveTree().InnerViewportScrollNode();
  1027. }
  1028. ScrollNode* InputHandler::OuterViewportScrollNode() const {
  1029. return ActiveTree().OuterViewportScrollNode();
  1030. }
  1031. Viewport& InputHandler::GetViewport() const {
  1032. return compositor_delegate_.GetImplDeprecated().viewport();
  1033. }
  1034. void InputHandler::SetNeedsCommit() {
  1035. compositor_delegate_.SetNeedsCommit();
  1036. }
  1037. LayerTreeImpl& InputHandler::ActiveTree() {
  1038. DCHECK(compositor_delegate_.GetImplDeprecated().active_tree());
  1039. return *compositor_delegate_.GetImplDeprecated().active_tree();
  1040. }
  1041. LayerTreeImpl& InputHandler::ActiveTree() const {
  1042. DCHECK(compositor_delegate_.GetImplDeprecated().active_tree());
  1043. return *compositor_delegate_.GetImplDeprecated().active_tree();
  1044. }
  1045. FrameSequenceTrackerType InputHandler::GetTrackerTypeForScroll(
  1046. ui::ScrollInputType input_type) const {
  1047. switch (input_type) {
  1048. case ui::ScrollInputType::kWheel:
  1049. return FrameSequenceTrackerType::kWheelScroll;
  1050. case ui::ScrollInputType::kTouchscreen:
  1051. return FrameSequenceTrackerType::kTouchScroll;
  1052. case ui::ScrollInputType::kScrollbar:
  1053. return FrameSequenceTrackerType::kScrollbarScroll;
  1054. case ui::ScrollInputType::kAutoscroll:
  1055. return FrameSequenceTrackerType::kMaxType;
  1056. }
  1057. }
  1058. bool InputHandler::IsMainThreadScrolling(
  1059. const InputHandler::ScrollStatus& status,
  1060. const ScrollNode* scroll_node) const {
  1061. if (status.thread == InputHandler::ScrollThread::SCROLL_ON_MAIN_THREAD) {
  1062. if (!!scroll_node->main_thread_scrolling_reasons) {
  1063. DCHECK(MainThreadScrollingReason::MainThreadCanSetScrollReasons(
  1064. status.main_thread_scrolling_reasons));
  1065. } else {
  1066. DCHECK(MainThreadScrollingReason::CompositorCanSetScrollReasons(
  1067. status.main_thread_scrolling_reasons));
  1068. }
  1069. return true;
  1070. }
  1071. return false;
  1072. }
  1073. float InputHandler::LineStep() const {
  1074. return kPixelsPerLineStep;
  1075. }
  1076. // TODO(mehdika): There is some redundancy between this function and
  1077. // ScrollbarController::GetScrollDistanceForScrollbarPart, these two need to be
  1078. // kept in sync.
  1079. gfx::Vector2dF InputHandler::ResolveScrollGranularityToPixels(
  1080. const ScrollNode& scroll_node,
  1081. const gfx::Vector2dF& scroll_delta,
  1082. ui::ScrollGranularity granularity) {
  1083. gfx::Vector2dF pixel_delta = scroll_delta;
  1084. if (granularity == ui::ScrollGranularity::kScrollByPage) {
  1085. // Page should use a percentage of the scroller so change the parameters
  1086. // and let the percentage case below resolve it.
  1087. granularity = ui::ScrollGranularity::kScrollByPercentage;
  1088. pixel_delta.Scale(kMinFractionToStepWhenPaging);
  1089. }
  1090. if (granularity == ui::ScrollGranularity::kScrollByPercentage) {
  1091. gfx::SizeF scroller_size = gfx::SizeF(scroll_node.container_bounds);
  1092. gfx::SizeF viewport_size(compositor_delegate_.VisualDeviceViewportSize());
  1093. // Convert from rootframe coordinates to screen coordinates (physical
  1094. // pixels if --use-zoom-for-dsf enabled, DIPs otherwise).
  1095. scroller_size.Scale(compositor_delegate_.PageScaleFactor());
  1096. // Convert from physical pixels to screen coordinates (if --use-zoom-for-dsf
  1097. // enabled, `DeviceScaleFactor()` returns 1).
  1098. viewport_size.Scale(1 / compositor_delegate_.DeviceScaleFactor());
  1099. pixel_delta = ScrollUtils::ResolveScrollPercentageToPixels(
  1100. pixel_delta, scroller_size, viewport_size);
  1101. }
  1102. if (granularity == ui::ScrollGranularity::kScrollByLine) {
  1103. pixel_delta.Scale(LineStep(), LineStep());
  1104. }
  1105. return pixel_delta;
  1106. }
  1107. InputHandler::ScrollStatus InputHandler::TryScroll(
  1108. const ScrollTree& scroll_tree,
  1109. ScrollNode* scroll_node) const {
  1110. DCHECK(!base::FeatureList::IsEnabled(features::kScrollUnification));
  1111. InputHandler::ScrollStatus scroll_status;
  1112. scroll_status.main_thread_scrolling_reasons =
  1113. MainThreadScrollingReason::kNotScrollingOnMain;
  1114. if (scroll_node->main_thread_scrolling_reasons) {
  1115. TRACE_EVENT1("cc", "LayerImpl::TryScroll: Failed ShouldScrollOnMainThread",
  1116. "MainThreadScrollingReason",
  1117. scroll_node->main_thread_scrolling_reasons);
  1118. scroll_status.thread = InputHandler::ScrollThread::SCROLL_ON_MAIN_THREAD;
  1119. scroll_status.main_thread_scrolling_reasons =
  1120. scroll_node->main_thread_scrolling_reasons;
  1121. return scroll_status;
  1122. }
  1123. gfx::Transform screen_space_transform =
  1124. scroll_tree.ScreenSpaceTransform(scroll_node->id);
  1125. if (!screen_space_transform.IsInvertible()) {
  1126. TRACE_EVENT0("cc", "LayerImpl::TryScroll: Ignored NonInvertibleTransform");
  1127. scroll_status.thread = InputHandler::ScrollThread::SCROLL_IGNORED;
  1128. scroll_status.main_thread_scrolling_reasons =
  1129. MainThreadScrollingReason::kNonInvertibleTransform;
  1130. return scroll_status;
  1131. }
  1132. if (!scroll_node->scrollable) {
  1133. TRACE_EVENT0("cc", "LayerImpl::tryScroll: Ignored not scrollable");
  1134. scroll_status.thread = InputHandler::ScrollThread::SCROLL_IGNORED;
  1135. scroll_status.main_thread_scrolling_reasons =
  1136. MainThreadScrollingReason::kNotScrollable;
  1137. return scroll_status;
  1138. }
  1139. // If an associated scrolling layer is not found, the scroll node must not
  1140. // support impl-scrolling. The root, secondary root, and inner viewports
  1141. // are all exceptions to this and may not have a layer because it is not
  1142. // required for hit testing.
  1143. if (scroll_node->id != kRootPropertyNodeId &&
  1144. scroll_node->id != kSecondaryRootPropertyNodeId &&
  1145. !scroll_node->scrolls_inner_viewport &&
  1146. !ActiveTree().LayerByElementId(scroll_node->element_id)) {
  1147. TRACE_EVENT0("cc",
  1148. "LayerImpl::tryScroll: Failed due to no scrolling layer");
  1149. scroll_status.thread = InputHandler::ScrollThread::SCROLL_ON_MAIN_THREAD;
  1150. scroll_status.main_thread_scrolling_reasons =
  1151. MainThreadScrollingReason::kNoScrollingLayer;
  1152. return scroll_status;
  1153. }
  1154. // The a viewport node should be scrolled even if it has no scroll extent
  1155. // since it'll scroll using the Viewport class which will generate browser
  1156. // controls movement and overscroll delta.
  1157. gfx::PointF max_scroll_offset = scroll_tree.MaxScrollOffset(scroll_node->id);
  1158. if (max_scroll_offset.x() <= 0 && max_scroll_offset.y() <= 0 &&
  1159. !GetViewport().ShouldScroll(*scroll_node)) {
  1160. TRACE_EVENT0("cc",
  1161. "LayerImpl::tryScroll: Ignored. Technically scrollable,"
  1162. " but has no affordance in either direction.");
  1163. scroll_status.thread = InputHandler::ScrollThread::SCROLL_IGNORED;
  1164. scroll_status.main_thread_scrolling_reasons =
  1165. MainThreadScrollingReason::kNotScrollable;
  1166. return scroll_status;
  1167. }
  1168. scroll_status.thread = InputHandler::ScrollThread::SCROLL_ON_IMPL_THREAD;
  1169. return scroll_status;
  1170. }
  1171. base::flat_set<int> InputHandler::NonFastScrollableNodes(
  1172. const gfx::PointF& device_viewport_point) const {
  1173. base::flat_set<int> non_fast_scrollable_nodes;
  1174. const auto& non_fast_layers =
  1175. ActiveTree().FindLayersHitByPointInNonFastScrollableRegion(
  1176. device_viewport_point);
  1177. for (const auto* layer : non_fast_layers)
  1178. non_fast_scrollable_nodes.insert(layer->scroll_tree_index());
  1179. return non_fast_scrollable_nodes;
  1180. }
  1181. ScrollNode* InputHandler::FindScrollNodeForCompositedScrolling(
  1182. const gfx::PointF& device_viewport_point,
  1183. LayerImpl* layer_impl,
  1184. bool* scroll_on_main_thread,
  1185. uint32_t* main_thread_scrolling_reasons) {
  1186. DCHECK(!base::FeatureList::IsEnabled(features::kScrollUnification));
  1187. DCHECK(scroll_on_main_thread);
  1188. DCHECK(main_thread_scrolling_reasons);
  1189. *main_thread_scrolling_reasons =
  1190. MainThreadScrollingReason::kNotScrollingOnMain;
  1191. const auto& non_fast_scrollable_nodes =
  1192. NonFastScrollableNodes(device_viewport_point);
  1193. // Walk up the hierarchy and look for a scrollable layer.
  1194. ScrollTree& scroll_tree = GetScrollTree();
  1195. ScrollNode* impl_scroll_node = nullptr;
  1196. if (layer_impl) {
  1197. // If this is a scrollbar layer, we can't directly use the associated
  1198. // scroll_node (because the scroll_node associated with this layer will be
  1199. // the owning scroller's parent). Instead, we first retrieve the scrollable
  1200. // layer corresponding to the scrollbars owner and then use its
  1201. // scroll_tree_index instead.
  1202. int scroll_tree_index = layer_impl->scroll_tree_index();
  1203. if (layer_impl->IsScrollbarLayer()) {
  1204. LayerImpl* owner_scroll_layer = ActiveTree().LayerByElementId(
  1205. ToScrollbarLayer(layer_impl)->scroll_element_id());
  1206. scroll_tree_index = owner_scroll_layer->scroll_tree_index();
  1207. }
  1208. ScrollNode* scroll_node = scroll_tree.Node(scroll_tree_index);
  1209. for (; scroll_tree.parent(scroll_node);
  1210. scroll_node = scroll_tree.parent(scroll_node)) {
  1211. // The content layer can also block attempts to scroll outside the main
  1212. // thread.
  1213. InputHandler::ScrollStatus status = TryScroll(scroll_tree, scroll_node);
  1214. if (IsMainThreadScrolling(status, scroll_node)) {
  1215. *scroll_on_main_thread = true;
  1216. *main_thread_scrolling_reasons = status.main_thread_scrolling_reasons;
  1217. return scroll_node;
  1218. }
  1219. if (non_fast_scrollable_nodes.contains(scroll_node->id)) {
  1220. *scroll_on_main_thread = true;
  1221. *main_thread_scrolling_reasons =
  1222. MainThreadScrollingReason::kNonFastScrollableRegion;
  1223. return scroll_node;
  1224. }
  1225. if (status.thread == InputHandler::ScrollThread::SCROLL_ON_IMPL_THREAD &&
  1226. !impl_scroll_node) {
  1227. impl_scroll_node = scroll_node;
  1228. }
  1229. }
  1230. }
  1231. // TODO(bokan): We shouldn't need this - ordinarily all scrolls should pass
  1232. // through the outer viewport. If we aren't able to find a scroller we should
  1233. // return nullptr here and ignore the scroll. However, it looks like on some
  1234. // pages (reddit.com) we start scrolling from the inner node.
  1235. if (!impl_scroll_node)
  1236. impl_scroll_node = InnerViewportScrollNode();
  1237. if (!impl_scroll_node)
  1238. return nullptr;
  1239. impl_scroll_node = GetNodeToScroll(impl_scroll_node);
  1240. // Ensure that final scroll node scrolls on impl thread (crbug.com/625100)
  1241. InputHandler::ScrollStatus status = TryScroll(scroll_tree, impl_scroll_node);
  1242. if (IsMainThreadScrolling(status, impl_scroll_node)) {
  1243. *scroll_on_main_thread = true;
  1244. *main_thread_scrolling_reasons = status.main_thread_scrolling_reasons;
  1245. } else if (non_fast_scrollable_nodes.contains(impl_scroll_node->id)) {
  1246. *scroll_on_main_thread = true;
  1247. *main_thread_scrolling_reasons =
  1248. MainThreadScrollingReason::kNonFastScrollableRegion;
  1249. }
  1250. return impl_scroll_node;
  1251. }
  1252. InputHandler::ScrollHitTestResult InputHandler::HitTestScrollNode(
  1253. const gfx::PointF& device_viewport_point) const {
  1254. ScrollHitTestResult result;
  1255. result.scroll_node = nullptr;
  1256. result.hit_test_successful = false;
  1257. std::vector<const LayerImpl*> layers =
  1258. ActiveTree().FindAllLayersUpToAndIncludingFirstScrollable(
  1259. device_viewport_point);
  1260. const LayerImpl* scroller_layer =
  1261. (!layers.empty() && layers.back()->IsScrollerOrScrollbar())
  1262. ? layers.back()
  1263. : nullptr;
  1264. // Go through each layer up to (and including) the scroller. Any may block
  1265. // scrolling if they come from outside the scroller's scroll-subtree or if we
  1266. // hit a non-fast-scrolling-region.
  1267. for (const auto* layer_impl : layers) {
  1268. // There are some cases where the hit layer may not be correct (e.g. layer
  1269. // squashing, pointer-events:none layer) because the compositor doesn't
  1270. // know what parts of the layer (if any) are actually visible to hit
  1271. // testing. This is fine if we can determine that the scrolling node will
  1272. // be the same regardless of whether we hit an opaque or transparent (to
  1273. // hit testing) point of the layer. If the scrolling node may depend on
  1274. // this, we have to get a hit test from the main thread.
  1275. if (!IsInitialScrollHitTestReliable(layer_impl, scroller_layer)) {
  1276. TRACE_EVENT_INSTANT0("cc", "Failed Hit Test", TRACE_EVENT_SCOPE_THREAD);
  1277. return result;
  1278. }
  1279. // If we hit a non-fast scrollable region, that means there's some reason we
  1280. // can't scroll in this region. Primarily, because there's another scroller
  1281. // there that isn't composited and we don't know about so we'll return
  1282. // failure.
  1283. if (ActiveTree().PointHitsNonFastScrollableRegion(device_viewport_point,
  1284. *layer_impl)) {
  1285. return result;
  1286. }
  1287. }
  1288. // It's theoretically possible to hit no layers or only non-scrolling layers.
  1289. // e.g. an API hit test outside the viewport, or sending a scroll to an OOPIF
  1290. // that does not have overflow. If we made it to here, we also don't have any
  1291. // non-fast scroll regions. Fallback to scrolling the viewport.
  1292. if (!scroller_layer) {
  1293. result.hit_test_successful = true;
  1294. if (InnerViewportScrollNode())
  1295. result.scroll_node = GetNodeToScroll(InnerViewportScrollNode());
  1296. return result;
  1297. }
  1298. // If we hit a scrollbar layer, get the ScrollNode from its associated
  1299. // scrolling layer, rather than directly from the scrollbar layer. The latter
  1300. // would return the parent scroller's ScrollNode.
  1301. if (scroller_layer->IsScrollbarLayer()) {
  1302. scroller_layer = ActiveTree().LayerByElementId(
  1303. ToScrollbarLayer(scroller_layer)->scroll_element_id());
  1304. DCHECK(scroller_layer);
  1305. }
  1306. ScrollNode* scroll_node =
  1307. GetScrollTree().Node(scroller_layer->scroll_tree_index());
  1308. result.scroll_node = GetNodeToScroll(scroll_node);
  1309. result.hit_test_successful = true;
  1310. return result;
  1311. }
  1312. // Requires falling back to main thread scrolling when it hit tests in scrollbar
  1313. // from touch.
  1314. bool InputHandler::IsTouchDraggingScrollbar(
  1315. LayerImpl* first_scrolling_layer_or_scrollbar,
  1316. ui::ScrollInputType type) {
  1317. return first_scrolling_layer_or_scrollbar &&
  1318. first_scrolling_layer_or_scrollbar->IsScrollbarLayer() &&
  1319. type == ui::ScrollInputType::kTouchscreen;
  1320. }
  1321. ScrollNode* InputHandler::GetNodeToScroll(ScrollNode* node) const {
  1322. // Blink has a notion of a "root scroller", which is the scroller in a page
  1323. // that is considered to host the main content. Typically this will be the
  1324. // document/LayoutView contents; however, in some situations Blink may choose
  1325. // a sub-scroller (div, iframe) that should scroll with "viewport" behavior.
  1326. // The "root scroller" is the node designated as the outer viewport in CC.
  1327. // See third_party/blink/renderer/core/page/scrolling/README.md for details.
  1328. //
  1329. // "Viewport" scrolling ensures generation of overscroll events, top controls
  1330. // movement, as well as correct multi-viewport panning in pinch-zoom and
  1331. // other scenarios. We use the viewport's outer scroll node to represent the
  1332. // viewport in the scroll chain and apply scroll delta using CC's Viewport
  1333. // class.
  1334. //
  1335. // Scrolling from position: fixed layers will chain directly up to the inner
  1336. // viewport. Whether that should use the outer viewport (and thus the
  1337. // Viewport class) to scroll or not depends on the root scroller scenario
  1338. // because we don't want setting a root scroller to change the scroll chain
  1339. // order. The |prevent_viewport_scrolling_from_inner| bit is used to
  1340. // communicate that context.
  1341. DCHECK(!node->prevent_viewport_scrolling_from_inner ||
  1342. node->scrolls_inner_viewport);
  1343. if (node->scrolls_inner_viewport &&
  1344. !node->prevent_viewport_scrolling_from_inner) {
  1345. DCHECK(OuterViewportScrollNode());
  1346. return OuterViewportScrollNode();
  1347. }
  1348. return node;
  1349. }
  1350. bool InputHandler::IsInitialScrollHitTestReliable(
  1351. const LayerImpl* layer_impl,
  1352. const LayerImpl* first_scrolling_layer_or_scrollbar) const {
  1353. if (!first_scrolling_layer_or_scrollbar)
  1354. return true;
  1355. // Hit tests directly on a composited scrollbar are always reliable.
  1356. if (layer_impl->IsScrollbarLayer()) {
  1357. DCHECK(layer_impl == first_scrolling_layer_or_scrollbar);
  1358. return true;
  1359. }
  1360. ScrollNode* closest_scroll_node = nullptr;
  1361. auto& scroll_tree = GetScrollTree();
  1362. ScrollNode* scroll_node = scroll_tree.Node(layer_impl->scroll_tree_index());
  1363. for (; scroll_tree.parent(scroll_node);
  1364. scroll_node = scroll_tree.parent(scroll_node)) {
  1365. // TODO(bokan): |scrollable| appears to always be true in LayerList mode.
  1366. // In non-LayerList, scroll hit tests should always be reliable because we
  1367. // don't have situations where a layer can be hit testable but pass some
  1368. // points through (e.g. squashing layers). Perhaps we can remove this
  1369. // condition?
  1370. if (scroll_node->scrollable) {
  1371. closest_scroll_node = GetNodeToScroll(scroll_node);
  1372. break;
  1373. }
  1374. }
  1375. if (!closest_scroll_node)
  1376. return false;
  1377. // If |first_scrolling_layer_or_scrollbar| is not a scrollbar, it must be
  1378. // a scrollabe layer with a scroll node. If this scroll node corresponds to
  1379. // first scrollable ancestor along the scroll tree for |layer_impl|, the hit
  1380. // test has not escaped to other areas of the scroll tree and is reliable.
  1381. if (!first_scrolling_layer_or_scrollbar->IsScrollbarLayer()) {
  1382. return closest_scroll_node->id ==
  1383. first_scrolling_layer_or_scrollbar->scroll_tree_index();
  1384. }
  1385. return false;
  1386. }
  1387. gfx::Vector2dF InputHandler::ComputeScrollDelta(const ScrollNode& scroll_node,
  1388. const gfx::Vector2dF& delta) {
  1389. ScrollTree& scroll_tree = GetScrollTree();
  1390. float scale_factor = compositor_delegate_.PageScaleFactor();
  1391. gfx::Vector2dF adjusted_scroll(delta);
  1392. adjusted_scroll.Scale(1.f / scale_factor);
  1393. adjusted_scroll = UserScrollableDelta(scroll_node, adjusted_scroll);
  1394. gfx::PointF old_offset =
  1395. scroll_tree.current_scroll_offset(scroll_node.element_id);
  1396. gfx::PointF new_offset = scroll_tree.ClampScrollOffsetToLimits(
  1397. old_offset + adjusted_scroll, scroll_node);
  1398. return new_offset - old_offset;
  1399. }
  1400. bool InputHandler::CalculateLocalScrollDeltaAndStartPoint(
  1401. const ScrollNode& scroll_node,
  1402. const gfx::PointF& viewport_point,
  1403. const gfx::Vector2dF& viewport_delta,
  1404. gfx::Vector2dF* out_local_scroll_delta,
  1405. gfx::PointF* out_local_start_point /*= nullptr*/) {
  1406. // Layers with non-invertible screen space transforms should not have passed
  1407. // the scroll hit test in the first place.
  1408. const gfx::Transform screen_space_transform =
  1409. GetScrollTree().ScreenSpaceTransform(scroll_node.id);
  1410. DCHECK(screen_space_transform.IsInvertible());
  1411. gfx::Transform inverse_screen_space_transform(
  1412. gfx::Transform::kSkipInitialization);
  1413. bool did_invert =
  1414. screen_space_transform.GetInverse(&inverse_screen_space_transform);
  1415. // TODO(shawnsingh): With the advent of impl-side scrolling for non-root
  1416. // layers, we may need to explicitly handle uninvertible transforms here.
  1417. DCHECK(did_invert);
  1418. float scale_from_viewport_to_screen_space =
  1419. compositor_delegate_.DeviceScaleFactor();
  1420. gfx::PointF screen_space_point =
  1421. gfx::ScalePoint(viewport_point, scale_from_viewport_to_screen_space);
  1422. gfx::Vector2dF screen_space_delta = viewport_delta;
  1423. screen_space_delta.Scale(scale_from_viewport_to_screen_space);
  1424. // Project the scroll start and end points to local layer space to find the
  1425. // scroll delta in layer coordinates.
  1426. bool start_clipped, end_clipped;
  1427. gfx::PointF screen_space_end_point = screen_space_point + screen_space_delta;
  1428. gfx::PointF local_start_point = MathUtil::ProjectPoint(
  1429. inverse_screen_space_transform, screen_space_point, &start_clipped);
  1430. gfx::PointF local_end_point = MathUtil::ProjectPoint(
  1431. inverse_screen_space_transform, screen_space_end_point, &end_clipped);
  1432. DCHECK(out_local_scroll_delta);
  1433. *out_local_scroll_delta = local_end_point - local_start_point;
  1434. if (out_local_start_point)
  1435. *out_local_start_point = local_start_point;
  1436. if (start_clipped || end_clipped)
  1437. return false;
  1438. return true;
  1439. }
  1440. gfx::Vector2dF InputHandler::ScrollNodeWithViewportSpaceDelta(
  1441. const ScrollNode& scroll_node,
  1442. const gfx::PointF& viewport_point,
  1443. const gfx::Vector2dF& viewport_delta) {
  1444. ScrollTree& scroll_tree = GetScrollTree();
  1445. gfx::PointF local_start_point;
  1446. gfx::Vector2dF local_scroll_delta;
  1447. if (!CalculateLocalScrollDeltaAndStartPoint(
  1448. scroll_node, viewport_point, viewport_delta, &local_scroll_delta,
  1449. &local_start_point)) {
  1450. return gfx::Vector2dF();
  1451. }
  1452. bool scrolls_outer_viewport = scroll_node.scrolls_outer_viewport;
  1453. TRACE_EVENT2("cc", "ScrollNodeWithViewportSpaceDelta", "delta_y",
  1454. local_scroll_delta.y(), "is_outer", scrolls_outer_viewport);
  1455. // Apply the scroll delta.
  1456. gfx::PointF previous_offset =
  1457. scroll_tree.current_scroll_offset(scroll_node.element_id);
  1458. scroll_tree.ScrollBy(scroll_node, local_scroll_delta, &ActiveTree());
  1459. gfx::Vector2dF scrolled =
  1460. scroll_tree.current_scroll_offset(scroll_node.element_id) -
  1461. previous_offset;
  1462. TRACE_EVENT_INSTANT1("cc", "ConsumedDelta", TRACE_EVENT_SCOPE_THREAD, "y",
  1463. scrolled.y());
  1464. // Get the end point in the layer's content space so we can apply its
  1465. // ScreenSpaceTransform.
  1466. gfx::PointF actual_local_end_point = local_start_point + scrolled;
  1467. // Calculate the applied scroll delta in viewport space coordinates.
  1468. bool end_clipped;
  1469. const gfx::Transform screen_space_transform =
  1470. scroll_tree.ScreenSpaceTransform(scroll_node.id);
  1471. gfx::PointF actual_screen_space_end_point = MathUtil::MapPoint(
  1472. screen_space_transform, actual_local_end_point, &end_clipped);
  1473. DCHECK(!end_clipped);
  1474. if (end_clipped)
  1475. return gfx::Vector2dF();
  1476. float scale_from_viewport_to_screen_space =
  1477. compositor_delegate_.DeviceScaleFactor();
  1478. gfx::PointF actual_viewport_end_point = gfx::ScalePoint(
  1479. actual_screen_space_end_point, 1.f / scale_from_viewport_to_screen_space);
  1480. return actual_viewport_end_point - viewport_point;
  1481. }
  1482. gfx::Vector2dF InputHandler::ScrollNodeWithLocalDelta(
  1483. const ScrollNode& scroll_node,
  1484. const gfx::Vector2dF& local_delta) const {
  1485. bool scrolls_outer_viewport = scroll_node.scrolls_outer_viewport;
  1486. TRACE_EVENT2("cc", "ScrollNodeWithLocalDelta", "delta_y", local_delta.y(),
  1487. "is_outer", scrolls_outer_viewport);
  1488. float page_scale_factor = compositor_delegate_.PageScaleFactor();
  1489. ScrollTree& scroll_tree = GetScrollTree();
  1490. gfx::PointF previous_offset =
  1491. scroll_tree.current_scroll_offset(scroll_node.element_id);
  1492. gfx::Vector2dF delta = local_delta;
  1493. delta.Scale(1.f / page_scale_factor);
  1494. scroll_tree.ScrollBy(scroll_node, delta, &ActiveTree());
  1495. gfx::Vector2dF scrolled =
  1496. scroll_tree.current_scroll_offset(scroll_node.element_id) -
  1497. previous_offset;
  1498. gfx::Vector2dF consumed_scroll(scrolled.x(), scrolled.y());
  1499. consumed_scroll.Scale(page_scale_factor);
  1500. TRACE_EVENT_INSTANT1("cc", "ConsumedDelta", TRACE_EVENT_SCOPE_THREAD, "y",
  1501. consumed_scroll.y());
  1502. return consumed_scroll;
  1503. }
  1504. // TODO(danakj): Make this into two functions, one with delta, one with
  1505. // viewport_point, no bool required.
  1506. gfx::Vector2dF InputHandler::ScrollSingleNode(const ScrollNode& scroll_node,
  1507. const gfx::Vector2dF& delta,
  1508. const gfx::Point& viewport_point,
  1509. bool is_direct_manipulation) {
  1510. gfx::Vector2dF adjusted_delta = UserScrollableDelta(scroll_node, delta);
  1511. // Events representing direct manipulation of the screen (such as gesture
  1512. // events) need to be transformed from viewport coordinates to local layer
  1513. // coordinates so that the scrolling contents exactly follow the user's
  1514. // finger. In contrast, events not representing direct manipulation of the
  1515. // screen (such as wheel events) represent a fixed amount of scrolling so we
  1516. // can just apply them directly, but the page scale factor is applied to the
  1517. // scroll delta.
  1518. if (is_direct_manipulation) {
  1519. // For touch-scroll we need to scale the delta here, as the transform tree
  1520. // won't know anything about the external page scale factors used by OOPIFs.
  1521. gfx::Vector2dF scaled_delta(adjusted_delta);
  1522. scaled_delta.Scale(1 / ActiveTree().external_page_scale_factor());
  1523. return ScrollNodeWithViewportSpaceDelta(
  1524. scroll_node, gfx::PointF(viewport_point), scaled_delta);
  1525. }
  1526. return ScrollNodeWithLocalDelta(scroll_node, adjusted_delta);
  1527. }
  1528. void InputHandler::ScrollLatchedScroller(ScrollState* scroll_state,
  1529. base::TimeDelta delayed_by) {
  1530. DCHECK(CurrentlyScrollingNode());
  1531. DCHECK(scroll_state);
  1532. DCHECK(latched_scroll_type_.has_value());
  1533. ScrollNode& scroll_node = *CurrentlyScrollingNode();
  1534. const gfx::Vector2dF delta(scroll_state->delta_x(), scroll_state->delta_y());
  1535. TRACE_EVENT2("cc", "InputHandler::ScrollLatchedScroller", "delta_x",
  1536. delta.x(), "delta_y", delta.y());
  1537. gfx::Vector2dF applied_delta;
  1538. gfx::Vector2dF delta_applied_to_content;
  1539. // TODO(tdresser): Use a more rational epsilon. See crbug.com/510550 for
  1540. // details.
  1541. const float kEpsilon = 0.1f;
  1542. if (ShouldAnimateScroll(*scroll_state)) {
  1543. DCHECK(!scroll_state->is_in_inertial_phase());
  1544. if (ElementId id = compositor_delegate_.GetImplDeprecated()
  1545. .mutator_host()
  1546. ->ImplOnlyScrollAnimatingElement()) {
  1547. TRACE_EVENT_INSTANT0("cc", "UpdateExistingAnimation",
  1548. TRACE_EVENT_SCOPE_THREAD);
  1549. ScrollNode* animating_scroll_node =
  1550. GetScrollTree().FindNodeFromElementId(id);
  1551. DCHECK(animating_scroll_node);
  1552. // Usually the CurrentlyScrollingNode will be the currently animating
  1553. // one. The one exception is the inner viewport. Scrolling the combined
  1554. // viewport will always set the outer viewport as the currently scrolling
  1555. // node. However, if an animation is created on the inner viewport we
  1556. // must use it when updating the animation curve.
  1557. DCHECK(animating_scroll_node->id == scroll_node.id ||
  1558. animating_scroll_node->scrolls_inner_viewport);
  1559. bool animation_updated = ScrollAnimationUpdateTarget(
  1560. *animating_scroll_node, delta, delayed_by);
  1561. if (animation_updated) {
  1562. // Because we updated the animation target, consume delta so we notify
  1563. // the `LatencyInfoSwapPromiseMonitor` to tell it that something
  1564. // happened that will cause a swap in the future. This will happen
  1565. // within the scope of the dispatch of a gesture scroll update input
  1566. // event. If we don't notify during the handling of the input event, the
  1567. // `LatencyInfo` associated with the input event will not be added as a
  1568. // swap promise and we won't get any swap results.
  1569. applied_delta = delta;
  1570. } else {
  1571. TRACE_EVENT_INSTANT0("cc", "Didn't Update Animation",
  1572. TRACE_EVENT_SCOPE_THREAD);
  1573. }
  1574. } else {
  1575. TRACE_EVENT_INSTANT0("cc", "CreateNewAnimation",
  1576. TRACE_EVENT_SCOPE_THREAD);
  1577. if (scroll_node.scrolls_outer_viewport) {
  1578. applied_delta = GetViewport().ScrollAnimated(delta, delayed_by);
  1579. } else {
  1580. applied_delta = ComputeScrollDelta(scroll_node, delta);
  1581. compositor_delegate_.GetImplDeprecated().ScrollAnimationCreate(
  1582. scroll_node, applied_delta, delayed_by);
  1583. }
  1584. }
  1585. // Animated scrolling always applied only to the content (i.e. not to the
  1586. // browser controls).
  1587. delta_applied_to_content = delta;
  1588. } else {
  1589. gfx::Point viewport_point(scroll_state->position_x(),
  1590. scroll_state->position_y());
  1591. if (GetViewport().ShouldScroll(scroll_node)) {
  1592. // |scrolls_outer_viewport| will only ever be false if the scroll chains
  1593. // up to the viewport without going through the outer viewport scroll
  1594. // node. This is because we normally terminate the scroll chain at the
  1595. // outer viewport node. For example, if we start scrolling from an
  1596. // element that's not a descendant of the root scroller. In these cases we
  1597. // want to scroll *only* the inner viewport -- to allow panning while
  1598. // zoomed -- but still use Viewport::ScrollBy to also move browser
  1599. // controls if needed.
  1600. Viewport::ScrollResult result = GetViewport().ScrollBy(
  1601. delta, viewport_point, scroll_state->is_direct_manipulation(),
  1602. latched_scroll_type_ != ui::ScrollInputType::kWheel,
  1603. scroll_node.scrolls_outer_viewport);
  1604. applied_delta = result.consumed_delta;
  1605. delta_applied_to_content = result.content_scrolled_delta;
  1606. } else {
  1607. applied_delta = ScrollSingleNode(scroll_node, delta, viewport_point,
  1608. scroll_state->is_direct_manipulation());
  1609. }
  1610. }
  1611. // If the layer wasn't able to move, try the next one in the hierarchy.
  1612. bool scrolled = std::abs(applied_delta.x()) > kEpsilon;
  1613. scrolled = scrolled || std::abs(applied_delta.y()) > kEpsilon;
  1614. if (!scrolled) {
  1615. // TODO(bokan): This preserves existing behavior by not allowing tiny
  1616. // scrolls to produce overscroll but is inconsistent in how delta gets
  1617. // chained up. We need to clean this up.
  1618. if (scroll_node.scrolls_outer_viewport)
  1619. scroll_state->ConsumeDelta(applied_delta.x(), applied_delta.y());
  1620. return;
  1621. }
  1622. if (!GetViewport().ShouldScroll(scroll_node)) {
  1623. // If the applied delta is within 45 degrees of the input
  1624. // delta, bail out to make it easier to scroll just one layer
  1625. // in one direction without affecting any of its parents.
  1626. float angle_threshold = 45;
  1627. if (MathUtil::SmallestAngleBetweenVectors(applied_delta, delta) <
  1628. angle_threshold) {
  1629. applied_delta = delta;
  1630. } else {
  1631. // Allow further movement only on an axis perpendicular to the direction
  1632. // in which the layer moved.
  1633. applied_delta = MathUtil::ProjectVector(delta, applied_delta);
  1634. }
  1635. delta_applied_to_content = applied_delta;
  1636. }
  1637. scroll_state->set_caused_scroll(
  1638. std::abs(delta_applied_to_content.x()) > kEpsilon,
  1639. std::abs(delta_applied_to_content.y()) > kEpsilon);
  1640. scroll_state->ConsumeDelta(applied_delta.x(), applied_delta.y());
  1641. }
  1642. bool InputHandler::CanPropagate(ScrollNode* scroll_node, float x, float y) {
  1643. return (x == 0 || scroll_node->overscroll_behavior.x ==
  1644. OverscrollBehavior::Type::kAuto) &&
  1645. (y == 0 || scroll_node->overscroll_behavior.y ==
  1646. OverscrollBehavior::Type::kAuto);
  1647. }
  1648. ScrollNode* InputHandler::FindNodeToLatch(ScrollState* scroll_state,
  1649. ScrollNode* starting_node,
  1650. ui::ScrollInputType type) {
  1651. ScrollTree& scroll_tree = GetScrollTree();
  1652. ScrollNode* scroll_node = nullptr;
  1653. ScrollNode* first_scrollable_node = nullptr;
  1654. for (ScrollNode* cur_node = starting_node; cur_node;
  1655. cur_node = scroll_tree.parent(cur_node)) {
  1656. if (GetViewport().ShouldScroll(*cur_node)) {
  1657. // Don't chain scrolls past a viewport node. Once we reach that, we
  1658. // should scroll using the appropriate viewport node which may not be
  1659. // |cur_node|.
  1660. scroll_node = GetNodeToScroll(cur_node);
  1661. break;
  1662. }
  1663. if (!cur_node->scrollable)
  1664. continue;
  1665. if (!first_scrollable_node) {
  1666. first_scrollable_node = cur_node;
  1667. }
  1668. if (CanConsumeDelta(*scroll_state, *cur_node)) {
  1669. scroll_node = cur_node;
  1670. break;
  1671. }
  1672. float delta_x = scroll_state->is_beginning() ? scroll_state->delta_x_hint()
  1673. : scroll_state->delta_x();
  1674. float delta_y = scroll_state->is_beginning() ? scroll_state->delta_y_hint()
  1675. : scroll_state->delta_y();
  1676. if (!CanPropagate(cur_node, delta_x, delta_y)) {
  1677. // If we reach a node with non-auto overscroll-behavior and we still
  1678. // haven't latched, we must latch to it. Consider a fully scrolled node
  1679. // with non-auto overscroll-behavior: we are not allowed to further
  1680. // chain scroll delta passed to it in the current direction but if we
  1681. // reverse direction we should scroll it so we must be latched to it.
  1682. scroll_node = cur_node;
  1683. scroll_state->set_is_scroll_chain_cut(true);
  1684. break;
  1685. }
  1686. }
  1687. // If the root scroller can not consume delta in an autoscroll, latch on
  1688. // to the top most autoscrollable scroller. See https://crbug.com/969150
  1689. if ((type == ui::ScrollInputType::kAutoscroll) && first_scrollable_node) {
  1690. // If scroll_node is nullptr or delta can not be consumed
  1691. if (!(scroll_node && CanConsumeDelta(*scroll_state, *scroll_node)))
  1692. scroll_node = first_scrollable_node;
  1693. }
  1694. return scroll_node;
  1695. }
  1696. void InputHandler::UpdateRootLayerStateForSynchronousInputHandler() {
  1697. if (!input_handler_client_)
  1698. return;
  1699. input_handler_client_->UpdateRootLayerStateForSynchronousInputHandler(
  1700. ActiveTree().TotalScrollOffset(), ActiveTree().TotalMaxScrollOffset(),
  1701. ActiveTree().ScrollableSize(), ActiveTree().current_page_scale_factor(),
  1702. ActiveTree().min_page_scale_factor(),
  1703. ActiveTree().max_page_scale_factor());
  1704. }
  1705. void InputHandler::DidLatchToScroller(const ScrollState& scroll_state,
  1706. ui::ScrollInputType type) {
  1707. DCHECK(CurrentlyScrollingNode());
  1708. deferred_scroll_end_ = false;
  1709. compositor_delegate_.GetImplDeprecated()
  1710. .browser_controls_manager()
  1711. ->ScrollBegin();
  1712. compositor_delegate_.GetImplDeprecated()
  1713. .mutator_host()
  1714. ->ScrollAnimationAbort();
  1715. scroll_animating_snap_target_ids_ = TargetSnapAreaElementIds();
  1716. last_latched_scroller_ = CurrentlyScrollingNode()->element_id;
  1717. latched_scroll_type_ = type;
  1718. last_scroll_begin_state_ = scroll_state;
  1719. compositor_delegate_.DidStartScroll();
  1720. RecordCompositorSlowScrollMetric(type, CC_THREAD);
  1721. UpdateScrollSourceInfo(scroll_state, type);
  1722. }
  1723. bool InputHandler::CanConsumeDelta(const ScrollState& scroll_state,
  1724. const ScrollNode& scroll_node) {
  1725. gfx::Vector2dF delta_to_scroll;
  1726. if (scroll_state.is_beginning()) {
  1727. delta_to_scroll = gfx::Vector2dF(scroll_state.delta_x_hint(),
  1728. scroll_state.delta_y_hint());
  1729. } else {
  1730. delta_to_scroll =
  1731. gfx::Vector2dF(scroll_state.delta_x(), scroll_state.delta_y());
  1732. }
  1733. if (delta_to_scroll == gfx::Vector2dF())
  1734. return true;
  1735. if (scroll_state.is_direct_manipulation()) {
  1736. gfx::Vector2dF local_scroll_delta;
  1737. if (!CalculateLocalScrollDeltaAndStartPoint(
  1738. scroll_node,
  1739. gfx::PointF(scroll_state.position_x(), scroll_state.position_y()),
  1740. delta_to_scroll, &local_scroll_delta)) {
  1741. return false;
  1742. }
  1743. delta_to_scroll = local_scroll_delta;
  1744. } else {
  1745. delta_to_scroll = ResolveScrollGranularityToPixels(
  1746. scroll_node, delta_to_scroll, scroll_state.delta_granularity());
  1747. }
  1748. if (ComputeScrollDelta(scroll_node, delta_to_scroll) != gfx::Vector2dF())
  1749. return true;
  1750. return false;
  1751. }
  1752. bool InputHandler::ShouldAnimateScroll(const ScrollState& scroll_state) const {
  1753. if (!compositor_delegate_.GetSettings().enable_smooth_scroll)
  1754. return false;
  1755. bool has_precise_scroll_deltas = scroll_state.delta_granularity() ==
  1756. ui::ScrollGranularity::kScrollByPrecisePixel;
  1757. return !has_precise_scroll_deltas;
  1758. }
  1759. bool InputHandler::SnapAtScrollEnd(SnapReason reason) {
  1760. ScrollNode* scroll_node = CurrentlyScrollingNode();
  1761. if (!scroll_node || !scroll_node->snap_container_data.has_value())
  1762. return false;
  1763. SnapContainerData& data = scroll_node->snap_container_data.value();
  1764. gfx::PointF current_position = GetVisualScrollOffset(*scroll_node);
  1765. // You might think that if a scroll never received a scroll update we could
  1766. // just drop the snap. However, if the GSB+GSE arrived while we were mid-snap
  1767. // from a previous gesture, this would leave the scroller at a
  1768. // non-snap-point.
  1769. DCHECK(last_scroll_update_state_ || last_scroll_begin_state_);
  1770. ScrollState& last_scroll_state = last_scroll_update_state_
  1771. ? *last_scroll_update_state_
  1772. : *last_scroll_begin_state_;
  1773. bool imprecise_wheel_scrolling =
  1774. latched_scroll_type_ == ui::ScrollInputType::kWheel &&
  1775. last_scroll_state.delta_granularity() !=
  1776. ui::ScrollGranularity::kScrollByPrecisePixel;
  1777. gfx::Vector2dF last_scroll_delta = last_scroll_state.DeltaOrHint();
  1778. std::unique_ptr<SnapSelectionStrategy> strategy;
  1779. if (imprecise_wheel_scrolling && !last_scroll_delta.IsZero() &&
  1780. reason == SnapReason::kScrollOffsetAnimationFinished) {
  1781. // This was an imprecise wheel scroll so use direction snapping.
  1782. // Note: gesture scroll end is delayed in anticipation of future wheel
  1783. // scrolls so it is fired well after the scroll ends as opposed to precise
  1784. // touch devices where we fire it as soon as the user lifts their finger.
  1785. // TODO(crbug.com/1201678): The directional scroll should probably be
  1786. // triggered at gesture scroll begin to improve responsiveness.
  1787. strategy = SnapSelectionStrategy::CreateForDirection(
  1788. current_position, last_scroll_delta, true);
  1789. } else {
  1790. strategy = SnapSelectionStrategy::CreateForEndPosition(
  1791. current_position, did_scroll_x_for_scroll_gesture_,
  1792. did_scroll_y_for_scroll_gesture_);
  1793. }
  1794. gfx::PointF snap_position;
  1795. TargetSnapAreaElementIds snap_target_ids;
  1796. if (!data.FindSnapPosition(*strategy, &snap_position, &snap_target_ids))
  1797. return false;
  1798. // TODO(bokan): Why only on the viewport?
  1799. if (GetViewport().ShouldScroll(*scroll_node)) {
  1800. compositor_delegate_.WillScrollContent(scroll_node->element_id);
  1801. }
  1802. gfx::Vector2dF delta = snap_position - current_position;
  1803. bool did_animate = false;
  1804. if (scroll_node->scrolls_outer_viewport) {
  1805. gfx::Vector2dF scaled_delta(delta);
  1806. scaled_delta.Scale(compositor_delegate_.PageScaleFactor());
  1807. gfx::Vector2dF consumed_delta =
  1808. GetViewport().ScrollAnimated(scaled_delta, base::TimeDelta());
  1809. did_animate = !consumed_delta.IsZero();
  1810. } else {
  1811. did_animate =
  1812. compositor_delegate_.GetImplDeprecated().ScrollAnimationCreate(
  1813. *scroll_node, delta, base::TimeDelta());
  1814. }
  1815. DCHECK(!IsAnimatingForSnap());
  1816. if (did_animate) {
  1817. // The snap target will be set when the animation is completed.
  1818. scroll_animating_snap_target_ids_ = snap_target_ids;
  1819. } else if (data.SetTargetSnapAreaElementIds(snap_target_ids)) {
  1820. updated_snapped_elements_[scroll_node->element_id] = snap_target_ids;
  1821. SetNeedsCommit();
  1822. }
  1823. return did_animate;
  1824. }
  1825. bool InputHandler::IsAnimatingForSnap() const {
  1826. return scroll_animating_snap_target_ids_ != TargetSnapAreaElementIds();
  1827. }
  1828. gfx::PointF InputHandler::GetVisualScrollOffset(
  1829. const ScrollNode& scroll_node) const {
  1830. if (scroll_node.scrolls_outer_viewport)
  1831. return GetViewport().TotalScrollOffset();
  1832. return GetScrollTree().current_scroll_offset(scroll_node.element_id);
  1833. }
  1834. void InputHandler::ClearCurrentlyScrollingNode() {
  1835. TRACE_EVENT0("cc", "InputHandler::ClearCurrentlyScrollingNode");
  1836. ActiveTree().ClearCurrentlyScrollingNode();
  1837. accumulated_root_overscroll_ = gfx::Vector2dF();
  1838. did_scroll_x_for_scroll_gesture_ = false;
  1839. did_scroll_y_for_scroll_gesture_ = false;
  1840. delta_consumed_for_scroll_gesture_ = false;
  1841. scroll_animating_snap_target_ids_ = TargetSnapAreaElementIds();
  1842. latched_scroll_type_.reset();
  1843. last_scroll_update_state_.reset();
  1844. last_scroll_begin_state_.reset();
  1845. compositor_delegate_.DidEndScroll();
  1846. }
  1847. bool InputHandler::ScrollAnimationUpdateTarget(
  1848. const ScrollNode& scroll_node,
  1849. const gfx::Vector2dF& scroll_delta,
  1850. base::TimeDelta delayed_by) {
  1851. // TODO(bokan): Remove |scroll_node| as a parameter and just use the value
  1852. // coming from |mutator_host|.
  1853. DCHECK_EQ(scroll_node.element_id, compositor_delegate_.GetImplDeprecated()
  1854. .mutator_host()
  1855. ->ImplOnlyScrollAnimatingElement());
  1856. float scale_factor = compositor_delegate_.PageScaleFactor();
  1857. gfx::Vector2dF adjusted_delta =
  1858. gfx::ScaleVector2d(scroll_delta, 1.f / scale_factor);
  1859. adjusted_delta = UserScrollableDelta(scroll_node, adjusted_delta);
  1860. bool animation_updated =
  1861. compositor_delegate_.GetImplDeprecated()
  1862. .mutator_host()
  1863. ->ImplOnlyScrollAnimationUpdateTarget(
  1864. adjusted_delta, GetScrollTree().MaxScrollOffset(scroll_node.id),
  1865. compositor_delegate_.GetImplDeprecated()
  1866. .CurrentBeginFrameArgs()
  1867. .frame_time,
  1868. delayed_by);
  1869. if (animation_updated) {
  1870. compositor_delegate_.DidUpdateScrollAnimationCurve();
  1871. // The animation is no longer targeting a snap position. By clearing the
  1872. // target, this will ensure that we attempt to resnap at the end of this
  1873. // animation.
  1874. scroll_animating_snap_target_ids_ = TargetSnapAreaElementIds();
  1875. }
  1876. return animation_updated;
  1877. }
  1878. void InputHandler::UpdateScrollSourceInfo(const ScrollState& scroll_state,
  1879. ui::ScrollInputType type) {
  1880. if (type == ui::ScrollInputType::kWheel &&
  1881. scroll_state.delta_granularity() ==
  1882. ui::ScrollGranularity::kScrollByPrecisePixel) {
  1883. has_scrolled_by_precisiontouchpad_ = true;
  1884. } else if (type == ui::ScrollInputType::kWheel) {
  1885. has_scrolled_by_wheel_ = true;
  1886. } else if (type == ui::ScrollInputType::kTouchscreen) {
  1887. has_scrolled_by_touch_ = true;
  1888. } else if (type == ui::ScrollInputType::kScrollbar) {
  1889. has_scrolled_by_scrollbar_ = true;
  1890. }
  1891. }
  1892. // Return true if scrollable node for 'ancestor' is the same as 'child' or an
  1893. // ancestor along the scroll tree.
  1894. bool InputHandler::IsScrolledBy(LayerImpl* child, ScrollNode* ancestor) {
  1895. DCHECK(ancestor && ancestor->scrollable);
  1896. if (!child)
  1897. return false;
  1898. DCHECK_EQ(child->layer_tree_impl(), &ActiveTree());
  1899. ScrollTree& scroll_tree = GetScrollTree();
  1900. for (ScrollNode* scroll_node = scroll_tree.Node(child->scroll_tree_index());
  1901. scroll_node; scroll_node = scroll_tree.parent(scroll_node)) {
  1902. if (scroll_node->id == ancestor->id)
  1903. return true;
  1904. }
  1905. return false;
  1906. }
  1907. gfx::Vector2dF InputHandler::UserScrollableDelta(
  1908. const ScrollNode& node,
  1909. const gfx::Vector2dF& delta) const {
  1910. gfx::Vector2dF adjusted_delta = delta;
  1911. if (!node.user_scrollable_horizontal)
  1912. adjusted_delta.set_x(0);
  1913. if (!node.user_scrollable_vertical)
  1914. adjusted_delta.set_y(0);
  1915. return adjusted_delta;
  1916. }
  1917. bool InputHandler::ScrollbarScrollIsActive() {
  1918. return scrollbar_controller_->ScrollbarScrollIsActive();
  1919. }
  1920. void InputHandler::SetDeferBeginMainFrame(bool defer_begin_main_frame) const {
  1921. compositor_delegate_.SetDeferBeginMainFrame(defer_begin_main_frame);
  1922. }
  1923. } // namespace cc