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