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 "WebClipboard.h"
37 #include "WebCursorInfo.h"
38 #include "WebDataSourceImpl.h"
39 #include "WebElement.h"
40 #include "WebInputEvent.h"
41 #include "WebInputEventConversion.h"
43 #include "WebKitClient.h"
44 #include "WebPlugin.h"
46 #include "WebString.h"
48 #include "WebURLError.h"
49 #include "WebURLRequest.h"
50 #include "WebVector.h"
51 #include "WrappedResourceResponse.h"
53 #include "EventNames.h"
54 #include "FocusController.h"
55 #include "FormState.h"
57 #include "FrameLoadRequest.h"
58 #include "FrameView.h"
59 #include "GraphicsContext.h"
60 #include "HostWindow.h"
61 #include "HTMLFormElement.h"
62 #include "HTMLNames.h"
63 #include "HTMLPlugInElement.h"
64 #include "KeyboardCodes.h"
65 #include "KeyboardEvent.h"
66 #include "MouseEvent.h"
68 #include "RenderBox.h"
69 #include "ScrollView.h"
70 #include "WheelEvent.h"
73 #include "PlatformContextSkia.h"
76 using namespace WebCore;
80 // Public methods --------------------------------------------------------------
82 void WebPluginContainerImpl::setFrameRect(const IntRect& frameRect)
84 Widget::setFrameRect(frameRect);
88 void WebPluginContainerImpl::paint(GraphicsContext* gc, const IntRect& damageRect)
90 if (gc->paintingDisabled())
96 // Don't paint anything if the plugin doesn't intersect the damage rect.
97 if (!frameRect().intersects(damageRect))
102 ASSERT(parent()->isFrameView());
103 ScrollView* view = parent();
105 // The plugin is positioned in window coordinates, so it needs to be painted
106 // in window coordinates.
107 IntPoint origin = view->windowToContents(IntPoint(0, 0));
108 gc->translate(static_cast<float>(origin.x()), static_cast<float>(origin.y()));
110 #if WEBKIT_USING_SKIA
111 WebCanvas* canvas = gc->platformContext()->canvas();
112 #elif WEBKIT_USING_CG
113 WebCanvas* canvas = gc->platformContext();
117 IntRect(view->contentsToWindow(damageRect.location()), damageRect.size());
118 m_webPlugin->paint(canvas, windowRect);
123 void WebPluginContainerImpl::invalidateRect(const IntRect& rect)
128 IntRect damageRect = convertToContainingWindow(rect);
130 // Get our clip rect and intersect with it to ensure we don't invalidate
132 IntRect clipRect = parent()->windowClipRect();
133 damageRect.intersect(clipRect);
135 parent()->hostWindow()->invalidateContentsAndWindow(damageRect, false /*immediate*/);
138 void WebPluginContainerImpl::setFocus(bool focused)
140 Widget::setFocus(focused);
141 m_webPlugin->updateFocus(focused);
144 void WebPluginContainerImpl::show()
146 setSelfVisible(true);
147 m_webPlugin->updateVisibility(true);
152 void WebPluginContainerImpl::hide()
154 setSelfVisible(false);
155 m_webPlugin->updateVisibility(false);
160 void WebPluginContainerImpl::handleEvent(Event* event)
162 if (!m_webPlugin->acceptsInputEvents())
165 // The events we pass are defined at:
166 // http://devedge-temp.mozilla.org/library/manuals/2002/plugin/1.0/structures5.html#1000000
167 // Don't take the documentation as truth, however. There are many cases
168 // where mozilla behaves differently than the spec.
169 if (event->isMouseEvent())
170 handleMouseEvent(static_cast<MouseEvent*>(event));
171 else if (event->isWheelEvent())
172 handleWheelEvent(static_cast<WheelEvent*>(event));
173 else if (event->isKeyboardEvent())
174 handleKeyboardEvent(static_cast<KeyboardEvent*>(event));
176 // FIXME: it would be cleaner if Widget::handleEvent returned true/false and
177 // HTMLPluginElement called setDefaultHandled or defaultEventHandler.
178 if (!event->defaultHandled())
179 m_element->Node::defaultEventHandler(event);
182 void WebPluginContainerImpl::frameRectsChanged()
184 Widget::frameRectsChanged();
188 void WebPluginContainerImpl::widgetPositionsUpdated()
190 Widget::widgetPositionsUpdated();
194 void WebPluginContainerImpl::setParentVisible(bool parentVisible)
196 // We override this function to make sure that geometry updates are sent
197 // over to the plugin. For e.g. when a plugin is instantiated it does not
198 // have a valid parent. As a result the first geometry update from webkit
199 // is ignored. This function is called when the plugin eventually gets a
202 if (isParentVisible() == parentVisible)
203 return; // No change.
205 Widget::setParentVisible(parentVisible);
206 if (!isSelfVisible())
207 return; // This widget has explicitely been marked as not visible.
209 m_webPlugin->updateVisibility(isVisible());
212 void WebPluginContainerImpl::setParent(ScrollView* view)
214 // We override this function so that if the plugin is windowed, we can call
215 // NPP_SetWindow at the first possible moment. This ensures that
216 // NPP_SetWindow is called before the manual load data is sent to a plugin.
217 // If this order is reversed, Flash won't load videos.
219 Widget::setParent(view);
224 bool WebPluginContainerImpl::supportsPaginatedPrint() const
226 return m_webPlugin->supportsPaginatedPrint();
229 int WebPluginContainerImpl::printBegin(const IntRect& printableArea,
230 int printerDPI) const
232 return m_webPlugin->printBegin(printableArea, printerDPI);
235 bool WebPluginContainerImpl::printPage(int pageNumber,
236 WebCore::GraphicsContext* gc)
239 #if WEBKIT_USING_SKIA
240 WebCanvas* canvas = gc->platformContext()->canvas();
241 #elif WEBKIT_USING_CG
242 WebCanvas* canvas = gc->platformContext();
244 bool ret = m_webPlugin->printPage(pageNumber, canvas);
249 void WebPluginContainerImpl::printEnd()
251 return m_webPlugin->printEnd();
254 void WebPluginContainerImpl::copy()
256 if (!plugin()->hasSelection())
259 webKitClient()->clipboard()->writeHTML(plugin()->selectionAsMarkup(), WebURL(), plugin()->selectionAsText(), false);
262 WebElement WebPluginContainerImpl::element()
264 return WebElement(m_element);
267 void WebPluginContainerImpl::invalidate()
269 Widget::invalidate();
272 void WebPluginContainerImpl::invalidateRect(const WebRect& rect)
274 invalidateRect(static_cast<IntRect>(rect));
277 void WebPluginContainerImpl::reportGeometry()
282 IntRect windowRect, clipRect;
283 Vector<IntRect> cutOutRects;
284 calculateGeometry(frameRect(), windowRect, clipRect, cutOutRects);
286 m_webPlugin->updateGeometry(windowRect, clipRect, cutOutRects, isVisible());
289 void WebPluginContainerImpl::clearScriptObjects()
291 Frame* frame = m_element->document()->frame();
294 frame->script()->cleanupScriptObjectsForPlugin(this);
297 NPObject* WebPluginContainerImpl::scriptableObjectForElement()
299 return m_element->getNPObject();
302 WebString WebPluginContainerImpl::executeScriptURL(const WebURL& url, bool popupsAllowed)
304 Frame* frame = m_element->document()->frame();
308 const KURL& kurl = url;
309 ASSERT(kurl.protocolIs("javascript"));
311 String script = decodeURLEscapeSequences(
312 kurl.string().substring(strlen("javascript:")));
314 ScriptValue result = frame->script()->executeScript(script, popupsAllowed);
316 // Failure is reported as a null string.
318 result.getString(resultStr);
322 void WebPluginContainerImpl::loadFrameRequest(
323 const WebURLRequest& request, const WebString& target, bool notifyNeeded, void* notifyData)
325 Frame* frame = m_element->document()->frame();
327 return; // FIXME: send a notification in this case?
330 // FIXME: This is a bit of hack to allow us to observe completion of
331 // our frame request. It would be better to evolve FrameLoader to
332 // support a completion callback instead.
333 WebPluginLoadObserver* observer =
334 new WebPluginLoadObserver(this, request.url(), notifyData);
335 m_pluginLoadObservers.append(observer);
336 WebDataSourceImpl::setNextPluginLoadObserver(observer);
339 FrameLoadRequest frameRequest(request.toResourceRequest());
340 frameRequest.setFrameName(target);
342 frame->loader()->loadFrameRequest(
344 false, // lock history
345 false, // lock back forward list
351 void WebPluginContainerImpl::didReceiveResponse(const ResourceResponse& response)
353 // Make sure that the plugin receives window geometry before data, or else
354 // plugins misbehave.
357 WrappedResourceResponse urlResponse(response);
358 m_webPlugin->didReceiveResponse(urlResponse);
361 void WebPluginContainerImpl::didReceiveData(const char *data, int dataLength)
363 m_webPlugin->didReceiveData(data, dataLength);
366 void WebPluginContainerImpl::didFinishLoading()
368 m_webPlugin->didFinishLoading();
371 void WebPluginContainerImpl::didFailLoading(const ResourceError& error)
373 m_webPlugin->didFailLoading(error);
376 NPObject* WebPluginContainerImpl::scriptableObject()
378 return m_webPlugin->scriptableObject();
381 void WebPluginContainerImpl::willDestroyPluginLoadObserver(WebPluginLoadObserver* observer)
383 size_t pos = m_pluginLoadObservers.find(observer);
386 m_pluginLoadObservers.remove(pos);
389 // Private methods -------------------------------------------------------------
391 WebPluginContainerImpl::~WebPluginContainerImpl()
393 for (size_t i = 0; i < m_pluginLoadObservers.size(); ++i)
394 m_pluginLoadObservers[i]->clearPluginContainer();
395 m_webPlugin->destroy();
398 void WebPluginContainerImpl::handleMouseEvent(MouseEvent* event)
400 ASSERT(parent()->isFrameView());
402 // We cache the parent FrameView here as the plugin widget could be deleted
403 // in the call to HandleEvent. See http://b/issue?id=1362948
404 FrameView* parentView = static_cast<FrameView*>(parent());
406 WebMouseEventBuilder webEvent(this, *event);
407 if (webEvent.type == WebInputEvent::Undefined)
410 if (event->type() == eventNames().mousedownEvent) {
411 // Ensure that the frame containing the plugin has focus.
412 Frame* containingFrame = parentView->frame();
413 if (Page* currentPage = containingFrame->page())
414 currentPage->focusController()->setFocusedFrame(containingFrame);
415 // Give focus to our containing HTMLPluginElement.
416 containingFrame->document()->setFocusedNode(m_element);
419 WebCursorInfo cursorInfo;
420 if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
421 event->setDefaultHandled();
423 // A windowless plugin can change the cursor in response to a mouse move
424 // event. We need to reflect the changed cursor in the frame view as the
425 // mouse is moved in the boundaries of the windowless plugin.
426 Page* page = parentView->frame()->page();
429 ChromeClientImpl* chromeClient =
430 static_cast<ChromeClientImpl*>(page->chrome()->client());
431 chromeClient->setCursorForPlugin(cursorInfo);
434 void WebPluginContainerImpl::handleWheelEvent(WheelEvent* event)
436 WebMouseWheelEventBuilder webEvent(this, *event);
437 if (webEvent.type == WebInputEvent::Undefined)
440 WebCursorInfo cursorInfo;
441 if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
442 event->setDefaultHandled();
445 void WebPluginContainerImpl::handleKeyboardEvent(KeyboardEvent* event)
447 WebKeyboardEventBuilder webEvent(*event);
448 if (webEvent.type == WebInputEvent::Undefined)
451 if (webEvent.type == WebInputEvent::KeyDown) {
452 #if defined(OS_MACOSX)
453 if (webEvent.modifiers == WebInputEvent::MetaKey
455 if (webEvent.modifiers == WebInputEvent::ControlKey
457 && webEvent.windowsKeyCode == VKEY_C) {
459 event->setDefaultHandled();
464 WebCursorInfo cursorInfo;
465 if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
466 event->setDefaultHandled();
469 void WebPluginContainerImpl::calculateGeometry(const IntRect& frameRect,
472 Vector<IntRect>& cutOutRects)
474 windowRect = IntRect(
475 parent()->contentsToWindow(frameRect.location()), frameRect.size());
477 // Calculate a clip-rect so that we don't overlap the scrollbars, etc.
478 clipRect = windowClipRect();
479 clipRect.move(-windowRect.x(), -windowRect.y());
481 windowCutOutRects(frameRect, cutOutRects);
482 // Convert to the plugin position.
483 for (size_t i = 0; i < cutOutRects.size(); i++)
484 cutOutRects[i].move(-frameRect.x(), -frameRect.y());
487 WebCore::IntRect WebPluginContainerImpl::windowClipRect() const
489 // Start by clipping to our bounds.
491 convertToContainingWindow(IntRect(0, 0, width(), height()));
493 // document()->renderer() can be 0 when we receive messages from the
494 // plugins while we are destroying a frame.
495 if (m_element->renderer()->document()->renderer()) {
496 // Take our element and get the clip rect from the enclosing layer and
498 RenderLayer* layer = m_element->renderer()->enclosingLayer();
500 m_element->document()->view()->windowClipRectForLayer(layer, true));
506 static void getObjectStack(const RenderObject* ro,
507 Vector<const RenderObject*>* roStack)
516 // Returns true if stack1 is at or above stack2
517 static bool checkStackOnTop(
518 const Vector<const RenderObject*>& iframeZstack,
519 const Vector<const RenderObject*>& pluginZstack)
521 for (size_t i1 = 0, i2 = 0;
522 i1 < iframeZstack.size() && i2 < pluginZstack.size();
524 // The root is at the end of these stacks. We want to iterate
525 // root-downwards so we index backwards from the end.
526 const RenderObject* ro1 = iframeZstack[iframeZstack.size() - 1 - i1];
527 const RenderObject* ro2 = pluginZstack[pluginZstack.size() - 1 - i2];
530 // When we find nodes in the stack that are not the same, then
531 // we've found the nodes just below the lowest comment ancestor.
532 // Determine which should be on top.
534 // See if z-index determines an order.
535 if (ro1->style() && ro2->style()) {
536 int z1 = ro1->style()->zIndex();
537 int z2 = ro2->style()->zIndex();
544 // For compatibility with IE: when the plugin is not positioned,
545 // it stacks behind the iframe, even if it's later in the
547 if (ro2->style()->position() == StaticPosition)
550 // Inspect the document order. Later order means higher
552 const RenderObject* parent = ro1->parent();
555 ASSERT(parent == ro2->parent());
557 for (const RenderObject* ro = parent->firstChild(); ro; ro = ro->nextSibling()) {
563 ASSERT(false); // We should have seen ro1 and ro2 by now.
570 // Return a set of rectangles that should not be overdrawn by the
571 // plugin ("cutouts"). This helps implement the "iframe shim"
572 // technique of overlaying a windowed plugin with content from the
573 // page. In a nutshell, iframe elements should occlude plugins when
574 // they occur higher in the stacking order.
575 void WebPluginContainerImpl::windowCutOutRects(const IntRect& frameRect,
576 Vector<IntRect>& cutOutRects)
578 RenderObject* pluginNode = m_element->renderer();
580 if (!pluginNode->style())
582 Vector<const RenderObject*> pluginZstack;
583 Vector<const RenderObject*> iframeZstack;
584 getObjectStack(pluginNode, &pluginZstack);
586 // Get the parent widget
587 Widget* parentWidget = this->parent();
588 if (!parentWidget->isFrameView())
591 FrameView* parentFrameView = static_cast<FrameView*>(parentWidget);
593 const HashSet<RefPtr<Widget> >* children = parentFrameView->children();
594 for (HashSet<RefPtr<Widget> >::const_iterator it = children->begin(); it != children->end(); ++it) {
595 // We only care about FrameView's because iframes show up as FrameViews.
596 if (!(*it)->isFrameView())
599 const FrameView* frameView =
600 static_cast<const FrameView*>((*it).get());
601 // Check to make sure we can get both the element and the RenderObject
602 // for this FrameView, if we can't just move on to the next object.
603 if (!frameView->frame() || !frameView->frame()->ownerElement()
604 || !frameView->frame()->ownerElement()->renderer())
607 HTMLElement* element = frameView->frame()->ownerElement();
608 RenderObject* iframeRenderer = element->renderer();
610 if (element->hasTagName(HTMLNames::iframeTag)
611 && iframeRenderer->absoluteBoundingBoxRect().intersects(frameRect)
612 && (!iframeRenderer->style() || iframeRenderer->style()->visibility() == VISIBLE)) {
613 getObjectStack(iframeRenderer, &iframeZstack);
614 if (checkStackOnTop(iframeZstack, pluginZstack)) {
616 roundedIntPoint(iframeRenderer->localToAbsolute());
617 RenderBox* rbox = toRenderBox(iframeRenderer);
618 IntSize size(rbox->width(), rbox->height());
619 cutOutRects.append(IntRect(point, size));
625 } // namespace WebKit