2 * Copyright (C) 2009 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
14 * * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include "WebPluginContainerImpl.h"
35 #include "ChromeClientImpl.h"
36 #include "WebCursorInfo.h"
37 #include "WebDataSourceImpl.h"
38 #include "WebInputEvent.h"
39 #include "WebInputEventConversion.h"
41 #include "WebPlugin.h"
43 #include "WebURLError.h"
44 #include "WebURLRequest.h"
45 #include "WebVector.h"
46 #include "WrappedResourceResponse.h"
48 #include "EventNames.h"
49 #include "FocusController.h"
50 #include "FormState.h"
52 #include "FrameLoadRequest.h"
53 #include "FrameView.h"
54 #include "GraphicsContext.h"
55 #include "HostWindow.h"
56 #include "HTMLFormElement.h"
57 #include "HTMLNames.h"
58 #include "HTMLPlugInElement.h"
59 #include "KeyboardEvent.h"
60 #include "MouseEvent.h"
62 #include "ScrollView.h"
63 #include "WheelEvent.h"
66 #include "PlatformContextSkia.h"
69 using namespace WebCore;
73 // Public methods --------------------------------------------------------------
75 void WebPluginContainerImpl::setFrameRect(const IntRect& frameRect)
77 Widget::setFrameRect(frameRect);
81 void WebPluginContainerImpl::paint(GraphicsContext* gc, const IntRect& damageRect)
83 if (gc->paintingDisabled())
89 // Don't paint anything if the plugin doesn't intersect the damage rect.
90 if (!frameRect().intersects(damageRect))
95 ASSERT(parent()->isFrameView());
96 ScrollView* view = parent();
98 // The plugin is positioned in window coordinates, so it needs to be painted
99 // in window coordinates.
100 IntPoint origin = view->windowToContents(IntPoint(0, 0));
101 gc->translate(static_cast<float>(origin.x()), static_cast<float>(origin.y()));
103 #if WEBKIT_USING_SKIA
104 WebCanvas* canvas = gc->platformContext()->canvas();
105 #elif WEBKIT_USING_CG
106 WebCanvas* canvas = gc->platformContext();
110 IntRect(view->contentsToWindow(damageRect.location()), damageRect.size());
111 m_webPlugin->paint(canvas, windowRect);
116 void WebPluginContainerImpl::invalidateRect(const IntRect& rect)
121 IntRect damageRect = convertToContainingWindow(rect);
123 // Get our clip rect and intersect with it to ensure we don't invalidate
125 IntRect clipRect = parent()->windowClipRect();
126 damageRect.intersect(clipRect);
128 parent()->hostWindow()->invalidateContentsAndWindow(damageRect, false /*immediate*/);
131 void WebPluginContainerImpl::setFocus()
134 m_webPlugin->updateFocus(true);
137 void WebPluginContainerImpl::show()
139 setSelfVisible(true);
140 m_webPlugin->updateVisibility(true);
145 void WebPluginContainerImpl::hide()
147 setSelfVisible(false);
148 m_webPlugin->updateVisibility(false);
153 void WebPluginContainerImpl::handleEvent(Event* event)
155 if (!m_webPlugin->acceptsInputEvents())
158 // The events we pass are defined at:
159 // http://devedge-temp.mozilla.org/library/manuals/2002/plugin/1.0/structures5.html#1000000
160 // Don't take the documentation as truth, however. There are many cases
161 // where mozilla behaves differently than the spec.
162 if (event->isMouseEvent())
163 handleMouseEvent(static_cast<MouseEvent*>(event));
164 else if (event->isWheelEvent())
165 handleWheelEvent(static_cast<WheelEvent*>(event));
166 else if (event->isKeyboardEvent())
167 handleKeyboardEvent(static_cast<KeyboardEvent*>(event));
170 void WebPluginContainerImpl::frameRectsChanged()
172 Widget::frameRectsChanged();
176 void WebPluginContainerImpl::widgetPositionsUpdated()
178 Widget::widgetPositionsUpdated();
182 void WebPluginContainerImpl::setParentVisible(bool parentVisible)
184 // We override this function to make sure that geometry updates are sent
185 // over to the plugin. For e.g. when a plugin is instantiated it does not
186 // have a valid parent. As a result the first geometry update from webkit
187 // is ignored. This function is called when the plugin eventually gets a
190 if (isParentVisible() == parentVisible)
191 return; // No change.
193 Widget::setParentVisible(parentVisible);
194 if (!isSelfVisible())
195 return; // This widget has explicitely been marked as not visible.
197 m_webPlugin->updateVisibility(isVisible());
200 void WebPluginContainerImpl::setParent(ScrollView* view)
202 // We override this function so that if the plugin is windowed, we can call
203 // NPP_SetWindow at the first possible moment. This ensures that
204 // NPP_SetWindow is called before the manual load data is sent to a plugin.
205 // If this order is reversed, Flash won't load videos.
207 Widget::setParent(view);
212 bool WebPluginContainerImpl::supportsPaginatedPrint() const
214 return m_webPlugin->supportsPaginatedPrint();
217 int WebPluginContainerImpl::printBegin(const IntRect& printableArea,
218 int printerDPI) const
220 return m_webPlugin->printBegin(printableArea, printerDPI);
223 bool WebPluginContainerImpl::printPage(int pageNumber,
224 WebCore::GraphicsContext* gc)
227 #if WEBKIT_USING_SKIA
228 WebCanvas* canvas = gc->platformContext()->canvas();
229 #elif WEBKIT_USING_CG
230 WebCanvas* canvas = gc->platformContext();
232 bool ret = m_webPlugin->printPage(pageNumber, canvas);
237 void WebPluginContainerImpl::printEnd()
239 return m_webPlugin->printEnd();
242 void WebPluginContainerImpl::invalidate()
244 Widget::invalidate();
247 void WebPluginContainerImpl::invalidateRect(const WebRect& rect)
249 invalidateRect(static_cast<IntRect>(rect));
252 void WebPluginContainerImpl::reportGeometry()
257 IntRect windowRect, clipRect;
258 Vector<IntRect> cutOutRects;
259 calculateGeometry(frameRect(), windowRect, clipRect, cutOutRects);
261 m_webPlugin->updateGeometry(windowRect, clipRect, cutOutRects, isVisible());
264 void WebPluginContainerImpl::clearScriptObjects()
266 Frame* frame = m_element->document()->frame();
269 frame->script()->cleanupScriptObjectsForPlugin(this);
272 NPObject* WebPluginContainerImpl::scriptableObjectForElement()
274 return m_element->getNPObject();
277 WebString WebPluginContainerImpl::executeScriptURL(const WebURL& url, bool popupsAllowed)
279 Frame* frame = m_element->document()->frame();
283 const KURL& kurl = url;
284 ASSERT(kurl.protocolIs("javascript"));
286 String script = decodeURLEscapeSequences(
287 kurl.string().substring(strlen("javascript:")));
289 ScriptValue result = frame->script()->executeScript(script, popupsAllowed);
291 // Failure is reported as a null string.
293 result.getString(resultStr);
297 void WebPluginContainerImpl::loadFrameRequest(
298 const WebURLRequest& request, const WebString& target, bool notifyNeeded, void* notifyData)
300 Frame* frame = m_element->document()->frame();
302 return; // FIXME: send a notification in this case?
305 // FIXME: This is a bit of hack to allow us to observe completion of
306 // our frame request. It would be better to evolve FrameLoader to
307 // support a completion callback instead.
308 WebPluginLoadObserver* observer =
309 new WebPluginLoadObserver(this, request.url(), notifyData);
310 m_pluginLoadObservers.append(observer);
311 WebDataSourceImpl::setNextPluginLoadObserver(observer);
314 FrameLoadRequest frameRequest(request.toResourceRequest());
315 frameRequest.setFrameName(target);
317 frame->loader()->loadFrameRequest(
319 false, // lock history
320 false, // lock back forward list
326 void WebPluginContainerImpl::didReceiveResponse(const ResourceResponse& response)
328 // Make sure that the plugin receives window geometry before data, or else
329 // plugins misbehave.
332 WrappedResourceResponse urlResponse(response);
333 m_webPlugin->didReceiveResponse(urlResponse);
336 void WebPluginContainerImpl::didReceiveData(const char *data, int dataLength)
338 m_webPlugin->didReceiveData(data, dataLength);
341 void WebPluginContainerImpl::didFinishLoading()
343 m_webPlugin->didFinishLoading();
346 void WebPluginContainerImpl::didFailLoading(const ResourceError& error)
348 m_webPlugin->didFailLoading(error);
351 NPObject* WebPluginContainerImpl::scriptableObject()
353 return m_webPlugin->scriptableObject();
356 void WebPluginContainerImpl::willDestroyPluginLoadObserver(WebPluginLoadObserver* observer)
358 size_t pos = m_pluginLoadObservers.find(observer);
361 m_pluginLoadObservers.remove(pos);
364 // Private methods -------------------------------------------------------------
366 WebPluginContainerImpl::~WebPluginContainerImpl()
368 for (size_t i = 0; i < m_pluginLoadObservers.size(); ++i)
369 m_pluginLoadObservers[i]->clearPluginContainer();
370 m_webPlugin->destroy();
373 void WebPluginContainerImpl::handleMouseEvent(MouseEvent* event)
375 ASSERT(parent()->isFrameView());
377 // We cache the parent FrameView here as the plugin widget could be deleted
378 // in the call to HandleEvent. See http://b/issue?id=1362948
379 FrameView* parentView = static_cast<FrameView*>(parent());
381 WebMouseEventBuilder webEvent(parentView, *event);
382 if (webEvent.type == WebInputEvent::Undefined)
385 if (event->type() == eventNames().mousedownEvent) {
386 // Ensure that the frame containing the plugin has focus.
387 Frame* containingFrame = parentView->frame();
388 if (Page* currentPage = containingFrame->page())
389 currentPage->focusController()->setFocusedFrame(containingFrame);
390 // Give focus to our containing HTMLPluginElement.
391 containingFrame->document()->setFocusedNode(m_element);
394 WebCursorInfo cursorInfo;
395 if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
396 event->setDefaultHandled();
398 // A windowless plugin can change the cursor in response to a mouse move
399 // event. We need to reflect the changed cursor in the frame view as the
400 // mouse is moved in the boundaries of the windowless plugin.
401 Page* page = parentView->frame()->page();
404 ChromeClientImpl* chromeClient =
405 static_cast<ChromeClientImpl*>(page->chrome()->client());
406 chromeClient->setCursorForPlugin(cursorInfo);
409 void WebPluginContainerImpl::handleWheelEvent(WheelEvent* event)
411 FrameView* parentView = static_cast<FrameView*>(parent());
412 WebMouseWheelEventBuilder webEvent(parentView, *event);
413 if (webEvent.type == WebInputEvent::Undefined)
416 WebCursorInfo cursorInfo;
417 if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
418 event->setDefaultHandled();
421 void WebPluginContainerImpl::handleKeyboardEvent(KeyboardEvent* event)
423 WebKeyboardEventBuilder webEvent(*event);
424 if (webEvent.type == WebInputEvent::Undefined)
427 WebCursorInfo cursorInfo;
428 if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
429 event->setDefaultHandled();
432 void WebPluginContainerImpl::calculateGeometry(const IntRect& frameRect,
435 Vector<IntRect>& cutOutRects)
437 windowRect = IntRect(
438 parent()->contentsToWindow(frameRect.location()), frameRect.size());
440 // Calculate a clip-rect so that we don't overlap the scrollbars, etc.
441 clipRect = windowClipRect();
442 clipRect.move(-windowRect.x(), -windowRect.y());
444 windowCutOutRects(frameRect, cutOutRects);
445 // Convert to the plugin position.
446 for (size_t i = 0; i < cutOutRects.size(); i++)
447 cutOutRects[i].move(-frameRect.x(), -frameRect.y());
450 WebCore::IntRect WebPluginContainerImpl::windowClipRect() const
452 // Start by clipping to our bounds.
454 convertToContainingWindow(IntRect(0, 0, width(), height()));
456 // document()->renderer() can be 0 when we receive messages from the
457 // plugins while we are destroying a frame.
458 if (m_element->renderer()->document()->renderer()) {
459 // Take our element and get the clip rect from the enclosing layer and
461 RenderLayer* layer = m_element->renderer()->enclosingLayer();
463 m_element->document()->view()->windowClipRectForLayer(layer, true));
469 static void getObjectStack(const RenderObject* ro,
470 Vector<const RenderObject*>* roStack)
479 // Returns true if stack1 is at or above stack2
480 static bool checkStackOnTop(
481 const Vector<const RenderObject*>& iframeZstack,
482 const Vector<const RenderObject*>& pluginZstack)
484 for (size_t i1 = 0, i2 = 0;
485 i1 < iframeZstack.size() && i2 < pluginZstack.size();
487 // The root is at the end of these stacks. We want to iterate
488 // root-downwards so we index backwards from the end.
489 const RenderObject* ro1 = iframeZstack[iframeZstack.size() - 1 - i1];
490 const RenderObject* ro2 = pluginZstack[pluginZstack.size() - 1 - i2];
493 // When we find nodes in the stack that are not the same, then
494 // we've found the nodes just below the lowest comment ancestor.
495 // Determine which should be on top.
497 // See if z-index determines an order.
498 if (ro1->style() && ro2->style()) {
499 int z1 = ro1->style()->zIndex();
500 int z2 = ro2->style()->zIndex();
507 // For compatibility with IE: when the plugin is not positioned,
508 // it stacks behind the iframe, even if it's later in the
510 if (ro2->style()->position() == StaticPosition)
513 // Inspect the document order. Later order means higher
515 const RenderObject* parent = ro1->parent();
518 ASSERT(parent == ro2->parent());
520 for (const RenderObject* ro = parent->firstChild(); ro; ro = ro->nextSibling()) {
526 ASSERT(false); // We should have seen ro1 and ro2 by now.
533 // Return a set of rectangles that should not be overdrawn by the
534 // plugin ("cutouts"). This helps implement the "iframe shim"
535 // technique of overlaying a windowed plugin with content from the
536 // page. In a nutshell, iframe elements should occlude plugins when
537 // they occur higher in the stacking order.
538 void WebPluginContainerImpl::windowCutOutRects(const IntRect& frameRect,
539 Vector<IntRect>& cutOutRects)
541 RenderObject* pluginNode = m_element->renderer();
543 if (!pluginNode->style())
545 Vector<const RenderObject*> pluginZstack;
546 Vector<const RenderObject*> iframeZstack;
547 getObjectStack(pluginNode, &pluginZstack);
549 // Get the parent widget
550 Widget* parentWidget = this->parent();
551 if (!parentWidget->isFrameView())
554 FrameView* parentFrameView = static_cast<FrameView*>(parentWidget);
556 const HashSet<RefPtr<Widget> >* children = parentFrameView->children();
557 for (HashSet<RefPtr<Widget> >::const_iterator it = children->begin(); it != children->end(); ++it) {
558 // We only care about FrameView's because iframes show up as FrameViews.
559 if (!(*it)->isFrameView())
562 const FrameView* frameView =
563 static_cast<const FrameView*>((*it).get());
564 // Check to make sure we can get both the element and the RenderObject
565 // for this FrameView, if we can't just move on to the next object.
566 if (!frameView->frame() || !frameView->frame()->ownerElement()
567 || !frameView->frame()->ownerElement()->renderer())
570 HTMLElement* element = frameView->frame()->ownerElement();
571 RenderObject* iframeRenderer = element->renderer();
573 if (element->hasTagName(HTMLNames::iframeTag)
574 && iframeRenderer->absoluteBoundingBoxRect().intersects(frameRect)
575 && (!iframeRenderer->style() || iframeRenderer->style()->visibility() == VISIBLE)) {
576 getObjectStack(iframeRenderer, &iframeZstack);
577 if (checkStackOnTop(iframeZstack, pluginZstack)) {
579 roundedIntPoint(iframeRenderer->localToAbsolute());
580 RenderBox* rbox = toRenderBox(iframeRenderer);
581 IntSize size(rbox->width(), rbox->height());
582 cutOutRects.append(IntRect(point, size));
588 } // namespace WebKit