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 "PluginLayerChromium.h"
37 #include "WebClipboard.h"
38 #include "WebCursorInfo.h"
39 #include "WebDataSourceImpl.h"
40 #include "WebElement.h"
41 #include "WebInputEvent.h"
42 #include "WebInputEventConversion.h"
44 #include "WebKitClient.h"
45 #include "WebPlugin.h"
47 #include "WebString.h"
49 #include "WebURLError.h"
50 #include "WebURLRequest.h"
51 #include "WebVector.h"
52 #include "WebViewImpl.h"
53 #include "WrappedResourceResponse.h"
55 #include "EventNames.h"
56 #include "FocusController.h"
57 #include "FormState.h"
59 #include "FrameLoadRequest.h"
60 #include "FrameView.h"
61 #include "GraphicsContext.h"
62 #include "HostWindow.h"
63 #include "HTMLFormElement.h"
64 #include "HTMLNames.h"
65 #include "HTMLPlugInElement.h"
66 #include "KeyboardCodes.h"
67 #include "KeyboardEvent.h"
68 #include "MouseEvent.h"
70 #include "RenderBox.h"
71 #include "ScrollView.h"
72 #include "WheelEvent.h"
75 #include "PlatformContextSkia.h"
78 using namespace WebCore;
82 // Public methods --------------------------------------------------------------
84 void WebPluginContainerImpl::setFrameRect(const IntRect& frameRect)
86 Widget::setFrameRect(frameRect);
90 void WebPluginContainerImpl::paint(GraphicsContext* gc, const IntRect& damageRect)
92 if (gc->paintingDisabled())
98 // Don't paint anything if the plugin doesn't intersect the damage rect.
99 if (!frameRect().intersects(damageRect))
104 ASSERT(parent()->isFrameView());
105 ScrollView* view = parent();
107 // The plugin is positioned in window coordinates, so it needs to be painted
108 // in window coordinates.
109 IntPoint origin = view->windowToContents(IntPoint(0, 0));
110 gc->translate(static_cast<float>(origin.x()), static_cast<float>(origin.y()));
112 #if WEBKIT_USING_SKIA
113 WebCanvas* canvas = gc->platformContext()->canvas();
114 #elif WEBKIT_USING_CG
115 WebCanvas* canvas = gc->platformContext();
119 IntRect(view->contentsToWindow(damageRect.location()), damageRect.size());
120 m_webPlugin->paint(canvas, windowRect);
125 void WebPluginContainerImpl::invalidateRect(const IntRect& rect)
130 IntRect damageRect = convertToContainingWindow(rect);
132 // Get our clip rect and intersect with it to ensure we don't invalidate
134 IntRect clipRect = parent()->windowClipRect();
135 damageRect.intersect(clipRect);
137 parent()->hostWindow()->invalidateContentsAndWindow(damageRect, false /*immediate*/);
140 void WebPluginContainerImpl::setFocus(bool focused)
142 Widget::setFocus(focused);
143 m_webPlugin->updateFocus(focused);
146 void WebPluginContainerImpl::show()
148 setSelfVisible(true);
149 m_webPlugin->updateVisibility(true);
154 void WebPluginContainerImpl::hide()
156 setSelfVisible(false);
157 m_webPlugin->updateVisibility(false);
162 void WebPluginContainerImpl::handleEvent(Event* event)
164 if (!m_webPlugin->acceptsInputEvents())
167 // The events we pass are defined at:
168 // http://devedge-temp.mozilla.org/library/manuals/2002/plugin/1.0/structures5.html#1000000
169 // Don't take the documentation as truth, however. There are many cases
170 // where mozilla behaves differently than the spec.
171 if (event->isMouseEvent())
172 handleMouseEvent(static_cast<MouseEvent*>(event));
173 else if (event->isWheelEvent())
174 handleWheelEvent(static_cast<WheelEvent*>(event));
175 else if (event->isKeyboardEvent())
176 handleKeyboardEvent(static_cast<KeyboardEvent*>(event));
178 // FIXME: it would be cleaner if Widget::handleEvent returned true/false and
179 // HTMLPluginElement called setDefaultHandled or defaultEventHandler.
180 if (!event->defaultHandled())
181 m_element->Node::defaultEventHandler(event);
184 void WebPluginContainerImpl::frameRectsChanged()
186 Widget::frameRectsChanged();
190 void WebPluginContainerImpl::widgetPositionsUpdated()
192 Widget::widgetPositionsUpdated();
196 void WebPluginContainerImpl::setParentVisible(bool parentVisible)
198 // We override this function to make sure that geometry updates are sent
199 // over to the plugin. For e.g. when a plugin is instantiated it does not
200 // have a valid parent. As a result the first geometry update from webkit
201 // is ignored. This function is called when the plugin eventually gets a
204 if (isParentVisible() == parentVisible)
205 return; // No change.
207 Widget::setParentVisible(parentVisible);
208 if (!isSelfVisible())
209 return; // This widget has explicitely been marked as not visible.
211 m_webPlugin->updateVisibility(isVisible());
214 void WebPluginContainerImpl::setParent(ScrollView* view)
216 // We override this function so that if the plugin is windowed, we can call
217 // NPP_SetWindow at the first possible moment. This ensures that
218 // NPP_SetWindow is called before the manual load data is sent to a plugin.
219 // If this order is reversed, Flash won't load videos.
221 Widget::setParent(view);
226 bool WebPluginContainerImpl::supportsPaginatedPrint() const
228 return m_webPlugin->supportsPaginatedPrint();
231 int WebPluginContainerImpl::printBegin(const IntRect& printableArea,
232 int printerDPI) const
234 return m_webPlugin->printBegin(printableArea, printerDPI);
237 bool WebPluginContainerImpl::printPage(int pageNumber,
238 WebCore::GraphicsContext* gc)
241 #if WEBKIT_USING_SKIA
242 WebCanvas* canvas = gc->platformContext()->canvas();
243 #elif WEBKIT_USING_CG
244 WebCanvas* canvas = gc->platformContext();
246 bool ret = m_webPlugin->printPage(pageNumber, canvas);
251 void WebPluginContainerImpl::printEnd()
253 return m_webPlugin->printEnd();
256 void WebPluginContainerImpl::copy()
258 if (!plugin()->hasSelection())
261 webKitClient()->clipboard()->writeHTML(plugin()->selectionAsMarkup(), WebURL(), plugin()->selectionAsText(), false);
264 WebElement WebPluginContainerImpl::element()
266 return WebElement(m_element);
269 void WebPluginContainerImpl::invalidate()
271 Widget::invalidate();
274 void WebPluginContainerImpl::invalidateRect(const WebRect& rect)
276 invalidateRect(static_cast<IntRect>(rect));
279 void WebPluginContainerImpl::scrollRect(int dx, int dy, const WebRect& rect)
281 Widget* parentWidget = parent();
282 if (parentWidget->isFrameView()) {
283 FrameView* parentFrameView = static_cast<FrameView*>(parentWidget);
284 if (!parentFrameView->isOverlapped()) {
285 IntRect damageRect = convertToContainingWindow(static_cast<IntRect>(rect));
286 IntSize scrollDelta(dx, dy);
287 // scroll() only uses the second rectangle, clipRect, and ignores the first
289 parent()->hostWindow()->scroll(scrollDelta, damageRect, damageRect);
294 // Use slow scrolling instead.
295 invalidateRect(rect);
298 void WebPluginContainerImpl::reportGeometry()
303 IntRect windowRect, clipRect;
304 Vector<IntRect> cutOutRects;
305 calculateGeometry(frameRect(), windowRect, clipRect, cutOutRects);
307 m_webPlugin->updateGeometry(windowRect, clipRect, cutOutRects, isVisible());
310 void WebPluginContainerImpl::commitBackingTexture()
312 #if USE(ACCELERATED_COMPOSITING)
314 platformLayer()->setNeedsDisplay();
318 void WebPluginContainerImpl::clearScriptObjects()
320 Frame* frame = m_element->document()->frame();
323 frame->script()->cleanupScriptObjectsForPlugin(this);
326 NPObject* WebPluginContainerImpl::scriptableObjectForElement()
328 return m_element->getNPObject();
331 WebString WebPluginContainerImpl::executeScriptURL(const WebURL& url, bool popupsAllowed)
333 Frame* frame = m_element->document()->frame();
337 const KURL& kurl = url;
338 ASSERT(kurl.protocolIs("javascript"));
340 String script = decodeURLEscapeSequences(
341 kurl.string().substring(strlen("javascript:")));
343 ScriptValue result = frame->script()->executeScript(script, popupsAllowed);
345 // Failure is reported as a null string.
347 result.getString(resultStr);
351 void WebPluginContainerImpl::loadFrameRequest(
352 const WebURLRequest& request, const WebString& target, bool notifyNeeded, void* notifyData)
354 Frame* frame = m_element->document()->frame();
356 return; // FIXME: send a notification in this case?
359 // FIXME: This is a bit of hack to allow us to observe completion of
360 // our frame request. It would be better to evolve FrameLoader to
361 // support a completion callback instead.
362 WebPluginLoadObserver* observer =
363 new WebPluginLoadObserver(this, request.url(), notifyData);
364 m_pluginLoadObservers.append(observer);
365 WebDataSourceImpl::setNextPluginLoadObserver(observer);
368 FrameLoadRequest frameRequest(request.toResourceRequest());
369 frameRequest.setFrameName(target);
371 frame->loader()->loadFrameRequest(
373 false, // lock history
374 false, // lock back forward list
380 void WebPluginContainerImpl::zoomLevelChanged(double zoomLevel)
382 WebViewImpl* view = WebViewImpl::fromPage(m_element->document()->frame()->page());
383 view->fullFramePluginZoomLevelChanged(zoomLevel);
386 void WebPluginContainerImpl::didReceiveResponse(const ResourceResponse& response)
388 // Make sure that the plugin receives window geometry before data, or else
389 // plugins misbehave.
392 WrappedResourceResponse urlResponse(response);
393 m_webPlugin->didReceiveResponse(urlResponse);
396 void WebPluginContainerImpl::didReceiveData(const char *data, int dataLength)
398 m_webPlugin->didReceiveData(data, dataLength);
401 void WebPluginContainerImpl::didFinishLoading()
403 m_webPlugin->didFinishLoading();
406 void WebPluginContainerImpl::didFailLoading(const ResourceError& error)
408 m_webPlugin->didFailLoading(error);
411 NPObject* WebPluginContainerImpl::scriptableObject()
413 return m_webPlugin->scriptableObject();
416 void WebPluginContainerImpl::willDestroyPluginLoadObserver(WebPluginLoadObserver* observer)
418 size_t pos = m_pluginLoadObservers.find(observer);
421 m_pluginLoadObservers.remove(pos);
424 #if USE(ACCELERATED_COMPOSITING)
425 WebCore::LayerChromium* WebPluginContainerImpl::platformLayer() const
427 // FIXME: In the event of a context lost, the texture needs to be recreated on the compositor's
428 // context and rebound to the platform layer here.
429 unsigned backingTextureId = m_webPlugin->getBackingTextureId();
430 if (!backingTextureId)
433 m_platformLayer->setTextureId(backingTextureId);
435 return m_platformLayer.get();
439 // Private methods -------------------------------------------------------------
441 WebPluginContainerImpl::WebPluginContainerImpl(WebCore::HTMLPlugInElement* element, WebPlugin* webPlugin)
442 : WebCore::PluginViewBase(0)
444 , m_webPlugin(webPlugin)
445 #if USE(ACCELERATED_COMPOSITING)
446 , m_platformLayer(PluginLayerChromium::create(0))
451 WebPluginContainerImpl::~WebPluginContainerImpl()
453 for (size_t i = 0; i < m_pluginLoadObservers.size(); ++i)
454 m_pluginLoadObservers[i]->clearPluginContainer();
455 m_webPlugin->destroy();
458 void WebPluginContainerImpl::handleMouseEvent(MouseEvent* event)
460 ASSERT(parent()->isFrameView());
462 // We cache the parent FrameView here as the plugin widget could be deleted
463 // in the call to HandleEvent. See http://b/issue?id=1362948
464 FrameView* parentView = static_cast<FrameView*>(parent());
466 WebMouseEventBuilder webEvent(this, *event);
467 if (webEvent.type == WebInputEvent::Undefined)
470 if (event->type() == eventNames().mousedownEvent) {
471 // Ensure that the frame containing the plugin has focus.
472 Frame* containingFrame = parentView->frame();
473 if (Page* currentPage = containingFrame->page())
474 currentPage->focusController()->setFocusedFrame(containingFrame);
475 // Give focus to our containing HTMLPluginElement.
476 containingFrame->document()->setFocusedNode(m_element);
479 WebCursorInfo cursorInfo;
480 if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
481 event->setDefaultHandled();
483 // A windowless plugin can change the cursor in response to a mouse move
484 // event. We need to reflect the changed cursor in the frame view as the
485 // mouse is moved in the boundaries of the windowless plugin.
486 Page* page = parentView->frame()->page();
489 ChromeClientImpl* chromeClient =
490 static_cast<ChromeClientImpl*>(page->chrome()->client());
491 chromeClient->setCursorForPlugin(cursorInfo);
494 void WebPluginContainerImpl::handleWheelEvent(WheelEvent* event)
496 WebMouseWheelEventBuilder webEvent(this, *event);
497 if (webEvent.type == WebInputEvent::Undefined)
500 WebCursorInfo cursorInfo;
501 if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
502 event->setDefaultHandled();
505 void WebPluginContainerImpl::handleKeyboardEvent(KeyboardEvent* event)
507 WebKeyboardEventBuilder webEvent(*event);
508 if (webEvent.type == WebInputEvent::Undefined)
511 if (webEvent.type == WebInputEvent::KeyDown) {
512 #if defined(OS_MACOSX)
513 if (webEvent.modifiers == WebInputEvent::MetaKey
515 if (webEvent.modifiers == WebInputEvent::ControlKey
517 && webEvent.windowsKeyCode == VKEY_C) {
519 event->setDefaultHandled();
524 const WebInputEvent* currentInputEvent = WebViewImpl::currentInputEvent();
526 // Copy stashed info over, and only copy here in order not to interfere
527 // the ctrl-c logic above.
528 if (currentInputEvent
529 && WebInputEvent::isKeyboardEventType(currentInputEvent->type)) {
530 webEvent.modifiers |= currentInputEvent->modifiers &
531 (WebInputEvent::CapsLockOn | WebInputEvent::NumLockOn);
534 WebCursorInfo cursorInfo;
535 if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
536 event->setDefaultHandled();
539 void WebPluginContainerImpl::calculateGeometry(const IntRect& frameRect,
542 Vector<IntRect>& cutOutRects)
544 windowRect = IntRect(
545 parent()->contentsToWindow(frameRect.location()), frameRect.size());
547 // Calculate a clip-rect so that we don't overlap the scrollbars, etc.
548 clipRect = windowClipRect();
549 clipRect.move(-windowRect.x(), -windowRect.y());
551 windowCutOutRects(frameRect, cutOutRects);
552 // Convert to the plugin position.
553 for (size_t i = 0; i < cutOutRects.size(); i++)
554 cutOutRects[i].move(-frameRect.x(), -frameRect.y());
557 WebCore::IntRect WebPluginContainerImpl::windowClipRect() const
559 // Start by clipping to our bounds.
561 convertToContainingWindow(IntRect(0, 0, width(), height()));
563 // document()->renderer() can be 0 when we receive messages from the
564 // plugins while we are destroying a frame.
565 if (m_element->renderer()->document()->renderer()) {
566 // Take our element and get the clip rect from the enclosing layer and
568 RenderLayer* layer = m_element->renderer()->enclosingLayer();
570 m_element->document()->view()->windowClipRectForLayer(layer, true));
576 static void getObjectStack(const RenderObject* ro,
577 Vector<const RenderObject*>* roStack)
586 // Returns true if stack1 is at or above stack2
587 static bool checkStackOnTop(
588 const Vector<const RenderObject*>& iframeZstack,
589 const Vector<const RenderObject*>& pluginZstack)
591 for (size_t i1 = 0, i2 = 0;
592 i1 < iframeZstack.size() && i2 < pluginZstack.size();
594 // The root is at the end of these stacks. We want to iterate
595 // root-downwards so we index backwards from the end.
596 const RenderObject* ro1 = iframeZstack[iframeZstack.size() - 1 - i1];
597 const RenderObject* ro2 = pluginZstack[pluginZstack.size() - 1 - i2];
600 // When we find nodes in the stack that are not the same, then
601 // we've found the nodes just below the lowest comment ancestor.
602 // Determine which should be on top.
604 // See if z-index determines an order.
605 if (ro1->style() && ro2->style()) {
606 int z1 = ro1->style()->zIndex();
607 int z2 = ro2->style()->zIndex();
614 // If the plugin does not have an explicit z-index it stacks behind the iframe.
615 // This is for maintaining compatibility with IE.
616 if (ro2->style()->position() == StaticPosition) {
617 // The 0'th elements of these RenderObject arrays represent the plugin node and
619 const RenderObject* pluginRenderObject = pluginZstack[0];
620 const RenderObject* iframeRenderObject = iframeZstack[0];
622 if (pluginRenderObject->style() && iframeRenderObject->style()) {
623 if (pluginRenderObject->style()->zIndex() > iframeRenderObject->style()->zIndex())
629 // Inspect the document order. Later order means higher
631 const RenderObject* parent = ro1->parent();
634 ASSERT(parent == ro2->parent());
636 for (const RenderObject* ro = parent->firstChild(); ro; ro = ro->nextSibling()) {
642 ASSERT(false); // We should have seen ro1 and ro2 by now.
649 // Return a set of rectangles that should not be overdrawn by the
650 // plugin ("cutouts"). This helps implement the "iframe shim"
651 // technique of overlaying a windowed plugin with content from the
652 // page. In a nutshell, iframe elements should occlude plugins when
653 // they occur higher in the stacking order.
654 void WebPluginContainerImpl::windowCutOutRects(const IntRect& frameRect,
655 Vector<IntRect>& cutOutRects)
657 RenderObject* pluginNode = m_element->renderer();
659 if (!pluginNode->style())
661 Vector<const RenderObject*> pluginZstack;
662 Vector<const RenderObject*> iframeZstack;
663 getObjectStack(pluginNode, &pluginZstack);
665 // Get the parent widget
666 Widget* parentWidget = this->parent();
667 if (!parentWidget->isFrameView())
670 FrameView* parentFrameView = static_cast<FrameView*>(parentWidget);
672 const HashSet<RefPtr<Widget> >* children = parentFrameView->children();
673 for (HashSet<RefPtr<Widget> >::const_iterator it = children->begin(); it != children->end(); ++it) {
674 // We only care about FrameView's because iframes show up as FrameViews.
675 if (!(*it)->isFrameView())
678 const FrameView* frameView =
679 static_cast<const FrameView*>((*it).get());
680 // Check to make sure we can get both the element and the RenderObject
681 // for this FrameView, if we can't just move on to the next object.
682 if (!frameView->frame() || !frameView->frame()->ownerElement()
683 || !frameView->frame()->ownerElement()->renderer())
686 HTMLElement* element = frameView->frame()->ownerElement();
687 RenderObject* iframeRenderer = element->renderer();
689 if (element->hasTagName(HTMLNames::iframeTag)
690 && iframeRenderer->absoluteBoundingBoxRect().intersects(frameRect)
691 && (!iframeRenderer->style() || iframeRenderer->style()->visibility() == VISIBLE)) {
692 getObjectStack(iframeRenderer, &iframeZstack);
693 if (checkStackOnTop(iframeZstack, pluginZstack)) {
695 roundedIntPoint(iframeRenderer->localToAbsolute());
696 RenderBox* rbox = toRenderBox(iframeRenderer);
697 IntSize size(rbox->width(), rbox->height());
698 cutOutRects.append(IntRect(point, size));
704 } // namespace WebKit