File: SmartClip.cpp

package info (click to toggle)
chromium-browser 41.0.2272.118-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-kfreebsd
  • size: 2,189,132 kB
  • sloc: cpp: 9,691,462; ansic: 3,341,451; python: 712,689; asm: 518,779; xml: 208,926; java: 169,820; sh: 119,353; perl: 68,907; makefile: 28,311; yacc: 13,305; objc: 11,385; tcl: 3,186; cs: 2,225; sql: 2,217; lex: 2,215; lisp: 1,349; pascal: 1,256; awk: 407; ruby: 155; sed: 53; php: 14; exp: 11
file content (277 lines) | stat: -rw-r--r-- 9,814 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
/*
 * Copyright (C) 2013 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "core/frame/SmartClip.h"

#include "core/dom/ContainerNode.h"
#include "core/dom/Document.h"
#include "core/dom/NodeTraversal.h"
#include "core/frame/LocalDOMWindow.h"
#include "core/frame/FrameView.h"
#include "core/html/HTMLFrameOwnerElement.h"
#include "core/page/Page.h"
#include "core/rendering/RenderObject.h"
#include "wtf/text/StringBuilder.h"

namespace blink {

static IntRect applyScaleWithoutCollapsingToZero(const IntRect& rect, float scale)
{
    IntRect result = rect;
    result.scale(scale);
    if (rect.width() > 0 && !result.width())
        result.setWidth(1);
    if (rect.height() > 0 && !result.height())
        result.setHeight(1);
    return result;
}

static Node* nodeInsideFrame(Node* node)
{
    if (node->isFrameOwnerElement())
        return toHTMLFrameOwnerElement(node)->contentDocument();
    return nullptr;
}

IntRect SmartClipData::rect() const
{
    return m_rect;
}

const String& SmartClipData::clipData() const
{
    return m_string;
}

SmartClip::SmartClip(PassRefPtrWillBeRawPtr<LocalFrame> frame)
    : m_frame(frame)
{
}

SmartClipData SmartClip::dataForRect(const IntRect& cropRect)
{
    IntRect resizedCropRect = applyScaleWithoutCollapsingToZero(cropRect, 1 / pageScaleFactor());

    Node* bestNode = findBestOverlappingNode(m_frame->document(), resizedCropRect);
    if (!bestNode)
        return SmartClipData();

    if (Node* nodeFromFrame = nodeInsideFrame(bestNode)) {
        // FIXME: This code only hit-tests a single iframe. It seems like we ought support nested frames.
        if (Node* bestNodeInFrame = findBestOverlappingNode(nodeFromFrame, resizedCropRect))
            bestNode = bestNodeInFrame;
    }

    WillBeHeapVector<RawPtrWillBeMember<Node>> hitNodes;
    collectOverlappingChildNodes(bestNode, resizedCropRect, hitNodes);

    if (hitNodes.isEmpty() || hitNodes.size() == bestNode->countChildren()) {
        hitNodes.clear();
        hitNodes.append(bestNode);
    }

    // Unite won't work with the empty rect, so we initialize to the first rect.
    IntRect unitedRects = hitNodes[0]->pixelSnappedBoundingBox();
    StringBuilder collectedText;
    for (size_t i = 0; i < hitNodes.size(); ++i) {
        collectedText.append(extractTextFromNode(hitNodes[i]));
        unitedRects.unite(hitNodes[i]->pixelSnappedBoundingBox());
    }

    return SmartClipData(bestNode, convertRectToWindow(unitedRects), collectedText.toString());
}

float SmartClip::pageScaleFactor()
{
    return m_frame->page()->pageScaleFactor();
}

// This function is a bit of a mystery. If you understand what it does, please
// consider adding a more descriptive name.
Node* SmartClip::minNodeContainsNodes(Node* minNode, Node* newNode)
{
    if (!newNode)
        return minNode;
    if (!minNode)
        return newNode;

    IntRect minNodeRect = minNode->pixelSnappedBoundingBox();
    IntRect newNodeRect = newNode->pixelSnappedBoundingBox();

    Node* parentMinNode = minNode->parentNode();
    Node* parentNewNode = newNode->parentNode();

    if (minNodeRect.contains(newNodeRect)) {
        if (parentMinNode && parentNewNode && parentNewNode->parentNode() == parentMinNode)
            return parentMinNode;
        return minNode;
    }

    if (newNodeRect.contains(minNodeRect)) {
        if (parentMinNode && parentNewNode && parentMinNode->parentNode() == parentNewNode)
            return parentNewNode;
        return newNode;
    }

    // This loop appears to find the nearest ancestor of minNode (in DOM order)
    // that contains the newNodeRect. It's very unclear to me why that's an
    // interesting node to find. Presumably this loop will often just return
    // the documentElement.
    Node* node = minNode;
    while (node) {
        if (node->renderer()) {
            IntRect nodeRect = node->pixelSnappedBoundingBox();
            if (nodeRect.contains(newNodeRect)) {
                return node;
            }
        }
        node = node->parentNode();
    }

    return nullptr;
}

Node* SmartClip::findBestOverlappingNode(Node* rootNode, const IntRect& cropRect)
{
    if (!rootNode)
        return nullptr;

    IntRect resizedCropRect = rootNode->document().view()->windowToContents(cropRect);

    Node* node = rootNode;
    Node* minNode = nullptr;

    while (node) {
        IntRect nodeRect = node->pixelSnappedBoundingBox();

        if (node->isElementNode() && equalIgnoringCase(toElement(node)->fastGetAttribute(HTMLNames::aria_hiddenAttr), "true")) {
            node = NodeTraversal::nextSkippingChildren(*node, rootNode);
            continue;
        }

        RenderObject* renderer = node->renderer();
        if (renderer && !nodeRect.isEmpty()) {
            if (renderer->isText()
                || renderer->isRenderImage()
                || node->isFrameOwnerElement()
                || (renderer->style()->hasBackgroundImage() && !shouldSkipBackgroundImage(node))) {
                if (resizedCropRect.intersects(nodeRect)) {
                    minNode = minNodeContainsNodes(minNode, node);
                } else {
                    node = NodeTraversal::nextSkippingChildren(*node, rootNode);
                    continue;
                }
            }
        }
        node = NodeTraversal::next(*node, rootNode);
    }

    return minNode;
}

// This function appears to heuristically guess whether to include a background
// image in the smart clip. It seems to want to include sprites created from
// CSS background images but to skip actual backgrounds.
bool SmartClip::shouldSkipBackgroundImage(Node* node)
{
    ASSERT(node);
    // Apparently we're only interested in background images on spans and divs.
    if (!isHTMLSpanElement(*node) && !isHTMLDivElement(*node))
        return true;

    // This check actually makes a bit of sense. If you're going to sprite an
    // image out of a CSS background, you're probably going to specify a height
    // or a width. On the other hand, if we've got a legit background image,
    // it's very likely the height or the width will be set to auto.
    RenderObject* renderer = node->renderer();
    if (renderer && (renderer->style()->logicalHeight().isAuto() || renderer->style()->logicalWidth().isAuto()))
        return true;

    return false;
}

void SmartClip::collectOverlappingChildNodes(Node* parentNode, const IntRect& cropRect, WillBeHeapVector<RawPtrWillBeMember<Node>>& hitNodes)
{
    if (!parentNode)
        return;
    IntRect resizedCropRect = parentNode->document().view()->windowToContents(cropRect);
    for (Node* child = parentNode->firstChild(); child; child = child->nextSibling()) {
        IntRect childRect = child->pixelSnappedBoundingBox();
        if (resizedCropRect.intersects(childRect))
            hitNodes.append(child);
    }
}

IntRect SmartClip::convertRectToWindow(const IntRect& nodeRect)
{
    IntRect result = m_frame->document()->view()->contentsToWindow(nodeRect);
    result.scale(pageScaleFactor());
    return result;
}

String SmartClip::extractTextFromNode(Node* node)
{
    // Science has proven that no text nodes are ever positioned at y == -99999.
    int prevYPos = -99999;

    StringBuilder result;
    for (Node& currentNode : NodeTraversal::inclusiveDescendantsOf(*node)) {
        RenderStyle* style = currentNode.computedStyle();
        if (style && style->userSelect() == SELECT_NONE)
            continue;

        if (Node* nodeFromFrame = nodeInsideFrame(&currentNode))
            result.append(extractTextFromNode(nodeFromFrame));

        IntRect nodeRect = currentNode.pixelSnappedBoundingBox();
        if (currentNode.renderer() && !nodeRect.isEmpty()) {
            if (currentNode.isTextNode()) {
                String nodeValue = currentNode.nodeValue();

                // It's unclear why we blacklist solitary "\n" node values.
                // Maybe we're trying to ignore <br> tags somehow?
                if (nodeValue == "\n")
                    nodeValue = "";

                if (nodeRect.y() != prevYPos) {
                    prevYPos = nodeRect.y();
                    result.append('\n');
                }

                result.append(nodeValue);
            }
        }
    }

    return result.toString();
}

} // namespace blink