Implement mechanism to detect (partially) hidden blocked plugins.
[WebKit-https.git] / Source / WebCore / rendering / RenderEmbeddedObject.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 2000 Simon Hausmann <hausmann@kde.org>
4  *           (C) 2000 Stefan Schimanski (1Stein@gmx.de)
5  * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010 Apple Inc. All rights reserved.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public License
18  * along with this library; see the file COPYING.LIB.  If not, write to
19  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20  * Boston, MA 02110-1301, USA.
21  *
22  */
23
24 #include "config.h"
25 #include "RenderEmbeddedObject.h"
26
27 #include "CSSValueKeywords.h"
28 #include "Chrome.h"
29 #include "ChromeClient.h"
30 #include "Cursor.h"
31 #include "EventHandler.h"
32 #include "Font.h"
33 #include "FontSelector.h"
34 #include "Frame.h"
35 #include "FrameLoaderClient.h"
36 #include "GraphicsContext.h"
37 #include "HTMLEmbedElement.h"
38 #include "HTMLIFrameElement.h"
39 #include "HTMLNames.h"
40 #include "HTMLObjectElement.h"
41 #include "HTMLParamElement.h"
42 #include "HTMLPlugInElement.h"
43 #include "HitTestResult.h"
44 #include "LocalizedStrings.h"
45 #include "MIMETypeRegistry.h"
46 #include "MouseEvent.h"
47 #include "Page.h"
48 #include "PaintInfo.h"
49 #include "Path.h"
50 #include "PlatformMouseEvent.h"
51 #include "PluginViewBase.h"
52 #include "RenderLayer.h"
53 #include "RenderTheme.h"
54 #include "RenderView.h"
55 #include "RenderWidgetProtector.h"
56 #include "Settings.h"
57 #include "Text.h"
58 #include "TextRun.h"
59 #include <wtf/StackStats.h>
60
61 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
62 #include "HTMLMediaElement.h"
63 #endif
64
65 namespace WebCore {
66
67 using namespace HTMLNames;
68     
69 static const float replacementTextRoundedRectHeight = 18;
70 static const float replacementTextRoundedRectLeftRightTextMargin = 6;
71 static const float replacementTextRoundedRectOpacity = 0.20f;
72 static const float replacementTextPressedRoundedRectOpacity = 0.65f;
73 static const float replacementTextRoundedRectRadius = 5;
74 static const float replacementTextTextOpacity = 0.55f;
75 static const float replacementTextPressedTextOpacity = 0.65f;
76
77 static const Color& replacementTextRoundedRectPressedColor()
78 {
79     static const Color lightGray(205, 205, 205);
80     return lightGray;
81 }
82     
83 RenderEmbeddedObject::RenderEmbeddedObject(Element* element)
84     : RenderPart(element)
85     , m_hasFallbackContent(false)
86     , m_showsUnavailablePluginIndicator(false)
87     , m_unavailablePluginIndicatorIsPressed(false)
88     , m_mouseDownWasInUnavailablePluginIndicator(false)
89 {
90     view()->frameView()->setIsVisuallyNonEmpty();
91 }
92
93 RenderEmbeddedObject::~RenderEmbeddedObject()
94 {
95     if (frameView())
96         frameView()->removeWidgetToUpdate(this);
97 }
98
99 #if USE(ACCELERATED_COMPOSITING)
100 bool RenderEmbeddedObject::requiresLayer() const
101 {
102     if (RenderPart::requiresLayer())
103         return true;
104     
105     return allowsAcceleratedCompositing();
106 }
107
108 bool RenderEmbeddedObject::allowsAcceleratedCompositing() const
109 {
110     return widget() && widget()->isPluginViewBase() && toPluginViewBase(widget())->platformLayer();
111 }
112 #endif
113
114 static String unavailablePluginReplacementText(RenderEmbeddedObject::PluginUnavailabilityReason pluginUnavailabilityReason)
115 {
116     switch (pluginUnavailabilityReason) {
117     case RenderEmbeddedObject::PluginMissing:
118         return missingPluginText();
119     case RenderEmbeddedObject::PluginCrashed:
120         return crashedPluginText();
121     case RenderEmbeddedObject::PluginBlockedByContentSecurityPolicy:
122         return blockedPluginByContentSecurityPolicyText();
123     case RenderEmbeddedObject::InsecurePluginVersion:
124         return insecurePluginVersionText();
125     }
126
127     ASSERT_NOT_REACHED();
128     return String();
129 }
130
131 void RenderEmbeddedObject::setPluginUnavailabilityReason(PluginUnavailabilityReason pluginUnavailabilityReason)
132 {
133     ASSERT(!m_showsUnavailablePluginIndicator);
134     m_showsUnavailablePluginIndicator = true;
135     m_pluginUnavailabilityReason = pluginUnavailabilityReason;
136
137     m_unavailablePluginReplacementText = unavailablePluginReplacementText(pluginUnavailabilityReason);
138 }
139
140 bool RenderEmbeddedObject::showsUnavailablePluginIndicator() const
141 {
142     return m_showsUnavailablePluginIndicator;
143 }
144
145 void RenderEmbeddedObject::setUnavailablePluginIndicatorIsPressed(bool pressed)
146 {
147     if (m_unavailablePluginIndicatorIsPressed == pressed)
148         return;
149     
150     m_unavailablePluginIndicatorIsPressed = pressed;
151     repaint();
152 }
153
154 void RenderEmbeddedObject::paintSnapshotImage(PaintInfo& paintInfo, const LayoutPoint& paintOffset, Image* image)
155 {
156     LayoutUnit cWidth = contentWidth();
157     LayoutUnit cHeight = contentHeight();
158     if (!cWidth || !cHeight)
159         return;
160
161     GraphicsContext* context = paintInfo.context;
162     LayoutSize contentSize(cWidth, cHeight);
163     LayoutPoint contentLocation = location() + paintOffset;
164     contentLocation.move(borderLeft() + paddingLeft(), borderTop() + paddingTop());
165
166     LayoutRect rect(contentLocation, contentSize);
167     IntRect alignedRect = pixelSnappedIntRect(rect);
168     if (alignedRect.width() <= 0 || alignedRect.height() <= 0)
169         return;
170
171     bool useLowQualityScaling = shouldPaintAtLowQuality(context, image, image, alignedRect.size());
172     context->drawImage(image, style()->colorSpace(), alignedRect, CompositeSourceOver, shouldRespectImageOrientation(), useLowQualityScaling);
173 }
174
175 void RenderEmbeddedObject::paintContents(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
176 {
177     Element* element = toElement(node());
178     if (!element || !element->isPluginElement())
179         return;
180
181     HTMLPlugInElement* plugInElement = toHTMLPlugInElement(element);
182
183     if (plugInElement->displayState() > HTMLPlugInElement::DisplayingSnapshot) {
184         RenderPart::paintContents(paintInfo, paintOffset);
185         if (!plugInElement->isRestartedPlugin())
186             return;
187     }
188
189     if (!plugInElement->isPlugInImageElement())
190         return;
191
192     Image* snapshot = toHTMLPlugInImageElement(plugInElement)->snapshotImage();
193     if (snapshot)
194         paintSnapshotImage(paintInfo, paintOffset, snapshot);
195 }
196
197 void RenderEmbeddedObject::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
198 {
199     Page* page = 0;
200     if (Frame* frame = this->frame())
201         page = frame->page();
202
203     if (showsUnavailablePluginIndicator()) {
204         if (page && paintInfo.phase == PaintPhaseForeground)
205             page->addRelevantUnpaintedObject(this, visualOverflowRect());
206         RenderReplaced::paint(paintInfo, paintOffset);
207         return;
208     }
209
210     if (page && paintInfo.phase == PaintPhaseForeground)
211         page->addRelevantRepaintedObject(this, visualOverflowRect());
212
213     RenderPart::paint(paintInfo, paintOffset);
214 }
215
216 void RenderEmbeddedObject::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
217 {
218     if (!showsUnavailablePluginIndicator())
219         return;
220
221     if (paintInfo.phase == PaintPhaseSelection)
222         return;
223     
224     GraphicsContext* context = paintInfo.context;
225     if (context->paintingDisabled())
226         return;
227     
228     FloatRect contentRect;
229     Path path;
230     FloatRect replacementTextRect;
231     Font font;
232     TextRun run("");
233     float textWidth;
234     if (!getReplacementTextGeometry(paintOffset, contentRect, path, replacementTextRect, font, run, textWidth))
235         return;
236     
237     GraphicsContextStateSaver stateSaver(*context);
238     context->clip(contentRect);
239     context->setAlpha(m_unavailablePluginIndicatorIsPressed ? replacementTextPressedRoundedRectOpacity : replacementTextRoundedRectOpacity);
240     context->setFillColor(m_unavailablePluginIndicatorIsPressed ? replacementTextRoundedRectPressedColor() : Color::white, style()->colorSpace());
241     context->fillPath(path);
242
243     const FontMetrics& fontMetrics = font.fontMetrics();
244     float labelX = roundf(replacementTextRect.location().x() + (replacementTextRect.size().width() - textWidth) / 2);
245     float labelY = roundf(replacementTextRect.location().y() + (replacementTextRect.size().height() - fontMetrics.height()) / 2 + fontMetrics.ascent());
246     context->setAlpha(m_unavailablePluginIndicatorIsPressed ? replacementTextPressedTextOpacity : replacementTextTextOpacity);
247     context->setFillColor(Color::black, style()->colorSpace());
248     context->drawBidiText(font, run, FloatPoint(labelX, labelY));
249 }
250
251 bool RenderEmbeddedObject::getReplacementTextGeometry(const LayoutPoint& accumulatedOffset, FloatRect& contentRect, Path& path, FloatRect& replacementTextRect, Font& font, TextRun& run, float& textWidth) const
252 {
253     contentRect = contentBoxRect();
254     contentRect.moveBy(roundedIntPoint(accumulatedOffset));
255     
256     FontDescription fontDescription;
257     RenderTheme::defaultTheme()->systemFont(CSSValueWebkitSmallControl, fontDescription);
258     fontDescription.setWeight(FontWeightBold);
259     Settings* settings = document()->settings();
260     ASSERT(settings);
261     if (!settings)
262         return false;
263     fontDescription.setRenderingMode(settings->fontRenderingMode());
264     fontDescription.setComputedSize(fontDescription.specifiedSize());
265     font = Font(fontDescription, 0, 0);
266     font.update(0);
267
268     run = TextRun(m_unavailablePluginReplacementText);
269     textWidth = font.width(run);
270     
271     replacementTextRect.setSize(FloatSize(textWidth + replacementTextRoundedRectLeftRightTextMargin * 2, replacementTextRoundedRectHeight));
272     float x = (contentRect.size().width() / 2 - replacementTextRect.size().width() / 2) + contentRect.location().x();
273     float y = (contentRect.size().height() / 2 - replacementTextRect.size().height() / 2) + contentRect.location().y();
274     replacementTextRect.setLocation(FloatPoint(x, y));
275     
276     path.addRoundedRect(replacementTextRect, FloatSize(replacementTextRoundedRectRadius, replacementTextRoundedRectRadius));
277
278     return true;
279 }
280
281 LayoutRect RenderEmbeddedObject::replacementTextRect(const LayoutPoint& accumulatedOffset) const
282 {
283     FloatRect contentRect;
284     Path path;
285     FloatRect replacementTextRect;
286     Font font;
287     TextRun run("", 0);
288     float textWidth;
289     if (getReplacementTextGeometry(accumulatedOffset, contentRect, path, replacementTextRect, font, run, textWidth))
290         return LayoutRect(replacementTextRect);
291     
292     return LayoutRect();
293 }
294
295 bool RenderEmbeddedObject::isReplacementObscured() const
296 {
297     // Return whether or not the replacement content for blocked plugins is accessible to the user.
298     
299     // Check the opacity of each layer containing the element or its ancestors.
300     float opacity = 1.0;
301     for (RenderLayer* layer = enclosingLayer(); layer; layer = layer->parent()) {
302         RenderLayerModelObject* renderer = layer->renderer();
303         RenderStyle* style = renderer->style();
304         opacity *= style->opacity();
305         if (opacity < 0.1)
306             return true;
307     }
308
309     // Calculate the absolute rect for the blocked plugin replacement text.
310     IntRect absoluteBoundingBox = absoluteBoundingBoxRect();
311     LayoutPoint absoluteLocation(absoluteBoundingBox.location());
312     LayoutRect rect = replacementTextRect(absoluteLocation);
313     if (rect.isEmpty())
314         return true;
315
316     RenderView* docRenderer = document()->renderView();
317     ASSERT(docRenderer);
318     if (!docRenderer)
319         return true;
320     
321     HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::IgnoreClipping | HitTestRequest::DisallowShadowContent);
322     HitTestResult result;
323     HitTestLocation location;
324     
325     LayoutUnit x = rect.x();
326     LayoutUnit y = rect.y();
327     LayoutUnit width = rect.width();
328     LayoutUnit height = rect.height();
329     
330     // Hit test the center and near the corners of the replacement text to ensure
331     // it is visible and is not masked by other elements.
332     bool hit = false;
333     location = LayoutPoint(x + width / 2, y + height / 2);
334     hit = docRenderer->hitTest(request, location, result);
335     if (!hit || result.innerNode() != node())
336         return true;
337     
338     location = LayoutPoint(x, y);
339     hit = docRenderer->hitTest(request, location, result);
340     if (!hit || result.innerNode() != node())
341         return true;
342     
343     location = LayoutPoint(x + width, y);
344     hit = docRenderer->hitTest(request, location, result);
345     if (!hit || result.innerNode() != node())
346         return true;
347     
348     location = LayoutPoint(x + width, y + height);
349     hit = docRenderer->hitTest(request, location, result);
350     if (!hit || result.innerNode() != node())
351         return true;
352     
353     location = LayoutPoint(x, y + height);
354     hit = docRenderer->hitTest(request, location, result);
355     if (!hit || result.innerNode() != node())
356         return true;
357
358     return false;
359 }
360
361 void RenderEmbeddedObject::layout()
362 {
363     StackStats::LayoutCheckPoint layoutCheckPoint;
364     ASSERT(needsLayout());
365
366     LayoutSize oldSize = contentBoxRect().size();
367
368     updateLogicalWidth();
369     updateLogicalHeight();
370
371     RenderPart::layout();
372
373     m_overflow.clear();
374     addVisualEffectOverflow();
375
376     updateLayerTransform();
377
378     bool wasMissingWidget = false;
379     if (!widget() && frameView() && canHaveWidget()) {
380         wasMissingWidget = true;
381         frameView()->addWidgetToUpdate(this);
382     }
383
384     setNeedsLayout(false);
385
386     LayoutSize newSize = contentBoxRect().size();
387
388     if (!wasMissingWidget && newSize.width() >= oldSize.width() && newSize.height() >= oldSize.height()) {
389         Element* element = toElement(node());
390         if (element && element->isPluginElement() && toHTMLPlugInElement(element)->isPlugInImageElement()) {
391             HTMLPlugInImageElement* plugInImageElement = toHTMLPlugInImageElement(element);
392             if (plugInImageElement->displayState() > HTMLPlugInElement::DisplayingSnapshot && plugInImageElement->snapshotDecision() == HTMLPlugInImageElement::MaySnapshotWhenResized && document()->view()) {
393                 plugInImageElement->setNeedsCheckForSizeChange();
394                 document()->view()->addWidgetToUpdate(this);
395             }
396         }
397     }
398
399     if (!canHaveChildren())
400         return;
401
402     // This code copied from RenderMedia::layout().
403     RenderObject* child = m_children.firstChild();
404
405     if (!child)
406         return;
407
408     RenderBox* childBox = toRenderBox(child);
409
410     if (!childBox)
411         return;
412     
413     if (newSize == oldSize && !childBox->needsLayout())
414         return;
415     
416     // When calling layout() on a child node, a parent must either push a LayoutStateMaintainter, or
417     // instantiate LayoutStateDisabler. Since using a LayoutStateMaintainer is slightly more efficient,
418     // and this method will be called many times per second during playback, use a LayoutStateMaintainer:
419     LayoutStateMaintainer statePusher(view(), this, locationOffset(), hasTransform() || hasReflection() || style()->isFlippedBlocksWritingMode());
420     
421     childBox->setLocation(LayoutPoint(borderLeft(), borderTop()) + LayoutSize(paddingLeft(), paddingTop()));
422     childBox->style()->setHeight(Length(newSize.height(), Fixed));
423     childBox->style()->setWidth(Length(newSize.width(), Fixed));
424     childBox->setNeedsLayout(true, MarkOnlyThis);
425     childBox->layout();
426     setChildNeedsLayout(false);
427     
428     statePusher.pop();
429 }
430
431 void RenderEmbeddedObject::viewCleared()
432 {
433     // This is required for <object> elements whose contents are rendered by WebCore (e.g. src="foo.html").
434     if (node() && widget() && widget()->isFrameView()) {
435         FrameView* view = toFrameView(widget());
436         int marginWidth = -1;
437         int marginHeight = -1;
438         if (node()->hasTagName(iframeTag)) {
439             HTMLIFrameElement* frame = static_cast<HTMLIFrameElement*>(node());
440             marginWidth = frame->marginWidth();
441             marginHeight = frame->marginHeight();
442         }
443         if (marginWidth != -1)
444             view->setMarginWidth(marginWidth);
445         if (marginHeight != -1)
446             view->setMarginHeight(marginHeight);
447     }
448 }
449
450 bool RenderEmbeddedObject::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
451 {
452     if (!RenderPart::nodeAtPoint(request, result, locationInContainer, accumulatedOffset, hitTestAction))
453         return false;
454
455     if (!widget() || !widget()->isPluginViewBase())
456         return true;
457
458     PluginViewBase* view = toPluginViewBase(widget());
459     IntPoint roundedPoint = locationInContainer.roundedPoint();
460
461     if (Scrollbar* horizontalScrollbar = view->horizontalScrollbar()) {
462         if (horizontalScrollbar->shouldParticipateInHitTesting() && horizontalScrollbar->frameRect().contains(roundedPoint)) {
463             result.setScrollbar(horizontalScrollbar);
464             return true;
465         }
466     }
467
468     if (Scrollbar* verticalScrollbar = view->verticalScrollbar()) {
469         if (verticalScrollbar->shouldParticipateInHitTesting() && verticalScrollbar->frameRect().contains(roundedPoint)) {
470             result.setScrollbar(verticalScrollbar);
471             return true;
472         }
473     }
474
475     return true;
476 }
477
478 bool RenderEmbeddedObject::scroll(ScrollDirection direction, ScrollGranularity granularity, float, Node**)
479 {
480     if (!widget() || !widget()->isPluginViewBase())
481         return false;
482
483     return toPluginViewBase(widget())->scroll(direction, granularity);
484 }
485
486 bool RenderEmbeddedObject::logicalScroll(ScrollLogicalDirection direction, ScrollGranularity granularity, float multiplier, Node** stopNode)
487 {
488     // Plugins don't expose a writing direction, so assuming horizontal LTR.
489     return scroll(logicalToPhysical(direction, true, false), granularity, multiplier, stopNode);
490 }
491
492
493 bool RenderEmbeddedObject::isInUnavailablePluginIndicator(const LayoutPoint& point) const
494 {
495     FloatRect contentRect;
496     Path path;
497     FloatRect replacementTextRect;
498     Font font;
499     TextRun run("");
500     float textWidth;
501     return getReplacementTextGeometry(IntPoint(), contentRect, path, replacementTextRect, font, run, textWidth)
502         && path.contains(point);
503 }
504
505 bool RenderEmbeddedObject::isInUnavailablePluginIndicator(MouseEvent* event) const
506 {
507     return isInUnavailablePluginIndicator(roundedLayoutPoint(absoluteToLocal(event->absoluteLocation(), UseTransforms)));
508 }
509
510 static bool shouldUnavailablePluginMessageBeButton(Document* document, RenderEmbeddedObject::PluginUnavailabilityReason pluginUnavailabilityReason)
511 {
512     Page* page = document->page();
513     return page && page->chrome().client()->shouldUnavailablePluginMessageBeButton(pluginUnavailabilityReason);
514 }
515
516 void RenderEmbeddedObject::handleUnavailablePluginIndicatorEvent(Event* event)
517 {
518     if (!shouldUnavailablePluginMessageBeButton(document(), m_pluginUnavailabilityReason))
519         return;
520     
521     if (!event->isMouseEvent())
522         return;
523     
524     MouseEvent* mouseEvent = static_cast<MouseEvent*>(event);
525     HTMLPlugInElement* element = toHTMLPlugInElement(node());
526     if (event->type() == eventNames().mousedownEvent && static_cast<MouseEvent*>(event)->button() == LeftButton) {
527         m_mouseDownWasInUnavailablePluginIndicator = isInUnavailablePluginIndicator(mouseEvent);
528         if (m_mouseDownWasInUnavailablePluginIndicator) {
529             if (Frame* frame = document()->frame()) {
530                 frame->eventHandler()->setCapturingMouseEventsNode(element);
531                 element->setIsCapturingMouseEvents(true);
532             }
533             setUnavailablePluginIndicatorIsPressed(true);
534         }
535         event->setDefaultHandled();
536     }        
537     if (event->type() == eventNames().mouseupEvent && static_cast<MouseEvent*>(event)->button() == LeftButton) {
538         if (m_unavailablePluginIndicatorIsPressed) {
539             if (Frame* frame = document()->frame()) {
540                 frame->eventHandler()->setCapturingMouseEventsNode(0);
541                 element->setIsCapturingMouseEvents(false);
542             }
543             setUnavailablePluginIndicatorIsPressed(false);
544         }
545         if (m_mouseDownWasInUnavailablePluginIndicator && isInUnavailablePluginIndicator(mouseEvent)) {
546             if (Page* page = document()->page())
547                 page->chrome().client()->unavailablePluginButtonClicked(element, m_pluginUnavailabilityReason);
548         }
549         m_mouseDownWasInUnavailablePluginIndicator = false;
550         event->setDefaultHandled();
551     }
552     if (event->type() == eventNames().mousemoveEvent) {
553         setUnavailablePluginIndicatorIsPressed(m_mouseDownWasInUnavailablePluginIndicator && isInUnavailablePluginIndicator(mouseEvent));
554         event->setDefaultHandled();
555     }
556 }
557
558 CursorDirective RenderEmbeddedObject::getCursor(const LayoutPoint& point, Cursor& cursor) const
559 {
560     if (showsUnavailablePluginIndicator() && shouldUnavailablePluginMessageBeButton(document(), m_pluginUnavailabilityReason) && isInUnavailablePluginIndicator(point)) {
561         cursor = handCursor();
562         return SetCursor;
563     }
564     return RenderPart::getCursor(point, cursor);
565 }
566
567 bool RenderEmbeddedObject::canHaveChildren() const
568 {
569 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
570     if (!node())
571         return false;
572
573     if (toElement(node())->isMediaElement())
574         return true;
575 #endif
576
577     if (isSnapshottedPlugIn())
578         return true;
579
580     return false;
581 }
582
583 }