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));
171 // FIXME: it would be cleaner if Widget::handleEvent returned true/false and
172 // HTMLPluginElement called setDefaultHandled or defaultEventHandler.
173 if (!event->defaultHandled())
174 m_element->Node::defaultEventHandler(event);
177 void WebPluginContainerImpl::frameRectsChanged()
179 Widget::frameRectsChanged();
183 void WebPluginContainerImpl::widgetPositionsUpdated()
185 Widget::widgetPositionsUpdated();
189 void WebPluginContainerImpl::setParentVisible(bool parentVisible)
191 // We override this function to make sure that geometry updates are sent
192 // over to the plugin. For e.g. when a plugin is instantiated it does not
193 // have a valid parent. As a result the first geometry update from webkit
194 // is ignored. This function is called when the plugin eventually gets a
197 if (isParentVisible() == parentVisible)
198 return; // No change.
200 Widget::setParentVisible(parentVisible);
201 if (!isSelfVisible())
202 return; // This widget has explicitely been marked as not visible.
204 m_webPlugin->updateVisibility(isVisible());
207 void WebPluginContainerImpl::setParent(ScrollView* view)
209 // We override this function so that if the plugin is windowed, we can call
210 // NPP_SetWindow at the first possible moment. This ensures that
211 // NPP_SetWindow is called before the manual load data is sent to a plugin.
212 // If this order is reversed, Flash won't load videos.
214 Widget::setParent(view);
219 bool WebPluginContainerImpl::supportsPaginatedPrint() const
221 return m_webPlugin->supportsPaginatedPrint();
224 int WebPluginContainerImpl::printBegin(const IntRect& printableArea,
225 int printerDPI) const
227 return m_webPlugin->printBegin(printableArea, printerDPI);
230 bool WebPluginContainerImpl::printPage(int pageNumber,
231 WebCore::GraphicsContext* gc)
234 #if WEBKIT_USING_SKIA
235 WebCanvas* canvas = gc->platformContext()->canvas();
236 #elif WEBKIT_USING_CG
237 WebCanvas* canvas = gc->platformContext();
239 bool ret = m_webPlugin->printPage(pageNumber, canvas);
244 void WebPluginContainerImpl::printEnd()
246 return m_webPlugin->printEnd();
249 WebString WebPluginContainerImpl::selectedText()
251 return m_webPlugin->selectedText();
254 WebElement WebPluginContainerImpl::element()
256 return WebElement(m_element);
259 void WebPluginContainerImpl::invalidate()
261 Widget::invalidate();
264 void WebPluginContainerImpl::invalidateRect(const WebRect& rect)
266 invalidateRect(static_cast<IntRect>(rect));
269 void WebPluginContainerImpl::reportGeometry()
274 IntRect windowRect, clipRect;
275 Vector<IntRect> cutOutRects;
276 calculateGeometry(frameRect(), windowRect, clipRect, cutOutRects);
278 m_webPlugin->updateGeometry(windowRect, clipRect, cutOutRects, isVisible());
281 void WebPluginContainerImpl::clearScriptObjects()
283 Frame* frame = m_element->document()->frame();
286 frame->script()->cleanupScriptObjectsForPlugin(this);
289 NPObject* WebPluginContainerImpl::scriptableObjectForElement()
291 return m_element->getNPObject();
294 WebString WebPluginContainerImpl::executeScriptURL(const WebURL& url, bool popupsAllowed)
296 Frame* frame = m_element->document()->frame();
300 const KURL& kurl = url;
301 ASSERT(kurl.protocolIs("javascript"));
303 String script = decodeURLEscapeSequences(
304 kurl.string().substring(strlen("javascript:")));
306 ScriptValue result = frame->script()->executeScript(script, popupsAllowed);
308 // Failure is reported as a null string.
310 result.getString(resultStr);
314 void WebPluginContainerImpl::loadFrameRequest(
315 const WebURLRequest& request, const WebString& target, bool notifyNeeded, void* notifyData)
317 Frame* frame = m_element->document()->frame();
319 return; // FIXME: send a notification in this case?
322 // FIXME: This is a bit of hack to allow us to observe completion of
323 // our frame request. It would be better to evolve FrameLoader to
324 // support a completion callback instead.
325 WebPluginLoadObserver* observer =
326 new WebPluginLoadObserver(this, request.url(), notifyData);
327 m_pluginLoadObservers.append(observer);
328 WebDataSourceImpl::setNextPluginLoadObserver(observer);
331 FrameLoadRequest frameRequest(request.toResourceRequest());
332 frameRequest.setFrameName(target);
334 frame->loader()->loadFrameRequest(
336 false, // lock history
337 false, // lock back forward list
343 void WebPluginContainerImpl::didReceiveResponse(const ResourceResponse& response)
345 // Make sure that the plugin receives window geometry before data, or else
346 // plugins misbehave.
349 WrappedResourceResponse urlResponse(response);
350 m_webPlugin->didReceiveResponse(urlResponse);
353 void WebPluginContainerImpl::didReceiveData(const char *data, int dataLength)
355 m_webPlugin->didReceiveData(data, dataLength);
358 void WebPluginContainerImpl::didFinishLoading()
360 m_webPlugin->didFinishLoading();
363 void WebPluginContainerImpl::didFailLoading(const ResourceError& error)
365 m_webPlugin->didFailLoading(error);
368 NPObject* WebPluginContainerImpl::scriptableObject()
370 return m_webPlugin->scriptableObject();
373 void WebPluginContainerImpl::willDestroyPluginLoadObserver(WebPluginLoadObserver* observer)
375 size_t pos = m_pluginLoadObservers.find(observer);
378 m_pluginLoadObservers.remove(pos);
381 // Private methods -------------------------------------------------------------
383 WebPluginContainerImpl::~WebPluginContainerImpl()
385 for (size_t i = 0; i < m_pluginLoadObservers.size(); ++i)
386 m_pluginLoadObservers[i]->clearPluginContainer();
387 m_webPlugin->destroy();
390 void WebPluginContainerImpl::handleMouseEvent(MouseEvent* event)
392 ASSERT(parent()->isFrameView());
394 // We cache the parent FrameView here as the plugin widget could be deleted
395 // in the call to HandleEvent. See http://b/issue?id=1362948
396 FrameView* parentView = static_cast<FrameView*>(parent());
398 WebMouseEventBuilder webEvent(parentView, *event);
399 if (webEvent.type == WebInputEvent::Undefined)
402 if (event->type() == eventNames().mousedownEvent) {
403 // Ensure that the frame containing the plugin has focus.
404 Frame* containingFrame = parentView->frame();
405 if (Page* currentPage = containingFrame->page())
406 currentPage->focusController()->setFocusedFrame(containingFrame);
407 // Give focus to our containing HTMLPluginElement.
408 containingFrame->document()->setFocusedNode(m_element);
411 WebCursorInfo cursorInfo;
412 if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
413 event->setDefaultHandled();
415 // A windowless plugin can change the cursor in response to a mouse move
416 // event. We need to reflect the changed cursor in the frame view as the
417 // mouse is moved in the boundaries of the windowless plugin.
418 Page* page = parentView->frame()->page();
421 ChromeClientImpl* chromeClient =
422 static_cast<ChromeClientImpl*>(page->chrome()->client());
423 chromeClient->setCursorForPlugin(cursorInfo);
426 void WebPluginContainerImpl::handleWheelEvent(WheelEvent* event)
428 FrameView* parentView = static_cast<FrameView*>(parent());
429 WebMouseWheelEventBuilder webEvent(parentView, *event);
430 if (webEvent.type == WebInputEvent::Undefined)
433 WebCursorInfo cursorInfo;
434 if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
435 event->setDefaultHandled();
438 void WebPluginContainerImpl::handleKeyboardEvent(KeyboardEvent* event)
440 WebKeyboardEventBuilder webEvent(*event);
441 if (webEvent.type == WebInputEvent::Undefined)
444 WebCursorInfo cursorInfo;
445 if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
446 event->setDefaultHandled();
449 void WebPluginContainerImpl::calculateGeometry(const IntRect& frameRect,
452 Vector<IntRect>& cutOutRects)
454 windowRect = IntRect(
455 parent()->contentsToWindow(frameRect.location()), frameRect.size());
457 // Calculate a clip-rect so that we don't overlap the scrollbars, etc.
458 clipRect = windowClipRect();
459 clipRect.move(-windowRect.x(), -windowRect.y());
461 windowCutOutRects(frameRect, cutOutRects);
462 // Convert to the plugin position.
463 for (size_t i = 0; i < cutOutRects.size(); i++)
464 cutOutRects[i].move(-frameRect.x(), -frameRect.y());
467 WebCore::IntRect WebPluginContainerImpl::windowClipRect() const
469 // Start by clipping to our bounds.
471 convertToContainingWindow(IntRect(0, 0, width(), height()));
473 // document()->renderer() can be 0 when we receive messages from the
474 // plugins while we are destroying a frame.
475 if (m_element->renderer()->document()->renderer()) {
476 // Take our element and get the clip rect from the enclosing layer and
478 RenderLayer* layer = m_element->renderer()->enclosingLayer();
480 m_element->document()->view()->windowClipRectForLayer(layer, true));
486 static void getObjectStack(const RenderObject* ro,
487 Vector<const RenderObject*>* roStack)
496 // Returns true if stack1 is at or above stack2
497 static bool checkStackOnTop(
498 const Vector<const RenderObject*>& iframeZstack,
499 const Vector<const RenderObject*>& pluginZstack)
501 for (size_t i1 = 0, i2 = 0;
502 i1 < iframeZstack.size() && i2 < pluginZstack.size();
504 // The root is at the end of these stacks. We want to iterate
505 // root-downwards so we index backwards from the end.
506 const RenderObject* ro1 = iframeZstack[iframeZstack.size() - 1 - i1];
507 const RenderObject* ro2 = pluginZstack[pluginZstack.size() - 1 - i2];
510 // When we find nodes in the stack that are not the same, then
511 // we've found the nodes just below the lowest comment ancestor.
512 // Determine which should be on top.
514 // See if z-index determines an order.
515 if (ro1->style() && ro2->style()) {
516 int z1 = ro1->style()->zIndex();
517 int z2 = ro2->style()->zIndex();
524 // For compatibility with IE: when the plugin is not positioned,
525 // it stacks behind the iframe, even if it's later in the
527 if (ro2->style()->position() == StaticPosition)
530 // Inspect the document order. Later order means higher
532 const RenderObject* parent = ro1->parent();
535 ASSERT(parent == ro2->parent());
537 for (const RenderObject* ro = parent->firstChild(); ro; ro = ro->nextSibling()) {
543 ASSERT(false); // We should have seen ro1 and ro2 by now.
550 // Return a set of rectangles that should not be overdrawn by the
551 // plugin ("cutouts"). This helps implement the "iframe shim"
552 // technique of overlaying a windowed plugin with content from the
553 // page. In a nutshell, iframe elements should occlude plugins when
554 // they occur higher in the stacking order.
555 void WebPluginContainerImpl::windowCutOutRects(const IntRect& frameRect,
556 Vector<IntRect>& cutOutRects)
558 RenderObject* pluginNode = m_element->renderer();
560 if (!pluginNode->style())
562 Vector<const RenderObject*> pluginZstack;
563 Vector<const RenderObject*> iframeZstack;
564 getObjectStack(pluginNode, &pluginZstack);
566 // Get the parent widget
567 Widget* parentWidget = this->parent();
568 if (!parentWidget->isFrameView())
571 FrameView* parentFrameView = static_cast<FrameView*>(parentWidget);
573 const HashSet<RefPtr<Widget> >* children = parentFrameView->children();
574 for (HashSet<RefPtr<Widget> >::const_iterator it = children->begin(); it != children->end(); ++it) {
575 // We only care about FrameView's because iframes show up as FrameViews.
576 if (!(*it)->isFrameView())
579 const FrameView* frameView =
580 static_cast<const FrameView*>((*it).get());
581 // Check to make sure we can get both the element and the RenderObject
582 // for this FrameView, if we can't just move on to the next object.
583 if (!frameView->frame() || !frameView->frame()->ownerElement()
584 || !frameView->frame()->ownerElement()->renderer())
587 HTMLElement* element = frameView->frame()->ownerElement();
588 RenderObject* iframeRenderer = element->renderer();
590 if (element->hasTagName(HTMLNames::iframeTag)
591 && iframeRenderer->absoluteBoundingBoxRect().intersects(frameRect)
592 && (!iframeRenderer->style() || iframeRenderer->style()->visibility() == VISIBLE)) {
593 getObjectStack(iframeRenderer, &iframeZstack);
594 if (checkStackOnTop(iframeZstack, pluginZstack)) {
596 roundedIntPoint(iframeRenderer->localToAbsolute());
597 RenderBox* rbox = toRenderBox(iframeRenderer);
598 IntSize size(rbox->width(), rbox->height());
599 cutOutRects.append(IntRect(point, size));
605 } // namespace WebKit