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 "WebViewImpl.h"
52 #include "WrappedResourceResponse.h"
54 #include "EventNames.h"
55 #include "FocusController.h"
56 #include "FormState.h"
58 #include "FrameLoadRequest.h"
59 #include "FrameView.h"
60 #include "GraphicsContext.h"
61 #include "HostWindow.h"
62 #include "HTMLFormElement.h"
63 #include "HTMLNames.h"
64 #include "HTMLPlugInElement.h"
65 #include "KeyboardCodes.h"
66 #include "KeyboardEvent.h"
67 #include "MouseEvent.h"
69 #include "RenderBox.h"
70 #include "ScrollView.h"
71 #include "WheelEvent.h"
74 #include "PlatformContextSkia.h"
77 using namespace WebCore;
81 // Public methods --------------------------------------------------------------
83 void WebPluginContainerImpl::setFrameRect(const IntRect& frameRect)
85 Widget::setFrameRect(frameRect);
89 void WebPluginContainerImpl::paint(GraphicsContext* gc, const IntRect& damageRect)
91 if (gc->paintingDisabled())
97 // Don't paint anything if the plugin doesn't intersect the damage rect.
98 if (!frameRect().intersects(damageRect))
103 ASSERT(parent()->isFrameView());
104 ScrollView* view = parent();
106 // The plugin is positioned in window coordinates, so it needs to be painted
107 // in window coordinates.
108 IntPoint origin = view->windowToContents(IntPoint(0, 0));
109 gc->translate(static_cast<float>(origin.x()), static_cast<float>(origin.y()));
111 #if WEBKIT_USING_SKIA
112 WebCanvas* canvas = gc->platformContext()->canvas();
113 #elif WEBKIT_USING_CG
114 WebCanvas* canvas = gc->platformContext();
118 IntRect(view->contentsToWindow(damageRect.location()), damageRect.size());
119 m_webPlugin->paint(canvas, windowRect);
124 void WebPluginContainerImpl::invalidateRect(const IntRect& rect)
129 IntRect damageRect = convertToContainingWindow(rect);
131 // Get our clip rect and intersect with it to ensure we don't invalidate
133 IntRect clipRect = parent()->windowClipRect();
134 damageRect.intersect(clipRect);
136 parent()->hostWindow()->invalidateContentsAndWindow(damageRect, false /*immediate*/);
139 void WebPluginContainerImpl::setFocus(bool focused)
141 Widget::setFocus(focused);
142 m_webPlugin->updateFocus(focused);
145 void WebPluginContainerImpl::show()
147 setSelfVisible(true);
148 m_webPlugin->updateVisibility(true);
153 void WebPluginContainerImpl::hide()
155 setSelfVisible(false);
156 m_webPlugin->updateVisibility(false);
161 void WebPluginContainerImpl::handleEvent(Event* event)
163 if (!m_webPlugin->acceptsInputEvents())
166 // The events we pass are defined at:
167 // http://devedge-temp.mozilla.org/library/manuals/2002/plugin/1.0/structures5.html#1000000
168 // Don't take the documentation as truth, however. There are many cases
169 // where mozilla behaves differently than the spec.
170 if (event->isMouseEvent())
171 handleMouseEvent(static_cast<MouseEvent*>(event));
172 else if (event->isWheelEvent())
173 handleWheelEvent(static_cast<WheelEvent*>(event));
174 else if (event->isKeyboardEvent())
175 handleKeyboardEvent(static_cast<KeyboardEvent*>(event));
177 // FIXME: it would be cleaner if Widget::handleEvent returned true/false and
178 // HTMLPluginElement called setDefaultHandled or defaultEventHandler.
179 if (!event->defaultHandled())
180 m_element->Node::defaultEventHandler(event);
183 void WebPluginContainerImpl::frameRectsChanged()
185 Widget::frameRectsChanged();
189 void WebPluginContainerImpl::widgetPositionsUpdated()
191 Widget::widgetPositionsUpdated();
195 void WebPluginContainerImpl::setParentVisible(bool parentVisible)
197 // We override this function to make sure that geometry updates are sent
198 // over to the plugin. For e.g. when a plugin is instantiated it does not
199 // have a valid parent. As a result the first geometry update from webkit
200 // is ignored. This function is called when the plugin eventually gets a
203 if (isParentVisible() == parentVisible)
204 return; // No change.
206 Widget::setParentVisible(parentVisible);
207 if (!isSelfVisible())
208 return; // This widget has explicitely been marked as not visible.
210 m_webPlugin->updateVisibility(isVisible());
213 void WebPluginContainerImpl::setParent(ScrollView* view)
215 // We override this function so that if the plugin is windowed, we can call
216 // NPP_SetWindow at the first possible moment. This ensures that
217 // NPP_SetWindow is called before the manual load data is sent to a plugin.
218 // If this order is reversed, Flash won't load videos.
220 Widget::setParent(view);
225 bool WebPluginContainerImpl::supportsPaginatedPrint() const
227 return m_webPlugin->supportsPaginatedPrint();
230 int WebPluginContainerImpl::printBegin(const IntRect& printableArea,
231 int printerDPI) const
233 return m_webPlugin->printBegin(printableArea, printerDPI);
236 bool WebPluginContainerImpl::printPage(int pageNumber,
237 WebCore::GraphicsContext* gc)
240 #if WEBKIT_USING_SKIA
241 WebCanvas* canvas = gc->platformContext()->canvas();
242 #elif WEBKIT_USING_CG
243 WebCanvas* canvas = gc->platformContext();
245 bool ret = m_webPlugin->printPage(pageNumber, canvas);
250 void WebPluginContainerImpl::printEnd()
252 return m_webPlugin->printEnd();
255 void WebPluginContainerImpl::copy()
257 if (!plugin()->hasSelection())
260 webKitClient()->clipboard()->writeHTML(plugin()->selectionAsMarkup(), WebURL(), plugin()->selectionAsText(), false);
263 WebElement WebPluginContainerImpl::element()
265 return WebElement(m_element);
268 void WebPluginContainerImpl::invalidate()
270 Widget::invalidate();
273 void WebPluginContainerImpl::invalidateRect(const WebRect& rect)
275 invalidateRect(static_cast<IntRect>(rect));
278 void WebPluginContainerImpl::reportGeometry()
283 IntRect windowRect, clipRect;
284 Vector<IntRect> cutOutRects;
285 calculateGeometry(frameRect(), windowRect, clipRect, cutOutRects);
287 m_webPlugin->updateGeometry(windowRect, clipRect, cutOutRects, isVisible());
290 void WebPluginContainerImpl::clearScriptObjects()
292 Frame* frame = m_element->document()->frame();
295 frame->script()->cleanupScriptObjectsForPlugin(this);
298 NPObject* WebPluginContainerImpl::scriptableObjectForElement()
300 return m_element->getNPObject();
303 WebString WebPluginContainerImpl::executeScriptURL(const WebURL& url, bool popupsAllowed)
305 Frame* frame = m_element->document()->frame();
309 const KURL& kurl = url;
310 ASSERT(kurl.protocolIs("javascript"));
312 String script = decodeURLEscapeSequences(
313 kurl.string().substring(strlen("javascript:")));
315 ScriptValue result = frame->script()->executeScript(script, popupsAllowed);
317 // Failure is reported as a null string.
319 result.getString(resultStr);
323 void WebPluginContainerImpl::loadFrameRequest(
324 const WebURLRequest& request, const WebString& target, bool notifyNeeded, void* notifyData)
326 Frame* frame = m_element->document()->frame();
328 return; // FIXME: send a notification in this case?
331 // FIXME: This is a bit of hack to allow us to observe completion of
332 // our frame request. It would be better to evolve FrameLoader to
333 // support a completion callback instead.
334 WebPluginLoadObserver* observer =
335 new WebPluginLoadObserver(this, request.url(), notifyData);
336 m_pluginLoadObservers.append(observer);
337 WebDataSourceImpl::setNextPluginLoadObserver(observer);
340 FrameLoadRequest frameRequest(request.toResourceRequest());
341 frameRequest.setFrameName(target);
343 frame->loader()->loadFrameRequest(
345 false, // lock history
346 false, // lock back forward list
352 void WebPluginContainerImpl::zoomLevelChanged(double zoomLevel)
354 WebViewImpl* view = WebViewImpl::fromPage(m_element->document()->frame()->page());
355 view->fullFramePluginZoomLevelChanged(zoomLevel);
358 void WebPluginContainerImpl::didReceiveResponse(const ResourceResponse& response)
360 // Make sure that the plugin receives window geometry before data, or else
361 // plugins misbehave.
364 WrappedResourceResponse urlResponse(response);
365 m_webPlugin->didReceiveResponse(urlResponse);
368 void WebPluginContainerImpl::didReceiveData(const char *data, int dataLength)
370 m_webPlugin->didReceiveData(data, dataLength);
373 void WebPluginContainerImpl::didFinishLoading()
375 m_webPlugin->didFinishLoading();
378 void WebPluginContainerImpl::didFailLoading(const ResourceError& error)
380 m_webPlugin->didFailLoading(error);
383 NPObject* WebPluginContainerImpl::scriptableObject()
385 return m_webPlugin->scriptableObject();
388 void WebPluginContainerImpl::willDestroyPluginLoadObserver(WebPluginLoadObserver* observer)
390 size_t pos = m_pluginLoadObservers.find(observer);
393 m_pluginLoadObservers.remove(pos);
396 // Private methods -------------------------------------------------------------
398 WebPluginContainerImpl::~WebPluginContainerImpl()
400 for (size_t i = 0; i < m_pluginLoadObservers.size(); ++i)
401 m_pluginLoadObservers[i]->clearPluginContainer();
402 m_webPlugin->destroy();
405 void WebPluginContainerImpl::handleMouseEvent(MouseEvent* event)
407 ASSERT(parent()->isFrameView());
409 // We cache the parent FrameView here as the plugin widget could be deleted
410 // in the call to HandleEvent. See http://b/issue?id=1362948
411 FrameView* parentView = static_cast<FrameView*>(parent());
413 WebMouseEventBuilder webEvent(this, *event);
414 if (webEvent.type == WebInputEvent::Undefined)
417 if (event->type() == eventNames().mousedownEvent) {
418 // Ensure that the frame containing the plugin has focus.
419 Frame* containingFrame = parentView->frame();
420 if (Page* currentPage = containingFrame->page())
421 currentPage->focusController()->setFocusedFrame(containingFrame);
422 // Give focus to our containing HTMLPluginElement.
423 containingFrame->document()->setFocusedNode(m_element);
426 WebCursorInfo cursorInfo;
427 if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
428 event->setDefaultHandled();
430 // A windowless plugin can change the cursor in response to a mouse move
431 // event. We need to reflect the changed cursor in the frame view as the
432 // mouse is moved in the boundaries of the windowless plugin.
433 Page* page = parentView->frame()->page();
436 ChromeClientImpl* chromeClient =
437 static_cast<ChromeClientImpl*>(page->chrome()->client());
438 chromeClient->setCursorForPlugin(cursorInfo);
441 void WebPluginContainerImpl::handleWheelEvent(WheelEvent* event)
443 WebMouseWheelEventBuilder webEvent(this, *event);
444 if (webEvent.type == WebInputEvent::Undefined)
447 WebCursorInfo cursorInfo;
448 if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
449 event->setDefaultHandled();
452 void WebPluginContainerImpl::handleKeyboardEvent(KeyboardEvent* event)
454 WebKeyboardEventBuilder webEvent(*event);
455 if (webEvent.type == WebInputEvent::Undefined)
458 if (webEvent.type == WebInputEvent::KeyDown) {
459 #if defined(OS_MACOSX)
460 if (webEvent.modifiers == WebInputEvent::MetaKey
462 if (webEvent.modifiers == WebInputEvent::ControlKey
464 && webEvent.windowsKeyCode == VKEY_C) {
466 event->setDefaultHandled();
471 const WebInputEvent* currentInputEvent = WebViewImpl::currentInputEvent();
473 // Copy stashed info over, and only copy here in order not to interfere
474 // the ctrl-c logic above.
475 if (currentInputEvent
476 && WebInputEvent::isKeyboardEventType(currentInputEvent->type)) {
477 webEvent.modifiers |= currentInputEvent->modifiers &
478 (WebInputEvent::CapsLockOn | WebInputEvent::NumLockOn);
481 WebCursorInfo cursorInfo;
482 if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
483 event->setDefaultHandled();
486 void WebPluginContainerImpl::calculateGeometry(const IntRect& frameRect,
489 Vector<IntRect>& cutOutRects)
491 windowRect = IntRect(
492 parent()->contentsToWindow(frameRect.location()), frameRect.size());
494 // Calculate a clip-rect so that we don't overlap the scrollbars, etc.
495 clipRect = windowClipRect();
496 clipRect.move(-windowRect.x(), -windowRect.y());
498 windowCutOutRects(frameRect, cutOutRects);
499 // Convert to the plugin position.
500 for (size_t i = 0; i < cutOutRects.size(); i++)
501 cutOutRects[i].move(-frameRect.x(), -frameRect.y());
504 WebCore::IntRect WebPluginContainerImpl::windowClipRect() const
506 // Start by clipping to our bounds.
508 convertToContainingWindow(IntRect(0, 0, width(), height()));
510 // document()->renderer() can be 0 when we receive messages from the
511 // plugins while we are destroying a frame.
512 if (m_element->renderer()->document()->renderer()) {
513 // Take our element and get the clip rect from the enclosing layer and
515 RenderLayer* layer = m_element->renderer()->enclosingLayer();
517 m_element->document()->view()->windowClipRectForLayer(layer, true));
523 static void getObjectStack(const RenderObject* ro,
524 Vector<const RenderObject*>* roStack)
533 // Returns true if stack1 is at or above stack2
534 static bool checkStackOnTop(
535 const Vector<const RenderObject*>& iframeZstack,
536 const Vector<const RenderObject*>& pluginZstack)
538 for (size_t i1 = 0, i2 = 0;
539 i1 < iframeZstack.size() && i2 < pluginZstack.size();
541 // The root is at the end of these stacks. We want to iterate
542 // root-downwards so we index backwards from the end.
543 const RenderObject* ro1 = iframeZstack[iframeZstack.size() - 1 - i1];
544 const RenderObject* ro2 = pluginZstack[pluginZstack.size() - 1 - i2];
547 // When we find nodes in the stack that are not the same, then
548 // we've found the nodes just below the lowest comment ancestor.
549 // Determine which should be on top.
551 // See if z-index determines an order.
552 if (ro1->style() && ro2->style()) {
553 int z1 = ro1->style()->zIndex();
554 int z2 = ro2->style()->zIndex();
561 // If the plugin does not have an explicit z-index it stacks behind the iframe.
562 // This is for maintaining compatibility with IE.
563 if (ro2->style()->position() == StaticPosition) {
564 // The 0'th elements of these RenderObject arrays represent the plugin node and
566 const RenderObject* pluginRenderObject = pluginZstack[0];
567 const RenderObject* iframeRenderObject = iframeZstack[0];
569 if (pluginRenderObject->style() && iframeRenderObject->style()) {
570 if (pluginRenderObject->style()->zIndex() > iframeRenderObject->style()->zIndex())
576 // Inspect the document order. Later order means higher
578 const RenderObject* parent = ro1->parent();
581 ASSERT(parent == ro2->parent());
583 for (const RenderObject* ro = parent->firstChild(); ro; ro = ro->nextSibling()) {
589 ASSERT(false); // We should have seen ro1 and ro2 by now.
596 // Return a set of rectangles that should not be overdrawn by the
597 // plugin ("cutouts"). This helps implement the "iframe shim"
598 // technique of overlaying a windowed plugin with content from the
599 // page. In a nutshell, iframe elements should occlude plugins when
600 // they occur higher in the stacking order.
601 void WebPluginContainerImpl::windowCutOutRects(const IntRect& frameRect,
602 Vector<IntRect>& cutOutRects)
604 RenderObject* pluginNode = m_element->renderer();
606 if (!pluginNode->style())
608 Vector<const RenderObject*> pluginZstack;
609 Vector<const RenderObject*> iframeZstack;
610 getObjectStack(pluginNode, &pluginZstack);
612 // Get the parent widget
613 Widget* parentWidget = this->parent();
614 if (!parentWidget->isFrameView())
617 FrameView* parentFrameView = static_cast<FrameView*>(parentWidget);
619 const HashSet<RefPtr<Widget> >* children = parentFrameView->children();
620 for (HashSet<RefPtr<Widget> >::const_iterator it = children->begin(); it != children->end(); ++it) {
621 // We only care about FrameView's because iframes show up as FrameViews.
622 if (!(*it)->isFrameView())
625 const FrameView* frameView =
626 static_cast<const FrameView*>((*it).get());
627 // Check to make sure we can get both the element and the RenderObject
628 // for this FrameView, if we can't just move on to the next object.
629 if (!frameView->frame() || !frameView->frame()->ownerElement()
630 || !frameView->frame()->ownerElement()->renderer())
633 HTMLElement* element = frameView->frame()->ownerElement();
634 RenderObject* iframeRenderer = element->renderer();
636 if (element->hasTagName(HTMLNames::iframeTag)
637 && iframeRenderer->absoluteBoundingBoxRect().intersects(frameRect)
638 && (!iframeRenderer->style() || iframeRenderer->style()->visibility() == VISIBLE)) {
639 getObjectStack(iframeRenderer, &iframeZstack);
640 if (checkStackOnTop(iframeZstack, pluginZstack)) {
642 roundedIntPoint(iframeRenderer->localToAbsolute());
643 RenderBox* rbox = toRenderBox(iframeRenderer);
644 IntSize size(rbox->width(), rbox->height());
645 cutOutRects.append(IntRect(point, size));
651 } // namespace WebKit