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 "WebInputEvent.h"
39 #include "WebInputEventConversion.h"
41 #include "WebPlugin.h"
43 #include "WebURLError.h"
44 #include "WebURLRequest.h"
45 #include "WebVector.h"
46 #include "WrappedResourceResponse.h"
48 #include "EventNames.h"
49 #include "FocusController.h"
50 #include "FormState.h"
52 #include "FrameLoadRequest.h"
53 #include "FrameView.h"
54 #include "GraphicsContext.h"
55 #include "HostWindow.h"
56 #include "HTMLFormElement.h"
57 #include "HTMLNames.h"
58 #include "HTMLPlugInElement.h"
59 #include "KeyboardEvent.h"
60 #include "MouseEvent.h"
62 #include "ScrollView.h"
65 #include "PlatformContextSkia.h"
68 using namespace WebCore;
72 // Public methods --------------------------------------------------------------
74 void WebPluginContainerImpl::setFrameRect(const IntRect& frameRect)
76 Widget::setFrameRect(frameRect);
80 void WebPluginContainerImpl::paint(GraphicsContext* gc, const IntRect& damageRect)
82 if (gc->paintingDisabled())
88 // Don't paint anything if the plugin doesn't intersect the damage rect.
89 if (!frameRect().intersects(damageRect))
94 ASSERT(parent()->isFrameView());
95 ScrollView* view = parent();
97 // The plugin is positioned in window coordinates, so it needs to be painted
98 // in window coordinates.
99 IntPoint origin = view->windowToContents(IntPoint(0, 0));
100 gc->translate(static_cast<float>(origin.x()), static_cast<float>(origin.y()));
102 #if WEBKIT_USING_SKIA
103 WebCanvas* canvas = gc->platformContext()->canvas();
104 #elif WEBKIT_USING_CG
105 WebCanvas* canvas = gc->platformContext();
109 IntRect(view->contentsToWindow(damageRect.location()), damageRect.size());
110 m_webPlugin->paint(canvas, windowRect);
115 void WebPluginContainerImpl::invalidateRect(const IntRect& rect)
120 IntRect damageRect = convertToContainingWindow(rect);
122 // Get our clip rect and intersect with it to ensure we don't invalidate
124 IntRect clipRect = parent()->windowClipRect();
125 damageRect.intersect(clipRect);
127 parent()->hostWindow()->repaint(damageRect, true);
130 void WebPluginContainerImpl::setFocus()
133 m_webPlugin->updateFocus(true);
136 void WebPluginContainerImpl::show()
138 setSelfVisible(true);
139 m_webPlugin->updateVisibility(true);
144 void WebPluginContainerImpl::hide()
146 setSelfVisible(false);
147 m_webPlugin->updateVisibility(false);
152 void WebPluginContainerImpl::handleEvent(Event* event)
154 if (!m_webPlugin->acceptsInputEvents())
157 // The events we pass are defined at:
158 // http://devedge-temp.mozilla.org/library/manuals/2002/plugin/1.0/structures5.html#1000000
159 // Don't take the documentation as truth, however. There are many cases
160 // where mozilla behaves differently than the spec.
161 if (event->isMouseEvent())
162 handleMouseEvent(static_cast<MouseEvent*>(event));
163 else if (event->isKeyboardEvent())
164 handleKeyboardEvent(static_cast<KeyboardEvent*>(event));
167 void WebPluginContainerImpl::frameRectsChanged()
169 Widget::frameRectsChanged();
173 void WebPluginContainerImpl::setParentVisible(bool parentVisible)
175 // We override this function to make sure that geometry updates are sent
176 // over to the plugin. For e.g. when a plugin is instantiated it does not
177 // have a valid parent. As a result the first geometry update from webkit
178 // is ignored. This function is called when the plugin eventually gets a
181 if (isParentVisible() == parentVisible)
182 return; // No change.
184 Widget::setParentVisible(parentVisible);
185 if (!isSelfVisible())
186 return; // This widget has explicitely been marked as not visible.
188 m_webPlugin->updateVisibility(isVisible());
191 void WebPluginContainerImpl::setParent(ScrollView* view)
193 // We override this function so that if the plugin is windowed, we can call
194 // NPP_SetWindow at the first possible moment. This ensures that
195 // NPP_SetWindow is called before the manual load data is sent to a plugin.
196 // If this order is reversed, Flash won't load videos.
198 Widget::setParent(view);
203 void WebPluginContainerImpl::invalidate()
205 Widget::invalidate();
208 void WebPluginContainerImpl::invalidateRect(const WebRect& rect)
210 invalidateRect(static_cast<IntRect>(rect));
213 void WebPluginContainerImpl::reportGeometry()
218 IntRect windowRect, clipRect;
219 Vector<IntRect> cutOutRects;
220 calculateGeometry(frameRect(), windowRect, clipRect, cutOutRects);
222 m_webPlugin->updateGeometry(windowRect, clipRect, cutOutRects, isVisible());
225 void WebPluginContainerImpl::clearScriptObjects()
227 Frame* frame = m_element->document()->frame();
230 frame->script()->cleanupScriptObjectsForPlugin(this);
233 NPObject* WebPluginContainerImpl::scriptableObjectForElement()
235 return m_element->getNPObject();
238 WebString WebPluginContainerImpl::executeScriptURL(const WebURL& url, bool popupsAllowed)
240 Frame* frame = m_element->document()->frame();
244 const KURL& kurl = url;
245 ASSERT(kurl.protocolIs("javascript"));
247 String script = decodeURLEscapeSequences(
248 kurl.string().substring(strlen("javascript:")));
250 ScriptValue result = frame->script()->executeScript(script, popupsAllowed);
252 // Failure is reported as a null string.
254 result.getString(resultStr);
258 void WebPluginContainerImpl::loadFrameRequest(
259 const WebURLRequest& request, const WebString& target, bool notifyNeeded, void* notifyData)
261 Frame* frame = m_element->document()->frame();
263 return; // FIXME: send a notification in this case?
266 // FIXME: This is a bit of hack to allow us to observe completion of
267 // our frame request. It would be better to evolve FrameLoader to
268 // support a completion callback instead.
269 WebPluginLoadObserver* observer =
270 new WebPluginLoadObserver(this, request.url(), notifyData);
271 m_pluginLoadObservers.append(observer);
272 WebDataSourceImpl::setNextPluginLoadObserver(observer);
275 FrameLoadRequest frameRequest(request.toResourceRequest());
276 frameRequest.setFrameName(target);
278 frame->loader()->loadFrameRequest(
280 false, // lock history
281 false, // lock back forward list
287 void WebPluginContainerImpl::didReceiveResponse(const ResourceResponse& response)
289 // Make sure that the plugin receives window geometry before data, or else
290 // plugins misbehave.
293 WrappedResourceResponse urlResponse(response);
294 m_webPlugin->didReceiveResponse(urlResponse);
297 void WebPluginContainerImpl::didReceiveData(const char *data, int dataLength)
299 m_webPlugin->didReceiveData(data, dataLength);
302 void WebPluginContainerImpl::didFinishLoading()
304 m_webPlugin->didFinishLoading();
307 void WebPluginContainerImpl::didFailLoading(const ResourceError& error)
309 m_webPlugin->didFailLoading(error);
312 NPObject* WebPluginContainerImpl::scriptableObject()
314 return m_webPlugin->scriptableObject();
317 void WebPluginContainerImpl::willDestroyPluginLoadObserver(WebPluginLoadObserver* observer)
319 size_t pos = m_pluginLoadObservers.find(observer);
322 m_pluginLoadObservers.remove(pos);
325 // Private methods -------------------------------------------------------------
327 WebPluginContainerImpl::~WebPluginContainerImpl()
329 for (size_t i = 0; i < m_pluginLoadObservers.size(); ++i)
330 m_pluginLoadObservers[i]->clearPluginContainer();
331 m_webPlugin->destroy();
334 void WebPluginContainerImpl::handleMouseEvent(MouseEvent* event)
336 ASSERT(parent()->isFrameView());
338 // We cache the parent FrameView here as the plugin widget could be deleted
339 // in the call to HandleEvent. See http://b/issue?id=1362948
340 FrameView* parentView = static_cast<FrameView*>(parent());
342 WebMouseEventBuilder webEvent(parentView, *event);
343 if (webEvent.type == WebInputEvent::Undefined)
346 if (event->type() == eventNames().mousedownEvent) {
347 // Ensure that the frame containing the plugin has focus.
348 Frame* containingFrame = parentView->frame();
349 if (Page* currentPage = containingFrame->page())
350 currentPage->focusController()->setFocusedFrame(containingFrame);
351 // Give focus to our containing HTMLPluginElement.
352 containingFrame->document()->setFocusedNode(m_element);
355 WebCursorInfo cursorInfo;
356 bool handled = m_webPlugin->handleInputEvent(webEvent, cursorInfo);
358 // TODO(pkasting): http://b/1119691 This conditional seems exactly
359 // backwards, but if I reverse it, giving focus to a transparent
360 // (windowless) plugin fails.
362 // TODO(awalker): oddly, the above is not true in Mac builds. Looking
363 // at Apple's corresponding code for Mac and Windows (PluginViewMac and
364 // PluginViewWin), setDefaultHandled() gets called when handleInputEvent()
365 // returns true, which then indicates to WebCore that the plugin wants to
366 // swallow the event--which is what we want. Calling setDefaultHandled()
367 // fixes several Mac Chromium bugs, but does indeed prevent windowless plugins
368 // from getting focus in Windows builds, as pkasting notes above. So for
369 // now, we only do so in Mac builds.
372 event->setDefaultHandled();
374 // A windowless plugin can change the cursor in response to a mouse move
375 // event. We need to reflect the changed cursor in the frame view as the
376 // mouse is moved in the boundaries of the windowless plugin.
377 Page* page = parentView->frame()->page();
380 ChromeClientImpl* chromeClient =
381 static_cast<ChromeClientImpl*>(page->chrome()->client());
382 chromeClient->setCursorForPlugin(cursorInfo);
385 void WebPluginContainerImpl::handleKeyboardEvent(KeyboardEvent* event)
387 WebKeyboardEventBuilder webEvent(*event);
388 if (webEvent.type == WebInputEvent::Undefined)
391 WebCursorInfo cursor_info;
392 bool handled = m_webPlugin->handleInputEvent(webEvent, cursor_info);
394 // TODO(pkasting): http://b/1119691 See above.
398 event->setDefaultHandled();
401 void WebPluginContainerImpl::calculateGeometry(const IntRect& frameRect,
404 Vector<IntRect>& cutOutRects)
406 windowRect = IntRect(
407 parent()->contentsToWindow(frameRect.location()), frameRect.size());
409 // Calculate a clip-rect so that we don't overlap the scrollbars, etc.
410 clipRect = windowClipRect();
411 clipRect.move(-windowRect.x(), -windowRect.y());
413 windowCutOutRects(frameRect, cutOutRects);
414 // Convert to the plugin position.
415 for (size_t i = 0; i < cutOutRects.size(); i++)
416 cutOutRects[i].move(-frameRect.x(), -frameRect.y());
419 WebCore::IntRect WebPluginContainerImpl::windowClipRect() const
421 // Start by clipping to our bounds.
423 convertToContainingWindow(IntRect(0, 0, width(), height()));
425 // document()->renderer() can be 0 when we receive messages from the
426 // plugins while we are destroying a frame.
427 if (m_element->renderer()->document()->renderer()) {
428 // Take our element and get the clip rect from the enclosing layer and
430 RenderLayer* layer = m_element->renderer()->enclosingLayer();
432 m_element->document()->view()->windowClipRectForLayer(layer, true));
438 static void getObjectStack(const RenderObject* ro,
439 Vector<const RenderObject*>* roStack)
448 // Returns true if stack1 is at or above stack2
449 static bool checkStackOnTop(
450 const Vector<const RenderObject*>& iframeZstack,
451 const Vector<const RenderObject*>& pluginZstack)
453 for (size_t i1 = 0, i2 = 0;
454 i1 < iframeZstack.size() && i2 < pluginZstack.size();
456 // The root is at the end of these stacks. We want to iterate
457 // root-downwards so we index backwards from the end.
458 const RenderObject* ro1 = iframeZstack[iframeZstack.size() - 1 - i1];
459 const RenderObject* ro2 = pluginZstack[pluginZstack.size() - 1 - i2];
462 // When we find nodes in the stack that are not the same, then
463 // we've found the nodes just below the lowest comment ancestor.
464 // Determine which should be on top.
466 // See if z-index determines an order.
467 if (ro1->style() && ro2->style()) {
468 int z1 = ro1->style()->zIndex();
469 int z2 = ro2->style()->zIndex();
476 // For compatibility with IE: when the plugin is not positioned,
477 // it stacks behind the iframe, even if it's later in the
479 if (ro2->style()->position() == StaticPosition)
482 // Inspect the document order. Later order means higher
484 const RenderObject* parent = ro1->parent();
487 ASSERT(parent == ro2->parent());
489 for (const RenderObject* ro = parent->firstChild(); ro; ro = ro->nextSibling()) {
495 ASSERT(false); // We should have seen ro1 and ro2 by now.
502 // Return a set of rectangles that should not be overdrawn by the
503 // plugin ("cutouts"). This helps implement the "iframe shim"
504 // technique of overlaying a windowed plugin with content from the
505 // page. In a nutshell, iframe elements should occlude plugins when
506 // they occur higher in the stacking order.
507 void WebPluginContainerImpl::windowCutOutRects(const IntRect& frameRect,
508 Vector<IntRect>& cutOutRects)
510 RenderObject* pluginNode = m_element->renderer();
512 if (!pluginNode->style())
514 Vector<const RenderObject*> pluginZstack;
515 Vector<const RenderObject*> iframeZstack;
516 getObjectStack(pluginNode, &pluginZstack);
518 // Get the parent widget
519 Widget* parentWidget = this->parent();
520 if (!parentWidget->isFrameView())
523 FrameView* parentFrameView = static_cast<FrameView*>(parentWidget);
525 const HashSet<RefPtr<Widget> >* children = parentFrameView->children();
526 for (HashSet<RefPtr<Widget> >::const_iterator it = children->begin(); it != children->end(); ++it) {
527 // We only care about FrameView's because iframes show up as FrameViews.
528 if (!(*it)->isFrameView())
531 const FrameView* frameView =
532 static_cast<const FrameView*>((*it).get());
533 // Check to make sure we can get both the element and the RenderObject
534 // for this FrameView, if we can't just move on to the next object.
535 if (!frameView->frame() || !frameView->frame()->ownerElement()
536 || !frameView->frame()->ownerElement()->renderer())
539 HTMLElement* element = frameView->frame()->ownerElement();
540 RenderObject* iframeRenderer = element->renderer();
542 if (element->hasTagName(HTMLNames::iframeTag)
543 && iframeRenderer->absoluteBoundingBoxRect().intersects(frameRect)
544 && (!iframeRenderer->style() || iframeRenderer->style()->visibility() == VISIBLE)) {
545 getObjectStack(iframeRenderer, &iframeZstack);
546 if (checkStackOnTop(iframeZstack, pluginZstack)) {
548 roundedIntPoint(iframeRenderer->localToAbsolute());
549 RenderBox* rbox = toRenderBox(iframeRenderer);
550 IntSize size(rbox->width(), rbox->height());
551 cutOutRects.append(IntRect(point, size));
557 } // namespace WebKit