Plugins that resize might need to be snapshotted.
[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 "Chrome.h"
28 #include "ChromeClient.h"
29 #include "Cursor.h"
30 #include "CSSValueKeywords.h"
31 #include "Font.h"
32 #include "FontSelector.h"
33 #include "Frame.h"
34 #include "FrameLoaderClient.h"
35 #include "GraphicsContext.h"
36 #include "HTMLEmbedElement.h"
37 #include "HTMLIFrameElement.h"
38 #include "HTMLNames.h"
39 #include "HTMLObjectElement.h"
40 #include "HTMLParamElement.h"
41 #include "HTMLPlugInElement.h"
42 #include "HitTestResult.h"
43 #include "LocalizedStrings.h"
44 #include "MIMETypeRegistry.h"
45 #include "MouseEvent.h"
46 #include "Page.h"
47 #include "PaintInfo.h"
48 #include "Path.h"
49 #include "PluginViewBase.h"
50 #include "RenderTheme.h"
51 #include "RenderView.h"
52 #include "RenderWidgetProtector.h"
53 #include "Settings.h"
54 #include "Text.h"
55 #include "TextRun.h"
56
57 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
58 #include "HTMLMediaElement.h"
59 #endif
60
61 namespace WebCore {
62
63 using namespace HTMLNames;
64     
65 static const float replacementTextRoundedRectHeight = 18;
66 static const float replacementTextRoundedRectLeftRightTextMargin = 6;
67 static const float replacementTextRoundedRectOpacity = 0.20f;
68 static const float replacementTextPressedRoundedRectOpacity = 0.65f;
69 static const float replacementTextRoundedRectRadius = 5;
70 static const float replacementTextTextOpacity = 0.55f;
71 static const float replacementTextPressedTextOpacity = 0.65f;
72
73 static const Color& replacementTextRoundedRectPressedColor()
74 {
75     static const Color lightGray(205, 205, 205);
76     return lightGray;
77 }
78     
79 RenderEmbeddedObject::RenderEmbeddedObject(Element* element)
80     : RenderPart(element)
81     , m_hasFallbackContent(false)
82     , m_showsUnavailablePluginIndicator(false)
83     , m_unavailablePluginIndicatorIsPressed(false)
84     , m_mouseDownWasInUnavailablePluginIndicator(false)
85 {
86     view()->frameView()->setIsVisuallyNonEmpty();
87 }
88
89 RenderEmbeddedObject::~RenderEmbeddedObject()
90 {
91     if (frameView())
92         frameView()->removeWidgetToUpdate(this);
93 }
94
95 #if USE(ACCELERATED_COMPOSITING)
96 bool RenderEmbeddedObject::requiresLayer() const
97 {
98     if (RenderPart::requiresLayer())
99         return true;
100     
101     return allowsAcceleratedCompositing();
102 }
103
104 bool RenderEmbeddedObject::allowsAcceleratedCompositing() const
105 {
106     return widget() && widget()->isPluginViewBase() && toPluginViewBase(widget())->platformLayer();
107 }
108 #endif
109
110 static String unavailablePluginReplacementText(RenderEmbeddedObject::PluginUnavailabilityReason pluginUnavailabilityReason)
111 {
112     switch (pluginUnavailabilityReason) {
113     case RenderEmbeddedObject::PluginMissing:
114         return missingPluginText();
115     case RenderEmbeddedObject::PluginCrashed:
116         return crashedPluginText();
117     case RenderEmbeddedObject::PluginBlockedByContentSecurityPolicy:
118         return blockedPluginByContentSecurityPolicyText();
119     case RenderEmbeddedObject::InsecurePluginVersion:
120         return insecurePluginVersionText();
121     case RenderEmbeddedObject::PluginInactive:
122         return inactivePluginText();
123     }
124
125     ASSERT_NOT_REACHED();
126     return String();
127 }
128
129 void RenderEmbeddedObject::setPluginUnavailabilityReason(PluginUnavailabilityReason pluginUnavailabilityReason)
130 {
131     ASSERT(!m_showsUnavailablePluginIndicator);
132     m_showsUnavailablePluginIndicator = true;
133     m_pluginUnavailabilityReason = pluginUnavailabilityReason;
134
135     m_unavailablePluginReplacementText = unavailablePluginReplacementText(pluginUnavailabilityReason);
136 }
137
138 bool RenderEmbeddedObject::showsUnavailablePluginIndicator() const
139 {
140     return m_showsUnavailablePluginIndicator;
141 }
142
143 void RenderEmbeddedObject::setUnavailablePluginIndicatorIsPressed(bool pressed)
144 {
145     if (m_unavailablePluginIndicatorIsPressed == pressed)
146         return;
147     
148     m_unavailablePluginIndicatorIsPressed = pressed;
149     repaint();
150 }
151
152 void RenderEmbeddedObject::paintSnapshotImage(PaintInfo& paintInfo, const LayoutPoint& paintOffset, Image* image)
153 {
154     LayoutUnit cWidth = contentWidth();
155     LayoutUnit cHeight = contentHeight();
156     if (!cWidth || !cHeight)
157         return;
158
159     GraphicsContext* context = paintInfo.context;
160     LayoutSize contentSize(cWidth, cHeight);
161     LayoutPoint contentLocation = location() + paintOffset;
162     contentLocation.move(borderLeft() + paddingLeft(), borderTop() + paddingTop());
163
164     LayoutRect rect(contentLocation, contentSize);
165     IntRect alignedRect = pixelSnappedIntRect(rect);
166     if (alignedRect.width() <= 0 || alignedRect.height() <= 0)
167         return;
168
169     bool useLowQualityScaling = shouldPaintAtLowQuality(context, image, image, alignedRect.size());
170     context->drawImage(image, style()->colorSpace(), alignedRect, CompositeSourceOver, shouldRespectImageOrientation(), useLowQualityScaling);
171 }
172
173 void RenderEmbeddedObject::paintContents(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
174 {
175     Element* element = toElement(node());
176     if (!element || !element->isPluginElement())
177         return;
178
179     HTMLPlugInElement* plugInElement = toHTMLPlugInElement(element);
180
181     if (plugInElement->displayState() > HTMLPlugInElement::DisplayingSnapshot) {
182         RenderPart::paintContents(paintInfo, paintOffset);
183         if (!plugInElement->restartedPlugin())
184             return;
185     }
186
187     if (!plugInElement->isPlugInImageElement())
188         return;
189
190     Image* snapshot = toHTMLPlugInImageElement(plugInElement)->snapshotImage();
191     if (snapshot)
192         paintSnapshotImage(paintInfo, paintOffset, snapshot);
193 }
194
195 void RenderEmbeddedObject::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
196 {
197     Page* page = 0;
198     if (Frame* frame = this->frame())
199         page = frame->page();
200
201     if (showsUnavailablePluginIndicator()) {
202         if (page && paintInfo.phase == PaintPhaseForeground)
203             page->addRelevantUnpaintedObject(this, visualOverflowRect());
204         RenderReplaced::paint(paintInfo, paintOffset);
205         return;
206     }
207
208     if (page && paintInfo.phase == PaintPhaseForeground)
209         page->addRelevantRepaintedObject(this, visualOverflowRect());
210
211     RenderPart::paint(paintInfo, paintOffset);
212 }
213
214 void RenderEmbeddedObject::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
215 {
216     if (!showsUnavailablePluginIndicator())
217         return;
218
219     if (paintInfo.phase == PaintPhaseSelection)
220         return;
221     
222     GraphicsContext* context = paintInfo.context;
223     if (context->paintingDisabled())
224         return;
225     
226     FloatRect contentRect;
227     Path path;
228     FloatRect replacementTextRect;
229     Font font;
230     TextRun run("");
231     float textWidth;
232     if (!getReplacementTextGeometry(paintOffset, contentRect, path, replacementTextRect, font, run, textWidth))
233         return;
234     
235     GraphicsContextStateSaver stateSaver(*context);
236     context->clip(contentRect);
237     context->setAlpha(m_unavailablePluginIndicatorIsPressed ? replacementTextPressedRoundedRectOpacity : replacementTextRoundedRectOpacity);
238     context->setFillColor(m_unavailablePluginIndicatorIsPressed ? replacementTextRoundedRectPressedColor() : Color::white, style()->colorSpace());
239     context->fillPath(path);
240
241     const FontMetrics& fontMetrics = font.fontMetrics();
242     float labelX = roundf(replacementTextRect.location().x() + (replacementTextRect.size().width() - textWidth) / 2);
243     float labelY = roundf(replacementTextRect.location().y() + (replacementTextRect.size().height() - fontMetrics.height()) / 2 + fontMetrics.ascent());
244     context->setAlpha(m_unavailablePluginIndicatorIsPressed ? replacementTextPressedTextOpacity : replacementTextTextOpacity);
245     context->setFillColor(Color::black, style()->colorSpace());
246     context->drawBidiText(font, run, FloatPoint(labelX, labelY));
247 }
248
249 bool RenderEmbeddedObject::getReplacementTextGeometry(const LayoutPoint& accumulatedOffset, FloatRect& contentRect, Path& path, FloatRect& replacementTextRect, Font& font, TextRun& run, float& textWidth) const
250 {
251     contentRect = contentBoxRect();
252     contentRect.moveBy(roundedIntPoint(accumulatedOffset));
253     
254     FontDescription fontDescription;
255     RenderTheme::defaultTheme()->systemFont(CSSValueWebkitSmallControl, fontDescription);
256     fontDescription.setWeight(FontWeightBold);
257     Settings* settings = document()->settings();
258     ASSERT(settings);
259     if (!settings)
260         return false;
261     fontDescription.setRenderingMode(settings->fontRenderingMode());
262     fontDescription.setComputedSize(fontDescription.specifiedSize());
263     font = Font(fontDescription, 0, 0);
264     font.update(0);
265
266     run = TextRun(m_unavailablePluginReplacementText);
267     textWidth = font.width(run);
268     
269     replacementTextRect.setSize(FloatSize(textWidth + replacementTextRoundedRectLeftRightTextMargin * 2, replacementTextRoundedRectHeight));
270     float x = (contentRect.size().width() / 2 - replacementTextRect.size().width() / 2) + contentRect.location().x();
271     float y = (contentRect.size().height() / 2 - replacementTextRect.size().height() / 2) + contentRect.location().y();
272     replacementTextRect.setLocation(FloatPoint(x, y));
273     
274     path.addRoundedRect(replacementTextRect, FloatSize(replacementTextRoundedRectRadius, replacementTextRoundedRectRadius));
275
276     return true;
277 }
278
279 void RenderEmbeddedObject::layout()
280 {
281     StackStats::LayoutCheckPoint layoutCheckPoint;
282     ASSERT(needsLayout());
283
284     LayoutSize oldSize = contentBoxRect().size();
285
286     updateLogicalWidth();
287     updateLogicalHeight();
288
289     RenderPart::layout();
290
291     m_overflow.clear();
292     addVisualEffectOverflow();
293
294     updateLayerTransform();
295
296     bool wasMissingWidget = false;
297     if (!widget() && frameView() && canHaveWidget()) {
298         wasMissingWidget = true;
299         frameView()->addWidgetToUpdate(this);
300     }
301
302     setNeedsLayout(false);
303
304     LayoutSize newSize = contentBoxRect().size();
305
306     if (!wasMissingWidget && newSize.width() >= oldSize.width() && newSize.height() >= oldSize.height()) {
307         Element* element = toElement(node());
308         if (element && element->isPluginElement() && toHTMLPlugInElement(element)->isPlugInImageElement()) {
309             HTMLPlugInImageElement* plugInImageElement = toHTMLPlugInImageElement(element);
310             if (plugInImageElement->displayState() > HTMLPlugInElement::DisplayingSnapshot && plugInImageElement->snapshotDecision() == HTMLPlugInImageElement::MaySnapshotWhenResized && document()->view()) {
311                 plugInImageElement->setNeedsCheckForSizeChange();
312                 document()->view()->addWidgetToUpdate(this);
313             }
314         }
315     }
316
317     if (!canHaveChildren())
318         return;
319
320     // This code copied from RenderMedia::layout().
321     RenderObject* child = m_children.firstChild();
322
323     if (!child)
324         return;
325
326     RenderBox* childBox = toRenderBox(child);
327
328     if (!childBox)
329         return;
330     
331     if (newSize == oldSize && !childBox->needsLayout())
332         return;
333     
334     // When calling layout() on a child node, a parent must either push a LayoutStateMaintainter, or
335     // instantiate LayoutStateDisabler. Since using a LayoutStateMaintainer is slightly more efficient,
336     // and this method will be called many times per second during playback, use a LayoutStateMaintainer:
337     LayoutStateMaintainer statePusher(view(), this, locationOffset(), hasTransform() || hasReflection() || style()->isFlippedBlocksWritingMode());
338     
339     childBox->setLocation(LayoutPoint(borderLeft(), borderTop()) + LayoutSize(paddingLeft(), paddingTop()));
340     childBox->style()->setHeight(Length(newSize.height(), Fixed));
341     childBox->style()->setWidth(Length(newSize.width(), Fixed));
342     childBox->setNeedsLayout(true, MarkOnlyThis);
343     childBox->layout();
344     setChildNeedsLayout(false);
345     
346     statePusher.pop();
347 }
348
349 void RenderEmbeddedObject::viewCleared()
350 {
351     // This is required for <object> elements whose contents are rendered by WebCore (e.g. src="foo.html").
352     if (node() && widget() && widget()->isFrameView()) {
353         FrameView* view = toFrameView(widget());
354         int marginWidth = -1;
355         int marginHeight = -1;
356         if (node()->hasTagName(iframeTag)) {
357             HTMLIFrameElement* frame = static_cast<HTMLIFrameElement*>(node());
358             marginWidth = frame->marginWidth();
359             marginHeight = frame->marginHeight();
360         }
361         if (marginWidth != -1)
362             view->setMarginWidth(marginWidth);
363         if (marginHeight != -1)
364             view->setMarginHeight(marginHeight);
365     }
366 }
367
368 bool RenderEmbeddedObject::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
369 {
370     if (!RenderPart::nodeAtPoint(request, result, locationInContainer, accumulatedOffset, hitTestAction))
371         return false;
372
373     if (!widget() || !widget()->isPluginViewBase())
374         return true;
375
376     PluginViewBase* view = toPluginViewBase(widget());
377     IntPoint roundedPoint = locationInContainer.roundedPoint();
378
379     if (Scrollbar* horizontalScrollbar = view->horizontalScrollbar()) {
380         if (horizontalScrollbar->shouldParticipateInHitTesting() && horizontalScrollbar->frameRect().contains(roundedPoint)) {
381             result.setScrollbar(horizontalScrollbar);
382             return true;
383         }
384     }
385
386     if (Scrollbar* verticalScrollbar = view->verticalScrollbar()) {
387         if (verticalScrollbar->shouldParticipateInHitTesting() && verticalScrollbar->frameRect().contains(roundedPoint)) {
388             result.setScrollbar(verticalScrollbar);
389             return true;
390         }
391     }
392
393     return true;
394 }
395
396 bool RenderEmbeddedObject::scroll(ScrollDirection direction, ScrollGranularity granularity, float, Node**)
397 {
398     if (!widget() || !widget()->isPluginViewBase())
399         return false;
400
401     return toPluginViewBase(widget())->scroll(direction, granularity);
402 }
403
404 bool RenderEmbeddedObject::logicalScroll(ScrollLogicalDirection direction, ScrollGranularity granularity, float multiplier, Node** stopNode)
405 {
406     // Plugins don't expose a writing direction, so assuming horizontal LTR.
407     return scroll(logicalToPhysical(direction, true, false), granularity, multiplier, stopNode);
408 }
409
410
411 bool RenderEmbeddedObject::isInUnavailablePluginIndicator(const LayoutPoint& point) const
412 {
413     FloatRect contentRect;
414     Path path;
415     FloatRect replacementTextRect;
416     Font font;
417     TextRun run("");
418     float textWidth;
419     return getReplacementTextGeometry(IntPoint(), contentRect, path, replacementTextRect, font, run, textWidth)
420         && path.contains(point);
421 }
422
423 bool RenderEmbeddedObject::isInUnavailablePluginIndicator(MouseEvent* event) const
424 {
425     return isInUnavailablePluginIndicator(roundedLayoutPoint(absoluteToLocal(event->absoluteLocation(), UseTransforms)));
426 }
427
428 static bool shouldUnavailablePluginMessageBeButton(Document* document, RenderEmbeddedObject::PluginUnavailabilityReason pluginUnavailabilityReason)
429 {
430     Page* page = document->page();
431     return page && page->chrome()->client()->shouldUnavailablePluginMessageBeButton(pluginUnavailabilityReason);
432 }
433
434 void RenderEmbeddedObject::handleUnavailablePluginIndicatorEvent(Event* event)
435 {
436     if (!shouldUnavailablePluginMessageBeButton(document(), m_pluginUnavailabilityReason))
437         return;
438     
439     if (!event->isMouseEvent())
440         return;
441     
442     MouseEvent* mouseEvent = static_cast<MouseEvent*>(event);
443     HTMLPlugInElement* element = toHTMLPlugInElement(node());
444     if (event->type() == eventNames().mousedownEvent && static_cast<MouseEvent*>(event)->button() == LeftButton) {
445         m_mouseDownWasInUnavailablePluginIndicator = isInUnavailablePluginIndicator(mouseEvent);
446         if (m_mouseDownWasInUnavailablePluginIndicator) {
447             if (Frame* frame = document()->frame()) {
448                 frame->eventHandler()->setCapturingMouseEventsNode(element);
449                 element->setIsCapturingMouseEvents(true);
450             }
451             setUnavailablePluginIndicatorIsPressed(true);
452         }
453         event->setDefaultHandled();
454     }        
455     if (event->type() == eventNames().mouseupEvent && static_cast<MouseEvent*>(event)->button() == LeftButton) {
456         if (m_unavailablePluginIndicatorIsPressed) {
457             if (Frame* frame = document()->frame()) {
458                 frame->eventHandler()->setCapturingMouseEventsNode(0);
459                 element->setIsCapturingMouseEvents(false);
460             }
461             setUnavailablePluginIndicatorIsPressed(false);
462         }
463         if (m_mouseDownWasInUnavailablePluginIndicator && isInUnavailablePluginIndicator(mouseEvent)) {
464             if (Page* page = document()->page())
465                 page->chrome()->client()->unavailablePluginButtonClicked(element, m_pluginUnavailabilityReason);
466         }
467         m_mouseDownWasInUnavailablePluginIndicator = false;
468         event->setDefaultHandled();
469     }
470     if (event->type() == eventNames().mousemoveEvent) {
471         setUnavailablePluginIndicatorIsPressed(m_mouseDownWasInUnavailablePluginIndicator && isInUnavailablePluginIndicator(mouseEvent));
472         event->setDefaultHandled();
473     }
474 }
475
476 CursorDirective RenderEmbeddedObject::getCursor(const LayoutPoint& point, Cursor& cursor) const
477 {
478     if (showsUnavailablePluginIndicator() && shouldUnavailablePluginMessageBeButton(document(), m_pluginUnavailabilityReason) && isInUnavailablePluginIndicator(point)) {
479         cursor = handCursor();
480         return SetCursor;
481     }
482     return RenderPart::getCursor(point, cursor);
483 }
484
485 bool RenderEmbeddedObject::canHaveChildren() const
486 {
487 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
488     if (!node())
489         return false;
490
491     if (toElement(node())->isMediaElement())
492         return true;
493 #endif
494
495     if (isSnapshottedPlugIn())
496         return true;
497
498     return false;
499 }
500
501 }