Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / page / TouchDisambiguation.cpp
1 /*
2  * Copyright (C) 2012 Google Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  *     * Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *     * Redistributions in binary form must reproduce the above
11  * copyright notice, this list of conditions and the following disclaimer
12  * in the documentation and/or other materials provided with the
13  * distribution.
14  *     * Neither the name of Google Inc. nor the names of its
15  * contributors may be used to endorse or promote products derived from
16  * this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #include "config.h"
32
33 #include "core/page/TouchDisambiguation.h"
34
35 #include <algorithm>
36 #include <cmath>
37 #include "HTMLNames.h"
38 #include "core/dom/Document.h"
39 #include "core/dom/Element.h"
40 #include "core/dom/NodeTraversal.h"
41 #include "core/page/EventHandler.h"
42 #include "core/frame/Frame.h"
43 #include "core/frame/FrameView.h"
44 #include "core/rendering/HitTestResult.h"
45 #include "core/rendering/RenderBlock.h"
46
47 using namespace std;
48
49 namespace WebCore {
50
51 static IntRect boundingBoxForEventNodes(Node* eventNode)
52 {
53     if (!eventNode->document().view())
54         return IntRect();
55
56     IntRect result;
57     Node* node = eventNode;
58     while (node) {
59         // Skip the whole sub-tree if the node doesn't propagate events.
60         if (node != eventNode && node->willRespondToMouseClickEvents()) {
61             node = NodeTraversal::nextSkippingChildren(*node, eventNode);
62             continue;
63         }
64         result.unite(node->pixelSnappedBoundingBox());
65         node = NodeTraversal::next(*node, eventNode);
66     }
67     return eventNode->document().view()->contentsToWindow(result);
68 }
69
70 static float scoreTouchTarget(IntPoint touchPoint, int padding, IntRect boundingBox)
71 {
72     if (boundingBox.isEmpty())
73         return 0;
74
75     float reciprocalPadding = 1.f / padding;
76     float score = 1;
77
78     IntSize distance = boundingBox.differenceToPoint(touchPoint);
79     score *= max((padding - abs(distance.width())) * reciprocalPadding, 0.f);
80     score *= max((padding - abs(distance.height())) * reciprocalPadding, 0.f);
81
82     return score;
83 }
84
85 struct TouchTargetData {
86     IntRect windowBoundingBox;
87     float score;
88 };
89
90 void findGoodTouchTargets(const IntRect& touchBox, Frame* mainFrame, Vector<IntRect>& goodTargets, Vector<Node*>& highlightNodes)
91 {
92     goodTargets.clear();
93
94     int touchPointPadding = ceil(max(touchBox.width(), touchBox.height()) * 0.5);
95
96     IntPoint touchPoint = touchBox.center();
97     IntPoint contentsPoint = mainFrame->view()->windowToContents(touchPoint);
98
99     HitTestResult result = mainFrame->eventHandler().hitTestResultAtPoint(contentsPoint, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent, IntSize(touchPointPadding, touchPointPadding));
100     const ListHashSet<RefPtr<Node> >& hitResults = result.rectBasedTestResult();
101
102     // Blacklist nodes that are container of disambiguated nodes.
103     // It is not uncommon to have a clickable <div> that contains other clickable objects.
104     // This heuristic avoids excessive disambiguation in that case.
105     HashSet<Node*> blackList;
106     for (ListHashSet<RefPtr<Node> >::const_iterator it = hitResults.begin(); it != hitResults.end(); ++it) {
107         // Ignore any Nodes that can't be clicked on.
108         RenderObject* renderer = it->get()->renderer();
109         if (!renderer || !it->get()->willRespondToMouseClickEvents())
110             continue;
111
112         // Blacklist all of the Node's containers.
113         for (RenderBlock* container = renderer->containingBlock(); container; container = container->containingBlock()) {
114             Node* containerNode = container->node();
115             if (!containerNode)
116                 continue;
117             if (!blackList.add(containerNode).isNewEntry)
118                 break;
119         }
120     }
121
122     HashMap<Node*, TouchTargetData> touchTargets;
123     float bestScore = 0;
124     for (ListHashSet<RefPtr<Node> >::const_iterator it = hitResults.begin(); it != hitResults.end(); ++it) {
125         for (Node* node = it->get(); node; node = node->parentNode()) {
126             if (blackList.contains(node))
127                 continue;
128             if (node->isDocumentNode() || node->hasTagName(HTMLNames::htmlTag) || node->hasTagName(HTMLNames::bodyTag))
129                 break;
130             if (node->willRespondToMouseClickEvents()) {
131                 TouchTargetData& targetData = touchTargets.add(node, TouchTargetData()).storedValue->value;
132                 targetData.windowBoundingBox = boundingBoxForEventNodes(node);
133                 targetData.score = scoreTouchTarget(touchPoint, touchPointPadding, targetData.windowBoundingBox);
134                 bestScore = max(bestScore, targetData.score);
135                 break;
136             }
137         }
138     }
139
140     for (HashMap<Node*, TouchTargetData>::iterator it = touchTargets.begin(); it != touchTargets.end(); ++it) {
141         // Currently the scoring function uses the overlap area with the fat point as the score.
142         // We ignore the candidates that has less than 1/2 overlap (we consider not really ambiguous enough) than the best candidate to avoid excessive popups.
143         if (it->value.score < bestScore * 0.5)
144             continue;
145         goodTargets.append(it->value.windowBoundingBox);
146         highlightNodes.append(it->key);
147     }
148 }
149
150 } // namespace WebCore