Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / web / LinkHighlight.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
6  * are met:
7  *
8  * 1.  Redistributions of source code must retain the above copyright
9  *     notice, this list of conditions and the following disclaimer.
10  * 2.  Redistributions in binary form must reproduce the above copyright
11  *     notice, this list of conditions and the following disclaimer in the
12  *     documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
15  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
16  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
17  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
18  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
19  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
20  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
21  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27
28 #include "web/LinkHighlight.h"
29
30 #include "SkMatrix44.h"
31 #include "core/dom/Node.h"
32 #include "core/frame/FrameView.h"
33 #include "core/frame/LocalFrame.h"
34 #include "core/rendering/RenderLayer.h"
35 #include "core/rendering/RenderLayerModelObject.h"
36 #include "core/rendering/RenderObject.h"
37 #include "core/rendering/RenderPart.h"
38 #include "core/rendering/RenderView.h"
39 #include "core/rendering/compositing/CompositedLayerMapping.h"
40 #include "core/rendering/style/ShadowData.h"
41 #include "platform/graphics/Color.h"
42 #include "public/platform/Platform.h"
43 #include "public/platform/WebAnimationCurve.h"
44 #include "public/platform/WebCompositorSupport.h"
45 #include "public/platform/WebFloatAnimationCurve.h"
46 #include "public/platform/WebFloatPoint.h"
47 #include "public/platform/WebRect.h"
48 #include "public/platform/WebSize.h"
49 #include "public/web/WebKit.h"
50 #include "web/WebLocalFrameImpl.h"
51 #include "web/WebSettingsImpl.h"
52 #include "web/WebViewImpl.h"
53 #include "wtf/CurrentTime.h"
54
55 namespace blink {
56
57 class WebViewImpl;
58
59 PassOwnPtr<LinkHighlight> LinkHighlight::create(Node* node, WebViewImpl* owningWebViewImpl)
60 {
61     return adoptPtr(new LinkHighlight(node, owningWebViewImpl));
62 }
63
64 LinkHighlight::LinkHighlight(Node* node, WebViewImpl* owningWebViewImpl)
65     : m_node(node)
66     , m_owningWebViewImpl(owningWebViewImpl)
67     , m_currentGraphicsLayer(0)
68     , m_geometryNeedsUpdate(false)
69     , m_isAnimating(false)
70     , m_startTime(monotonicallyIncreasingTime())
71 {
72     ASSERT(m_node);
73     ASSERT(owningWebViewImpl);
74     WebCompositorSupport* compositorSupport = Platform::current()->compositorSupport();
75     m_contentLayer = adoptPtr(compositorSupport->createContentLayer(this));
76     m_clipLayer = adoptPtr(compositorSupport->createLayer());
77     m_clipLayer->setTransformOrigin(WebFloatPoint3D());
78     m_clipLayer->addChild(m_contentLayer->layer());
79     m_contentLayer->layer()->setAnimationDelegate(this);
80     m_contentLayer->layer()->setDrawsContent(true);
81     m_contentLayer->layer()->setOpacity(1);
82     m_geometryNeedsUpdate = true;
83     updateGeometry();
84 }
85
86 LinkHighlight::~LinkHighlight()
87 {
88     clearGraphicsLayerLinkHighlightPointer();
89     releaseResources();
90 }
91
92 WebContentLayer* LinkHighlight::contentLayer()
93 {
94     return m_contentLayer.get();
95 }
96
97 WebLayer* LinkHighlight::clipLayer()
98 {
99     return m_clipLayer.get();
100 }
101
102 void LinkHighlight::releaseResources()
103 {
104     m_node.clear();
105 }
106
107 RenderLayer* LinkHighlight::computeEnclosingCompositingLayer()
108 {
109     if (!m_node || !m_node->renderer())
110         return 0;
111
112     // Find the nearest enclosing composited layer and attach to it. We may need to cross frame boundaries
113     // to find a suitable layer.
114     RenderObject* renderer = m_node->renderer();
115     RenderLayer* renderLayer;
116     do {
117         renderLayer = renderer->enclosingLayer()->enclosingLayerForPaintInvalidation();
118         if (!renderLayer) {
119             renderer = renderer->frame()->ownerRenderer();
120             if (!renderer)
121                 return 0;
122         }
123     } while (!renderLayer);
124
125     ASSERT(renderLayer->compositingState() != NotComposited);
126
127     GraphicsLayer* newGraphicsLayer = renderLayer->graphicsLayerBacking();
128     if (!newGraphicsLayer->drawsContent()) {
129         newGraphicsLayer = renderLayer->graphicsLayerBackingForScrolling();
130     }
131
132     m_clipLayer->setTransform(SkMatrix44(SkMatrix44::kIdentity_Constructor));
133
134     if (m_currentGraphicsLayer != newGraphicsLayer) {
135         if (m_currentGraphicsLayer)
136             clearGraphicsLayerLinkHighlightPointer();
137
138         m_currentGraphicsLayer = newGraphicsLayer;
139         m_currentGraphicsLayer->addLinkHighlight(this);
140     }
141
142     return renderLayer;
143 }
144
145 static void convertTargetSpaceQuadToCompositedLayer(const FloatQuad& targetSpaceQuad, RenderObject* targetRenderer, RenderObject* compositedRenderer, FloatQuad& compositedSpaceQuad)
146 {
147     ASSERT(targetRenderer);
148     ASSERT(compositedRenderer);
149
150     for (unsigned i = 0; i < 4; ++i) {
151         IntPoint point;
152         switch (i) {
153         case 0: point = roundedIntPoint(targetSpaceQuad.p1()); break;
154         case 1: point = roundedIntPoint(targetSpaceQuad.p2()); break;
155         case 2: point = roundedIntPoint(targetSpaceQuad.p3()); break;
156         case 3: point = roundedIntPoint(targetSpaceQuad.p4()); break;
157         }
158
159         point = targetRenderer->frame()->view()->contentsToWindow(point);
160         point = compositedRenderer->frame()->view()->windowToContents(point);
161         FloatPoint floatPoint = compositedRenderer->absoluteToLocal(point, UseTransforms);
162
163         switch (i) {
164         case 0: compositedSpaceQuad.setP1(floatPoint); break;
165         case 1: compositedSpaceQuad.setP2(floatPoint); break;
166         case 2: compositedSpaceQuad.setP3(floatPoint); break;
167         case 3: compositedSpaceQuad.setP4(floatPoint); break;
168         }
169     }
170 }
171
172 static void addQuadToPath(const FloatQuad& quad, Path& path)
173 {
174     // FIXME: Make this create rounded quad-paths, just like the axis-aligned case.
175     path.moveTo(quad.p1());
176     path.addLineTo(quad.p2());
177     path.addLineTo(quad.p3());
178     path.addLineTo(quad.p4());
179     path.closeSubpath();
180 }
181
182 void LinkHighlight::computeQuads(Node* node, Vector<FloatQuad>& outQuads) const
183 {
184     if (!node || !node->renderer())
185         return;
186
187     RenderObject* renderer = node->renderer();
188
189     // For inline elements, absoluteQuads will return a line box based on the line-height
190     // and font metrics, which is technically incorrect as replaced elements like images
191     // should use their intristic height and expand the linebox  as needed. To get an
192     // appropriately sized highlight we descend into the children and have them add their
193     // boxes.
194     if (renderer->isRenderInline()) {
195         for (Node* child = node->firstChild(); child; child = child->nextSibling())
196             computeQuads(child, outQuads);
197     } else {
198         renderer->absoluteQuads(outQuads);
199     }
200
201 }
202
203 bool LinkHighlight::computeHighlightLayerPathAndPosition(RenderLayer* compositingLayer)
204 {
205     if (!m_node || !m_node->renderer() || !m_currentGraphicsLayer)
206         return false;
207
208     ASSERT(compositingLayer);
209
210     // Get quads for node in absolute coordinates.
211     Vector<FloatQuad> quads;
212     computeQuads(m_node.get(), quads);
213     ASSERT(quads.size());
214
215     // Adjust for offset between target graphics layer and the node's renderer.
216     FloatPoint positionAdjust = IntPoint(m_currentGraphicsLayer->offsetFromRenderer());
217
218     Path newPath;
219     for (size_t quadIndex = 0; quadIndex < quads.size(); ++quadIndex) {
220         FloatQuad absoluteQuad = quads[quadIndex];
221         absoluteQuad.move(-positionAdjust.x(), -positionAdjust.y());
222
223         // Transform node quads in target absolute coords to local coordinates in the compositor layer.
224         FloatQuad transformedQuad;
225         convertTargetSpaceQuadToCompositedLayer(absoluteQuad, m_node->renderer(), compositingLayer->renderer(), transformedQuad);
226
227         // FIXME: for now, we'll only use rounded paths if we have a single node quad. The reason for this is that
228         // we may sometimes get a chain of adjacent boxes (e.g. for text nodes) which end up looking like sausage
229         // links: these should ideally be merged into a single rect before creating the path, but that's
230         // another CL.
231         if (quads.size() == 1 && transformedQuad.isRectilinear()
232             && !m_owningWebViewImpl->settingsImpl()->mockGestureTapHighlightsEnabled()) {
233             FloatSize rectRoundingRadii(3, 3);
234             newPath.addRoundedRect(transformedQuad.boundingBox(), rectRoundingRadii);
235         } else
236             addQuadToPath(transformedQuad, newPath);
237     }
238
239     FloatRect boundingRect = newPath.boundingRect();
240     newPath.translate(-toFloatSize(boundingRect.location()));
241
242     bool pathHasChanged = !(newPath == m_path);
243     if (pathHasChanged) {
244         m_path = newPath;
245         m_contentLayer->layer()->setBounds(enclosingIntRect(boundingRect).size());
246     }
247
248     m_contentLayer->layer()->setPosition(boundingRect.location());
249
250     return pathHasChanged;
251 }
252
253 void LinkHighlight::paintContents(WebCanvas* canvas, const WebRect& webClipRect, bool, WebFloatRect&,
254     WebContentLayerClient::GraphicsContextStatus contextStatus)
255 {
256     if (!m_node || !m_node->renderer())
257         return;
258
259     GraphicsContext gc(canvas,
260         contextStatus == WebContentLayerClient::GraphicsContextEnabled ? GraphicsContext::NothingDisabled : GraphicsContext::FullyDisabled);
261     IntRect clipRect(IntPoint(webClipRect.x, webClipRect.y), IntSize(webClipRect.width, webClipRect.height));
262     gc.clip(clipRect);
263     gc.setFillColor(m_node->renderer()->style()->tapHighlightColor());
264     gc.fillPath(m_path);
265 }
266
267 void LinkHighlight::startHighlightAnimationIfNeeded()
268 {
269     if (m_isAnimating)
270         return;
271
272     m_isAnimating = true;
273     const float startOpacity = 1;
274     // FIXME: Should duration be configurable?
275     const float fadeDuration = 0.1f;
276     const float minPreFadeDuration = 0.1f;
277
278     m_contentLayer->layer()->setOpacity(startOpacity);
279
280     WebCompositorSupport* compositorSupport = Platform::current()->compositorSupport();
281
282     OwnPtr<WebFloatAnimationCurve> curve = adoptPtr(compositorSupport->createFloatAnimationCurve());
283
284     curve->add(WebFloatKeyframe(0, startOpacity));
285     // Make sure we have displayed for at least minPreFadeDuration before starting to fade out.
286     float extraDurationRequired = std::max(0.f, minPreFadeDuration - static_cast<float>(monotonicallyIncreasingTime() - m_startTime));
287     if (extraDurationRequired)
288         curve->add(WebFloatKeyframe(extraDurationRequired, startOpacity));
289     // For layout tests we don't fade out.
290     curve->add(WebFloatKeyframe(fadeDuration + extraDurationRequired, blink::layoutTestMode() ? startOpacity : 0));
291
292     OwnPtr<WebAnimation> animation = adoptPtr(compositorSupport->createAnimation(*curve, WebAnimation::TargetPropertyOpacity));
293
294     m_contentLayer->layer()->setDrawsContent(true);
295     m_contentLayer->layer()->addAnimation(animation.leakPtr());
296
297     invalidate();
298     m_owningWebViewImpl->scheduleAnimation();
299 }
300
301 void LinkHighlight::clearGraphicsLayerLinkHighlightPointer()
302 {
303     if (m_currentGraphicsLayer) {
304         m_currentGraphicsLayer->removeLinkHighlight(this);
305         m_currentGraphicsLayer = 0;
306     }
307 }
308
309 void LinkHighlight::notifyAnimationStarted(double, blink::WebAnimation::TargetProperty)
310 {
311 }
312
313 void LinkHighlight::notifyAnimationFinished(double, blink::WebAnimation::TargetProperty)
314 {
315     // Since WebViewImpl may hang on to us for a while, make sure we
316     // release resources as soon as possible.
317     clearGraphicsLayerLinkHighlightPointer();
318     releaseResources();
319 }
320
321 void LinkHighlight::updateGeometry()
322 {
323     // To avoid unnecessary updates (e.g. other entities have requested animations from our WebViewImpl),
324     // only proceed if we actually requested an update.
325     if (!m_geometryNeedsUpdate)
326         return;
327
328     m_geometryNeedsUpdate = false;
329
330     RenderLayer* compositingLayer = computeEnclosingCompositingLayer();
331     if (compositingLayer && computeHighlightLayerPathAndPosition(compositingLayer)) {
332         // We only need to invalidate the layer if the highlight size has changed, otherwise
333         // we can just re-position the layer without needing to repaint.
334         m_contentLayer->layer()->invalidate();
335
336         if (m_currentGraphicsLayer)
337             m_currentGraphicsLayer->addRepaintRect(FloatRect(layer()->position().x, layer()->position().y, layer()->bounds().width, layer()->bounds().height));
338     } else if (!m_node || !m_node->renderer()) {
339         clearGraphicsLayerLinkHighlightPointer();
340         releaseResources();
341     }
342 }
343
344 void LinkHighlight::clearCurrentGraphicsLayer()
345 {
346     m_currentGraphicsLayer = 0;
347     m_geometryNeedsUpdate = true;
348 }
349
350 void LinkHighlight::invalidate()
351 {
352     // Make sure we update geometry on the next callback from WebViewImpl::layout().
353     m_geometryNeedsUpdate = true;
354 }
355
356 WebLayer* LinkHighlight::layer()
357 {
358     return clipLayer();
359 }
360
361 } // namespace blink