d0d455a760e2fe98444cb8387cf6c215a12a96ca
[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     if (!widget() && frameView() && canHaveWidget())
297         frameView()->addWidgetToUpdate(this);
298
299     setNeedsLayout(false);
300
301     if (!canHaveChildren())
302         return;
303
304     // This code copied from RenderMedia::layout().
305     RenderObject* child = m_children.firstChild();
306
307     if (!child)
308         return;
309
310     RenderBox* childBox = toRenderBox(child);
311
312     if (!childBox)
313         return;
314     
315     LayoutSize newSize = contentBoxRect().size();
316     if (newSize == oldSize && !childBox->needsLayout())
317         return;
318     
319     // When calling layout() on a child node, a parent must either push a LayoutStateMaintainter, or
320     // instantiate LayoutStateDisabler. Since using a LayoutStateMaintainer is slightly more efficient,
321     // and this method will be called many times per second during playback, use a LayoutStateMaintainer:
322     LayoutStateMaintainer statePusher(view(), this, locationOffset(), hasTransform() || hasReflection() || style()->isFlippedBlocksWritingMode());
323     
324     childBox->setLocation(LayoutPoint(borderLeft(), borderTop()) + LayoutSize(paddingLeft(), paddingTop()));
325     childBox->style()->setHeight(Length(newSize.height(), Fixed));
326     childBox->style()->setWidth(Length(newSize.width(), Fixed));
327     childBox->setNeedsLayout(true, MarkOnlyThis);
328     childBox->layout();
329     setChildNeedsLayout(false);
330     
331     statePusher.pop();
332 }
333
334 void RenderEmbeddedObject::viewCleared()
335 {
336     // This is required for <object> elements whose contents are rendered by WebCore (e.g. src="foo.html").
337     if (node() && widget() && widget()->isFrameView()) {
338         FrameView* view = toFrameView(widget());
339         int marginWidth = -1;
340         int marginHeight = -1;
341         if (node()->hasTagName(iframeTag)) {
342             HTMLIFrameElement* frame = static_cast<HTMLIFrameElement*>(node());
343             marginWidth = frame->marginWidth();
344             marginHeight = frame->marginHeight();
345         }
346         if (marginWidth != -1)
347             view->setMarginWidth(marginWidth);
348         if (marginHeight != -1)
349             view->setMarginHeight(marginHeight);
350     }
351 }
352
353 bool RenderEmbeddedObject::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
354 {
355     if (!RenderPart::nodeAtPoint(request, result, locationInContainer, accumulatedOffset, hitTestAction))
356         return false;
357
358     if (!widget() || !widget()->isPluginViewBase())
359         return true;
360
361     PluginViewBase* view = toPluginViewBase(widget());
362     IntPoint roundedPoint = locationInContainer.roundedPoint();
363
364     if (Scrollbar* horizontalScrollbar = view->horizontalScrollbar()) {
365         if (horizontalScrollbar->shouldParticipateInHitTesting() && horizontalScrollbar->frameRect().contains(roundedPoint)) {
366             result.setScrollbar(horizontalScrollbar);
367             return true;
368         }
369     }
370
371     if (Scrollbar* verticalScrollbar = view->verticalScrollbar()) {
372         if (verticalScrollbar->shouldParticipateInHitTesting() && verticalScrollbar->frameRect().contains(roundedPoint)) {
373             result.setScrollbar(verticalScrollbar);
374             return true;
375         }
376     }
377
378     return true;
379 }
380
381 bool RenderEmbeddedObject::scroll(ScrollDirection direction, ScrollGranularity granularity, float, Node**)
382 {
383     if (!widget() || !widget()->isPluginViewBase())
384         return false;
385
386     return toPluginViewBase(widget())->scroll(direction, granularity);
387 }
388
389 bool RenderEmbeddedObject::logicalScroll(ScrollLogicalDirection direction, ScrollGranularity granularity, float multiplier, Node** stopNode)
390 {
391     // Plugins don't expose a writing direction, so assuming horizontal LTR.
392     return scroll(logicalToPhysical(direction, true, false), granularity, multiplier, stopNode);
393 }
394
395
396 bool RenderEmbeddedObject::isInUnavailablePluginIndicator(const LayoutPoint& point) const
397 {
398     FloatRect contentRect;
399     Path path;
400     FloatRect replacementTextRect;
401     Font font;
402     TextRun run("");
403     float textWidth;
404     return getReplacementTextGeometry(IntPoint(), contentRect, path, replacementTextRect, font, run, textWidth)
405         && path.contains(point);
406 }
407
408 bool RenderEmbeddedObject::isInUnavailablePluginIndicator(MouseEvent* event) const
409 {
410     return isInUnavailablePluginIndicator(roundedLayoutPoint(absoluteToLocal(event->absoluteLocation(), UseTransforms)));
411 }
412
413 static bool shouldUnavailablePluginMessageBeButton(Document* document, RenderEmbeddedObject::PluginUnavailabilityReason pluginUnavailabilityReason)
414 {
415     Page* page = document->page();
416     return page && page->chrome()->client()->shouldUnavailablePluginMessageBeButton(pluginUnavailabilityReason);
417 }
418
419 void RenderEmbeddedObject::handleUnavailablePluginIndicatorEvent(Event* event)
420 {
421     if (!shouldUnavailablePluginMessageBeButton(document(), m_pluginUnavailabilityReason))
422         return;
423     
424     if (!event->isMouseEvent())
425         return;
426     
427     MouseEvent* mouseEvent = static_cast<MouseEvent*>(event);
428     HTMLPlugInElement* element = toHTMLPlugInElement(node());
429     if (event->type() == eventNames().mousedownEvent && static_cast<MouseEvent*>(event)->button() == LeftButton) {
430         m_mouseDownWasInUnavailablePluginIndicator = isInUnavailablePluginIndicator(mouseEvent);
431         if (m_mouseDownWasInUnavailablePluginIndicator) {
432             if (Frame* frame = document()->frame()) {
433                 frame->eventHandler()->setCapturingMouseEventsNode(element);
434                 element->setIsCapturingMouseEvents(true);
435             }
436             setUnavailablePluginIndicatorIsPressed(true);
437         }
438         event->setDefaultHandled();
439     }        
440     if (event->type() == eventNames().mouseupEvent && static_cast<MouseEvent*>(event)->button() == LeftButton) {
441         if (m_unavailablePluginIndicatorIsPressed) {
442             if (Frame* frame = document()->frame()) {
443                 frame->eventHandler()->setCapturingMouseEventsNode(0);
444                 element->setIsCapturingMouseEvents(false);
445             }
446             setUnavailablePluginIndicatorIsPressed(false);
447         }
448         if (m_mouseDownWasInUnavailablePluginIndicator && isInUnavailablePluginIndicator(mouseEvent)) {
449             if (Page* page = document()->page())
450                 page->chrome()->client()->unavailablePluginButtonClicked(element, m_pluginUnavailabilityReason);
451         }
452         m_mouseDownWasInUnavailablePluginIndicator = false;
453         event->setDefaultHandled();
454     }
455     if (event->type() == eventNames().mousemoveEvent) {
456         setUnavailablePluginIndicatorIsPressed(m_mouseDownWasInUnavailablePluginIndicator && isInUnavailablePluginIndicator(mouseEvent));
457         event->setDefaultHandled();
458     }
459 }
460
461 CursorDirective RenderEmbeddedObject::getCursor(const LayoutPoint& point, Cursor& cursor) const
462 {
463     if (showsUnavailablePluginIndicator() && shouldUnavailablePluginMessageBeButton(document(), m_pluginUnavailabilityReason) && isInUnavailablePluginIndicator(point)) {
464         cursor = handCursor();
465         return SetCursor;
466     }
467     return RenderPart::getCursor(point, cursor);
468 }
469
470 bool RenderEmbeddedObject::canHaveChildren() const
471 {
472 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
473     if (!node())
474         return false;
475
476     if (toElement(node())->isMediaElement())
477         return true;
478 #endif
479
480     if (isSnapshottedPlugIn())
481         return true;
482
483     return false;
484 }
485
486 }