File: ScrollAnchor.cpp

package info (click to toggle)
chromium-browser 57.0.2987.98-1~deb8u1
  • links: PTS, VCS
  • area: main
  • in suites: jessie
  • size: 2,637,852 kB
  • ctags: 2,544,394
  • sloc: cpp: 12,815,961; ansic: 3,676,222; python: 1,147,112; asm: 526,608; java: 523,212; xml: 286,794; perl: 92,654; sh: 86,408; objc: 73,271; makefile: 27,698; cs: 18,487; yacc: 13,031; tcl: 12,957; pascal: 4,875; ml: 4,716; lex: 3,904; sql: 3,862; ruby: 1,982; lisp: 1,508; php: 1,368; exp: 404; awk: 325; csh: 117; jsp: 39; sed: 37
file content (339 lines) | stat: -rw-r--r-- 11,042 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "core/layout/ScrollAnchor.h"

#include "core/frame/FrameView.h"
#include "core/frame/UseCounter.h"
#include "core/layout/LayoutBlockFlow.h"
#include "core/layout/api/LayoutBoxItem.h"
#include "core/layout/line/InlineTextBox.h"
#include "core/paint/PaintLayer.h"
#include "core/paint/PaintLayerScrollableArea.h"
#include "platform/Histogram.h"

namespace blink {

using Corner = ScrollAnchor::Corner;

ScrollAnchor::ScrollAnchor()
    : m_anchorObject(nullptr),
      m_corner(Corner::TopLeft),
      m_scrollAnchorDisablingStyleChanged(false),
      m_queued(false) {}

ScrollAnchor::ScrollAnchor(ScrollableArea* scroller) : ScrollAnchor() {
  setScroller(scroller);
}

ScrollAnchor::~ScrollAnchor() {}

void ScrollAnchor::setScroller(ScrollableArea* scroller) {
  DCHECK(m_scroller != scroller);
  DCHECK(scroller);
  DCHECK(scroller->isRootFrameViewport() || scroller->isFrameView() ||
         scroller->isPaintLayerScrollableArea());
  m_scroller = scroller;
  clearSelf();
}

// TODO(pilgrim): Replace all instances of scrollerLayoutBox with
// scrollerLayoutBoxItem, https://crbug.com/499321
static LayoutBox* scrollerLayoutBox(const ScrollableArea* scroller) {
  LayoutBox* box = scroller->layoutBox();
  DCHECK(box);
  return box;
}

static LayoutBoxItem scrollerLayoutBoxItem(const ScrollableArea* scroller) {
  return LayoutBoxItem(scrollerLayoutBox(scroller));
}

static Corner cornerToAnchor(const ScrollableArea* scroller) {
  const ComputedStyle* style = scrollerLayoutBox(scroller)->style();
  if (style->isFlippedBlocksWritingMode() || !style->isLeftToRightDirection())
    return Corner::TopRight;
  return Corner::TopLeft;
}

static LayoutPoint cornerPointOfRect(LayoutRect rect, Corner whichCorner) {
  switch (whichCorner) {
    case Corner::TopLeft:
      return rect.minXMinYCorner();
    case Corner::TopRight:
      return rect.maxXMinYCorner();
  }
  ASSERT_NOT_REACHED();
  return LayoutPoint();
}

// Bounds of the LayoutObject relative to the scroller's visible content rect.
static LayoutRect relativeBounds(const LayoutObject* layoutObject,
                                 const ScrollableArea* scroller) {
  LayoutRect localBounds;
  if (layoutObject->isBox()) {
    localBounds = toLayoutBox(layoutObject)->borderBoxRect();
    if (!layoutObject->hasOverflowClip()) {
      // borderBoxRect doesn't include overflow content and floats.
      LayoutUnit maxHeight =
          std::max(localBounds.height(),
                   toLayoutBox(layoutObject)->layoutOverflowRect().height());
      if (layoutObject->isLayoutBlockFlow() &&
          toLayoutBlockFlow(layoutObject)->containsFloats()) {
        // Note that lowestFloatLogicalBottom doesn't include floating
        // grandchildren.
        maxHeight = std::max(
            maxHeight,
            toLayoutBlockFlow(layoutObject)->lowestFloatLogicalBottom());
      }
      localBounds.setHeight(maxHeight);
    }
  } else if (layoutObject->isText()) {
    // TODO(skobes): Use first and last InlineTextBox only?
    for (InlineTextBox* box = toLayoutText(layoutObject)->firstTextBox(); box;
         box = box->nextTextBox())
      localBounds.unite(box->frameRect());
  } else {
    // Only LayoutBox and LayoutText are supported.
    ASSERT_NOT_REACHED();
  }

  LayoutRect relativeBounds = LayoutRect(
      scroller->localToVisibleContentQuad(FloatRect(localBounds), layoutObject)
          .boundingBox());

  return relativeBounds;
}

static LayoutPoint computeRelativeOffset(const LayoutObject* layoutObject,
                                         const ScrollableArea* scroller,
                                         Corner corner) {
  return cornerPointOfRect(relativeBounds(layoutObject, scroller), corner);
}

static bool candidateMayMoveWithScroller(const LayoutObject* candidate,
                                         const ScrollableArea* scroller) {
  if (const ComputedStyle* style = candidate->style()) {
    if (style->hasViewportConstrainedPosition())
      return false;
  }

  LayoutObject::AncestorSkipInfo skipInfo(scrollerLayoutBox(scroller));
  candidate->container(&skipInfo);
  return !skipInfo.ancestorSkipped();
}

ScrollAnchor::ExamineResult ScrollAnchor::examine(
    const LayoutObject* candidate) const {
  if (candidate->isLayoutInline())
    return ExamineResult(Continue);

  // Anonymous blocks are not in the DOM tree and it may be hard for
  // developers to reason about the anchor node.
  if (candidate->isAnonymous())
    return ExamineResult(Continue);

  if (!candidate->isText() && !candidate->isBox())
    return ExamineResult(Skip);

  if (!candidateMayMoveWithScroller(candidate, m_scroller))
    return ExamineResult(Skip);

  if (candidate->style()->overflowAnchor() == EOverflowAnchor::None)
    return ExamineResult(Skip);

  LayoutRect candidateRect = relativeBounds(candidate, m_scroller);
  LayoutRect visibleRect =
      scrollerLayoutBoxItem(m_scroller).overflowClipRect(LayoutPoint());

  bool occupiesSpace = candidateRect.width() > 0 && candidateRect.height() > 0;
  if (occupiesSpace && visibleRect.intersects(candidateRect)) {
    return ExamineResult(
        visibleRect.contains(candidateRect) ? Return : Constrain,
        cornerToAnchor(m_scroller));
  } else {
    return ExamineResult(Skip);
  }
}

void ScrollAnchor::findAnchor() {
  TRACE_EVENT0("blink", "ScrollAnchor::findAnchor");
  SCOPED_BLINK_UMA_HISTOGRAM_TIMER("Layout.ScrollAnchor.TimeToFindAnchor");

  LayoutObject* stayWithin = scrollerLayoutBox(m_scroller);
  LayoutObject* candidate = stayWithin->nextInPreOrder(stayWithin);
  while (candidate) {
    ExamineResult result = examine(candidate);
    if (result.viable) {
      m_anchorObject = candidate;
      m_corner = result.corner;
    }
    switch (result.status) {
      case Skip:
        candidate = candidate->nextInPreOrderAfterChildren(stayWithin);
        break;
      case Constrain:
        stayWithin = candidate;
      // fall through
      case Continue:
        candidate = candidate->nextInPreOrder(stayWithin);
        break;
      case Return:
        return;
    }
  }
}

bool ScrollAnchor::computeScrollAnchorDisablingStyleChanged() {
  LayoutObject* current = anchorObject();
  if (!current)
    return false;

  LayoutObject* scrollerBox = scrollerLayoutBox(m_scroller);
  while (true) {
    DCHECK(current);
    if (current->scrollAnchorDisablingStyleChanged())
      return true;
    if (current == scrollerBox)
      return false;
    current = current->parent();
  }
}

void ScrollAnchor::notifyBeforeLayout() {
  if (m_queued) {
    m_scrollAnchorDisablingStyleChanged |=
        computeScrollAnchorDisablingStyleChanged();
    return;
  }
  DCHECK(m_scroller);
  ScrollOffset scrollOffset = m_scroller->getScrollOffset();
  float blockDirectionScrollOffset =
      scrollerLayoutBox(m_scroller)->isHorizontalWritingMode()
          ? scrollOffset.height()
          : scrollOffset.width();
  if (blockDirectionScrollOffset == 0) {
    clearSelf();
    return;
  }

  if (!m_anchorObject) {
    findAnchor();
    if (!m_anchorObject)
      return;

    m_anchorObject->setIsScrollAnchorObject();
    m_savedRelativeOffset =
        computeRelativeOffset(m_anchorObject, m_scroller, m_corner);
  }

  m_scrollAnchorDisablingStyleChanged =
      computeScrollAnchorDisablingStyleChanged();

  FrameView* frameView = scrollerLayoutBox(m_scroller)->frameView();
  ScrollableArea* owningScroller =
      m_scroller->isRootFrameViewport()
          ? &toRootFrameViewport(m_scroller)->layoutViewport()
          : m_scroller.get();
  frameView->enqueueScrollAnchoringAdjustment(owningScroller);
  m_queued = true;
}

IntSize ScrollAnchor::computeAdjustment() const {
  // The anchor node can report fractional positions, but it is DIP-snapped when
  // painting (crbug.com/610805), so we must round the offsets to determine the
  // visual delta. If we scroll by the delta in LayoutUnits, the snapping of the
  // anchor node may round differently from the snapping of the scroll position.
  // (For example, anchor moving from 2.4px -> 2.6px is really 2px -> 3px, so we
  // should scroll by 1px instead of 0.2px.) This is true regardless of whether
  // the ScrollableArea actually uses fractional scroll positions.
  IntSize delta = roundedIntSize(computeRelativeOffset(m_anchorObject,
                                                       m_scroller, m_corner)) -
                  roundedIntSize(m_savedRelativeOffset);

  // Only adjust on the block layout axis.
  if (scrollerLayoutBox(m_scroller)->isHorizontalWritingMode())
    delta.setWidth(0);
  else
    delta.setHeight(0);
  return delta;
}

void ScrollAnchor::adjust() {
  if (!m_queued)
    return;
  m_queued = false;
  DCHECK(m_scroller);
  if (!m_anchorObject)
    return;
  IntSize adjustment = computeAdjustment();
  if (adjustment.isZero())
    return;

  if (m_scrollAnchorDisablingStyleChanged) {
    // Note that we only clear if the adjustment would have been non-zero.
    // This minimizes redundant calls to findAnchor.
    // TODO(skobes): add UMA metric for this.
    clearSelf();

    DEFINE_STATIC_LOCAL(EnumerationHistogram, suppressedBySanaclapHistogram,
                        ("Layout.ScrollAnchor.SuppressedBySanaclap", 2));
    suppressedBySanaclapHistogram.count(1);

    return;
  }

  m_scroller->setScrollOffset(
      m_scroller->getScrollOffset() + FloatSize(adjustment), AnchoringScroll);

  // Update UMA metric.
  DEFINE_STATIC_LOCAL(EnumerationHistogram, adjustedOffsetHistogram,
                      ("Layout.ScrollAnchor.AdjustedScrollOffset", 2));
  adjustedOffsetHistogram.count(1);
  UseCounter::count(scrollerLayoutBox(m_scroller)->document(),
                    UseCounter::ScrollAnchored);
}

void ScrollAnchor::clearSelf() {
  LayoutObject* anchorObject = m_anchorObject;
  m_anchorObject = nullptr;

  if (anchorObject)
    anchorObject->maybeClearIsScrollAnchorObject();
}

void ScrollAnchor::clear() {
  LayoutObject* layoutObject =
      m_anchorObject ? m_anchorObject : scrollerLayoutBox(m_scroller);
  PaintLayer* layer = nullptr;
  if (LayoutObject* parent = layoutObject->parent())
    layer = parent->enclosingLayer();

  // Walk up the layer tree to clear any scroll anchors.
  while (layer) {
    if (PaintLayerScrollableArea* scrollableArea = layer->getScrollableArea()) {
      ScrollAnchor* anchor = scrollableArea->scrollAnchor();
      DCHECK(anchor);
      anchor->clearSelf();
    }
    layer = layer->parent();
  }

  if (FrameView* view = layoutObject->frameView()) {
    ScrollAnchor* anchor = view->scrollAnchor();
    DCHECK(anchor);
    anchor->clearSelf();
  }
}

bool ScrollAnchor::refersTo(const LayoutObject* layoutObject) const {
  return m_anchorObject == layoutObject;
}

void ScrollAnchor::notifyRemoved(LayoutObject* layoutObject) {
  if (m_anchorObject == layoutObject)
    clearSelf();
}

}  // namespace blink