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 "WebElement.h"
39 #include "WebInputEvent.h"
40 #include "WebInputEventConversion.h"
42 #include "WebPlugin.h"
44 #include "WebURLError.h"
45 #include "WebURLRequest.h"
46 #include "WebVector.h"
47 #include "WrappedResourceResponse.h"
49 #include "EventNames.h"
50 #include "FocusController.h"
51 #include "FormState.h"
53 #include "FrameLoadRequest.h"
54 #include "FrameView.h"
55 #include "GraphicsContext.h"
56 #include "HostWindow.h"
57 #include "HTMLFormElement.h"
58 #include "HTMLNames.h"
59 #include "HTMLPlugInElement.h"
60 #include "KeyboardEvent.h"
61 #include "MouseEvent.h"
63 #include "RenderBox.h"
64 #include "ScrollView.h"
65 #include "WheelEvent.h"
68 #include "PlatformContextSkia.h"
71 using namespace WebCore;
75 // Public methods --------------------------------------------------------------
77 void WebPluginContainerImpl::setFrameRect(const IntRect& frameRect)
79 Widget::setFrameRect(frameRect);
83 void WebPluginContainerImpl::paint(GraphicsContext* gc, const IntRect& damageRect)
85 if (gc->paintingDisabled())
91 // Don't paint anything if the plugin doesn't intersect the damage rect.
92 if (!frameRect().intersects(damageRect))
97 ASSERT(parent()->isFrameView());
98 ScrollView* view = parent();
100 // The plugin is positioned in window coordinates, so it needs to be painted
101 // in window coordinates.
102 IntPoint origin = view->windowToContents(IntPoint(0, 0));
103 gc->translate(static_cast<float>(origin.x()), static_cast<float>(origin.y()));
105 #if WEBKIT_USING_SKIA
106 WebCanvas* canvas = gc->platformContext()->canvas();
107 #elif WEBKIT_USING_CG
108 WebCanvas* canvas = gc->platformContext();
112 IntRect(view->contentsToWindow(damageRect.location()), damageRect.size());
113 m_webPlugin->paint(canvas, windowRect);
118 void WebPluginContainerImpl::invalidateRect(const IntRect& rect)
123 IntRect damageRect = convertToContainingWindow(rect);
125 // Get our clip rect and intersect with it to ensure we don't invalidate
127 IntRect clipRect = parent()->windowClipRect();
128 damageRect.intersect(clipRect);
130 parent()->hostWindow()->invalidateContentsAndWindow(damageRect, false /*immediate*/);
133 void WebPluginContainerImpl::setFocus(bool focused)
135 Widget::setFocus(focused);
136 m_webPlugin->updateFocus(focused);
139 void WebPluginContainerImpl::show()
141 setSelfVisible(true);
142 m_webPlugin->updateVisibility(true);
147 void WebPluginContainerImpl::hide()
149 setSelfVisible(false);
150 m_webPlugin->updateVisibility(false);
155 void WebPluginContainerImpl::handleEvent(Event* event)
157 if (!m_webPlugin->acceptsInputEvents())
160 // The events we pass are defined at:
161 // http://devedge-temp.mozilla.org/library/manuals/2002/plugin/1.0/structures5.html#1000000
162 // Don't take the documentation as truth, however. There are many cases
163 // where mozilla behaves differently than the spec.
164 if (event->isMouseEvent())
165 handleMouseEvent(static_cast<MouseEvent*>(event));
166 else if (event->isWheelEvent())
167 handleWheelEvent(static_cast<WheelEvent*>(event));
168 else if (event->isKeyboardEvent())
169 handleKeyboardEvent(static_cast<KeyboardEvent*>(event));
172 void WebPluginContainerImpl::frameRectsChanged()
174 Widget::frameRectsChanged();
178 void WebPluginContainerImpl::widgetPositionsUpdated()
180 Widget::widgetPositionsUpdated();
184 void WebPluginContainerImpl::setParentVisible(bool parentVisible)
186 // We override this function to make sure that geometry updates are sent
187 // over to the plugin. For e.g. when a plugin is instantiated it does not
188 // have a valid parent. As a result the first geometry update from webkit
189 // is ignored. This function is called when the plugin eventually gets a
192 if (isParentVisible() == parentVisible)
193 return; // No change.
195 Widget::setParentVisible(parentVisible);
196 if (!isSelfVisible())
197 return; // This widget has explicitely been marked as not visible.
199 m_webPlugin->updateVisibility(isVisible());
202 void WebPluginContainerImpl::setParent(ScrollView* view)
204 // We override this function so that if the plugin is windowed, we can call
205 // NPP_SetWindow at the first possible moment. This ensures that
206 // NPP_SetWindow is called before the manual load data is sent to a plugin.
207 // If this order is reversed, Flash won't load videos.
209 Widget::setParent(view);
214 bool WebPluginContainerImpl::supportsPaginatedPrint() const
216 return m_webPlugin->supportsPaginatedPrint();
219 int WebPluginContainerImpl::printBegin(const IntRect& printableArea,
220 int printerDPI) const
222 return m_webPlugin->printBegin(printableArea, printerDPI);
225 bool WebPluginContainerImpl::printPage(int pageNumber,
226 WebCore::GraphicsContext* gc)
229 #if WEBKIT_USING_SKIA
230 WebCanvas* canvas = gc->platformContext()->canvas();
231 #elif WEBKIT_USING_CG
232 WebCanvas* canvas = gc->platformContext();
234 bool ret = m_webPlugin->printPage(pageNumber, canvas);
239 void WebPluginContainerImpl::printEnd()
241 return m_webPlugin->printEnd();
244 WebElement WebPluginContainerImpl::element()
246 return WebElement(m_element);
249 void WebPluginContainerImpl::invalidate()
251 Widget::invalidate();
254 void WebPluginContainerImpl::invalidateRect(const WebRect& rect)
256 invalidateRect(static_cast<IntRect>(rect));
259 void WebPluginContainerImpl::reportGeometry()
264 IntRect windowRect, clipRect;
265 Vector<IntRect> cutOutRects;
266 calculateGeometry(frameRect(), windowRect, clipRect, cutOutRects);
268 m_webPlugin->updateGeometry(windowRect, clipRect, cutOutRects, isVisible());
271 void WebPluginContainerImpl::clearScriptObjects()
273 Frame* frame = m_element->document()->frame();
276 frame->script()->cleanupScriptObjectsForPlugin(this);
279 NPObject* WebPluginContainerImpl::scriptableObjectForElement()
281 return m_element->getNPObject();
284 WebString WebPluginContainerImpl::executeScriptURL(const WebURL& url, bool popupsAllowed)
286 Frame* frame = m_element->document()->frame();
290 const KURL& kurl = url;
291 ASSERT(kurl.protocolIs("javascript"));
293 String script = decodeURLEscapeSequences(
294 kurl.string().substring(strlen("javascript:")));
296 ScriptValue result = frame->script()->executeScript(script, popupsAllowed);
298 // Failure is reported as a null string.
300 result.getString(resultStr);
304 void WebPluginContainerImpl::loadFrameRequest(
305 const WebURLRequest& request, const WebString& target, bool notifyNeeded, void* notifyData)
307 Frame* frame = m_element->document()->frame();
309 return; // FIXME: send a notification in this case?
312 // FIXME: This is a bit of hack to allow us to observe completion of
313 // our frame request. It would be better to evolve FrameLoader to
314 // support a completion callback instead.
315 WebPluginLoadObserver* observer =
316 new WebPluginLoadObserver(this, request.url(), notifyData);
317 m_pluginLoadObservers.append(observer);
318 WebDataSourceImpl::setNextPluginLoadObserver(observer);
321 FrameLoadRequest frameRequest(request.toResourceRequest());
322 frameRequest.setFrameName(target);
324 frame->loader()->loadFrameRequest(
326 false, // lock history
327 false, // lock back forward list
333 void WebPluginContainerImpl::didReceiveResponse(const ResourceResponse& response)
335 // Make sure that the plugin receives window geometry before data, or else
336 // plugins misbehave.
339 WrappedResourceResponse urlResponse(response);
340 m_webPlugin->didReceiveResponse(urlResponse);
343 void WebPluginContainerImpl::didReceiveData(const char *data, int dataLength)
345 m_webPlugin->didReceiveData(data, dataLength);
348 void WebPluginContainerImpl::didFinishLoading()
350 m_webPlugin->didFinishLoading();
353 void WebPluginContainerImpl::didFailLoading(const ResourceError& error)
355 m_webPlugin->didFailLoading(error);
358 NPObject* WebPluginContainerImpl::scriptableObject()
360 return m_webPlugin->scriptableObject();
363 void WebPluginContainerImpl::willDestroyPluginLoadObserver(WebPluginLoadObserver* observer)
365 size_t pos = m_pluginLoadObservers.find(observer);
368 m_pluginLoadObservers.remove(pos);
371 // Private methods -------------------------------------------------------------
373 WebPluginContainerImpl::~WebPluginContainerImpl()
375 for (size_t i = 0; i < m_pluginLoadObservers.size(); ++i)
376 m_pluginLoadObservers[i]->clearPluginContainer();
377 m_webPlugin->destroy();
380 void WebPluginContainerImpl::handleMouseEvent(MouseEvent* event)
382 ASSERT(parent()->isFrameView());
384 // We cache the parent FrameView here as the plugin widget could be deleted
385 // in the call to HandleEvent. See http://b/issue?id=1362948
386 FrameView* parentView = static_cast<FrameView*>(parent());
388 WebMouseEventBuilder webEvent(parentView, *event);
389 if (webEvent.type == WebInputEvent::Undefined)
392 if (event->type() == eventNames().mousedownEvent) {
393 // Ensure that the frame containing the plugin has focus.
394 Frame* containingFrame = parentView->frame();
395 if (Page* currentPage = containingFrame->page())
396 currentPage->focusController()->setFocusedFrame(containingFrame);
397 // Give focus to our containing HTMLPluginElement.
398 containingFrame->document()->setFocusedNode(m_element);
401 WebCursorInfo cursorInfo;
402 if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
403 event->setDefaultHandled();
405 // A windowless plugin can change the cursor in response to a mouse move
406 // event. We need to reflect the changed cursor in the frame view as the
407 // mouse is moved in the boundaries of the windowless plugin.
408 Page* page = parentView->frame()->page();
411 ChromeClientImpl* chromeClient =
412 static_cast<ChromeClientImpl*>(page->chrome()->client());
413 chromeClient->setCursorForPlugin(cursorInfo);
416 void WebPluginContainerImpl::handleWheelEvent(WheelEvent* event)
418 FrameView* parentView = static_cast<FrameView*>(parent());
419 WebMouseWheelEventBuilder webEvent(parentView, *event);
420 if (webEvent.type == WebInputEvent::Undefined)
423 WebCursorInfo cursorInfo;
424 if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
425 event->setDefaultHandled();
428 void WebPluginContainerImpl::handleKeyboardEvent(KeyboardEvent* event)
430 WebKeyboardEventBuilder webEvent(*event);
431 if (webEvent.type == WebInputEvent::Undefined)
434 WebCursorInfo cursorInfo;
435 if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
436 event->setDefaultHandled();
439 void WebPluginContainerImpl::calculateGeometry(const IntRect& frameRect,
442 Vector<IntRect>& cutOutRects)
444 windowRect = IntRect(
445 parent()->contentsToWindow(frameRect.location()), frameRect.size());
447 // Calculate a clip-rect so that we don't overlap the scrollbars, etc.
448 clipRect = windowClipRect();
449 clipRect.move(-windowRect.x(), -windowRect.y());
451 windowCutOutRects(frameRect, cutOutRects);
452 // Convert to the plugin position.
453 for (size_t i = 0; i < cutOutRects.size(); i++)
454 cutOutRects[i].move(-frameRect.x(), -frameRect.y());
457 WebCore::IntRect WebPluginContainerImpl::windowClipRect() const
459 // Start by clipping to our bounds.
461 convertToContainingWindow(IntRect(0, 0, width(), height()));
463 // document()->renderer() can be 0 when we receive messages from the
464 // plugins while we are destroying a frame.
465 if (m_element->renderer()->document()->renderer()) {
466 // Take our element and get the clip rect from the enclosing layer and
468 RenderLayer* layer = m_element->renderer()->enclosingLayer();
470 m_element->document()->view()->windowClipRectForLayer(layer, true));
476 static void getObjectStack(const RenderObject* ro,
477 Vector<const RenderObject*>* roStack)
486 // Returns true if stack1 is at or above stack2
487 static bool checkStackOnTop(
488 const Vector<const RenderObject*>& iframeZstack,
489 const Vector<const RenderObject*>& pluginZstack)
491 for (size_t i1 = 0, i2 = 0;
492 i1 < iframeZstack.size() && i2 < pluginZstack.size();
494 // The root is at the end of these stacks. We want to iterate
495 // root-downwards so we index backwards from the end.
496 const RenderObject* ro1 = iframeZstack[iframeZstack.size() - 1 - i1];
497 const RenderObject* ro2 = pluginZstack[pluginZstack.size() - 1 - i2];
500 // When we find nodes in the stack that are not the same, then
501 // we've found the nodes just below the lowest comment ancestor.
502 // Determine which should be on top.
504 // See if z-index determines an order.
505 if (ro1->style() && ro2->style()) {
506 int z1 = ro1->style()->zIndex();
507 int z2 = ro2->style()->zIndex();
514 // For compatibility with IE: when the plugin is not positioned,
515 // it stacks behind the iframe, even if it's later in the
517 if (ro2->style()->position() == StaticPosition)
520 // Inspect the document order. Later order means higher
522 const RenderObject* parent = ro1->parent();
525 ASSERT(parent == ro2->parent());
527 for (const RenderObject* ro = parent->firstChild(); ro; ro = ro->nextSibling()) {
533 ASSERT(false); // We should have seen ro1 and ro2 by now.
540 // Return a set of rectangles that should not be overdrawn by the
541 // plugin ("cutouts"). This helps implement the "iframe shim"
542 // technique of overlaying a windowed plugin with content from the
543 // page. In a nutshell, iframe elements should occlude plugins when
544 // they occur higher in the stacking order.
545 void WebPluginContainerImpl::windowCutOutRects(const IntRect& frameRect,
546 Vector<IntRect>& cutOutRects)
548 RenderObject* pluginNode = m_element->renderer();
550 if (!pluginNode->style())
552 Vector<const RenderObject*> pluginZstack;
553 Vector<const RenderObject*> iframeZstack;
554 getObjectStack(pluginNode, &pluginZstack);
556 // Get the parent widget
557 Widget* parentWidget = this->parent();
558 if (!parentWidget->isFrameView())
561 FrameView* parentFrameView = static_cast<FrameView*>(parentWidget);
563 const HashSet<RefPtr<Widget> >* children = parentFrameView->children();
564 for (HashSet<RefPtr<Widget> >::const_iterator it = children->begin(); it != children->end(); ++it) {
565 // We only care about FrameView's because iframes show up as FrameViews.
566 if (!(*it)->isFrameView())
569 const FrameView* frameView =
570 static_cast<const FrameView*>((*it).get());
571 // Check to make sure we can get both the element and the RenderObject
572 // for this FrameView, if we can't just move on to the next object.
573 if (!frameView->frame() || !frameView->frame()->ownerElement()
574 || !frameView->frame()->ownerElement()->renderer())
577 HTMLElement* element = frameView->frame()->ownerElement();
578 RenderObject* iframeRenderer = element->renderer();
580 if (element->hasTagName(HTMLNames::iframeTag)
581 && iframeRenderer->absoluteBoundingBoxRect().intersects(frameRect)
582 && (!iframeRenderer->style() || iframeRenderer->style()->visibility() == VISIBLE)) {
583 getObjectStack(iframeRenderer, &iframeZstack);
584 if (checkStackOnTop(iframeZstack, pluginZstack)) {
586 roundedIntPoint(iframeRenderer->localToAbsolute());
587 RenderBox* rbox = toRenderBox(iframeRenderer);
588 IntSize size(rbox->width(), rbox->height());
589 cutOutRects.append(IntRect(point, size));
595 } // namespace WebKit