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"
34 #include "ChromeClientImpl.h"
35 #include "WebCursorInfo.h"
36 #include "WebDataSourceImpl.h"
37 #include "WebInputEvent.h"
38 #include "WebInputEventConversion.h"
40 #include "WebPlugin.h"
42 #include "WebURLError.h"
43 #include "WebURLRequest.h"
44 #include "WebVector.h"
45 #include "WrappedResourceResponse.h"
47 #include "EventNames.h"
48 #include "FocusController.h"
49 #include "FormState.h"
51 #include "FrameLoadRequest.h"
52 #include "FrameView.h"
53 #include "GraphicsContext.h"
54 #include "HostWindow.h"
55 #include "HTMLFormElement.h"
56 #include "HTMLNames.h"
57 #include "HTMLPlugInElement.h"
58 #include "KeyboardEvent.h"
59 #include "MouseEvent.h"
61 #include "ScrollView.h"
64 #include "PlatformContextSkia.h"
67 using namespace WebCore;
71 // Public methods --------------------------------------------------------------
73 void WebPluginContainerImpl::setFrameRect(const IntRect& frameRect)
75 Widget::setFrameRect(frameRect);
79 void WebPluginContainerImpl::paint(GraphicsContext* gc, const IntRect& damageRect)
81 if (gc->paintingDisabled())
87 // Don't paint anything if the plugin doesn't intersect the damage rect.
88 if (!frameRect().intersects(damageRect))
93 ASSERT(parent()->isFrameView());
94 ScrollView* view = parent();
96 // The plugin is positioned in window coordinates, so it needs to be painted
97 // in window coordinates.
98 IntPoint origin = view->windowToContents(IntPoint(0, 0));
99 gc->translate(static_cast<float>(origin.x()), static_cast<float>(origin.y()));
101 #if WEBKIT_USING_SKIA
102 WebCanvas* canvas = gc->platformContext()->canvas();
103 #elif WEBKIT_USING_CG
104 WebCanvas* canvas = gc->platformContext();
108 IntRect(view->contentsToWindow(damageRect.location()), damageRect.size());
109 m_webPlugin->paint(canvas, windowRect);
114 void WebPluginContainerImpl::invalidateRect(const IntRect& rect)
119 IntRect damageRect = convertToContainingWindow(rect);
121 // Get our clip rect and intersect with it to ensure we don't invalidate
123 IntRect clipRect = parent()->windowClipRect();
124 damageRect.intersect(clipRect);
126 parent()->hostWindow()->repaint(damageRect, true);
129 void WebPluginContainerImpl::setFocus()
132 m_webPlugin->updateFocus(true);
135 void WebPluginContainerImpl::show()
137 setSelfVisible(true);
138 m_webPlugin->updateVisibility(true);
143 void WebPluginContainerImpl::hide()
145 setSelfVisible(false);
146 m_webPlugin->updateVisibility(false);
151 void WebPluginContainerImpl::handleEvent(Event* event)
153 if (!m_webPlugin->acceptsInputEvents())
156 // The events we pass are defined at:
157 // http://devedge-temp.mozilla.org/library/manuals/2002/plugin/1.0/structures5.html#1000000
158 // Don't take the documentation as truth, however. There are many cases
159 // where mozilla behaves differently than the spec.
160 if (event->isMouseEvent())
161 handleMouseEvent(static_cast<MouseEvent*>(event));
162 else if (event->isKeyboardEvent())
163 handleKeyboardEvent(static_cast<KeyboardEvent*>(event));
166 void WebPluginContainerImpl::frameRectsChanged()
168 Widget::frameRectsChanged();
172 void WebPluginContainerImpl::setParentVisible(bool parentVisible)
174 // We override this function to make sure that geometry updates are sent
175 // over to the plugin. For e.g. when a plugin is instantiated it does not
176 // have a valid parent. As a result the first geometry update from webkit
177 // is ignored. This function is called when the plugin eventually gets a
180 if (isParentVisible() == parentVisible)
181 return; // No change.
183 Widget::setParentVisible(parentVisible);
184 if (!isSelfVisible())
185 return; // This widget has explicitely been marked as not visible.
187 m_webPlugin->updateVisibility(isVisible());
190 void WebPluginContainerImpl::setParent(ScrollView* view)
192 // We override this function so that if the plugin is windowed, we can call
193 // NPP_SetWindow at the first possible moment. This ensures that
194 // NPP_SetWindow is called before the manual load data is sent to a plugin.
195 // If this order is reversed, Flash won't load videos.
197 Widget::setParent(view);
202 void WebPluginContainerImpl::invalidate()
204 Widget::invalidate();
207 void WebPluginContainerImpl::invalidateRect(const WebRect& rect)
209 invalidateRect(static_cast<IntRect>(rect));
212 void WebPluginContainerImpl::reportGeometry()
217 IntRect windowRect, clipRect;
218 Vector<IntRect> cutOutRects;
219 calculateGeometry(frameRect(), windowRect, clipRect, cutOutRects);
221 m_webPlugin->updateGeometry(windowRect, clipRect, cutOutRects, isVisible());
224 void WebPluginContainerImpl::clearScriptObjects()
226 Frame* frame = m_element->document()->frame();
229 frame->script()->cleanupScriptObjectsForPlugin(this);
232 NPObject* WebPluginContainerImpl::scriptableObjectForElement()
234 return m_element->getNPObject();
237 WebString WebPluginContainerImpl::executeScriptURL(const WebURL& url, bool popupsAllowed)
239 Frame* frame = m_element->document()->frame();
243 const KURL& kurl = url;
244 ASSERT(kurl.protocolIs("javascript"));
246 String script = decodeURLEscapeSequences(
247 kurl.string().substring(strlen("javascript:")));
249 ScriptValue result = frame->script()->executeScript(script, popupsAllowed);
251 // Failure is reported as a null string.
253 result.getString(resultStr);
257 void WebPluginContainerImpl::loadFrameRequest(
258 const WebURLRequest& request, const WebString& target, bool notifyNeeded, void* notifyData)
260 Frame* frame = m_element->document()->frame();
262 return; // FIXME: send a notification in this case?
265 // FIXME: This is a bit of hack to allow us to observe completion of
266 // our frame request. It would be better to evolve FrameLoader to
267 // support a completion callback instead.
268 WebPluginLoadObserver* observer =
269 new WebPluginLoadObserver(this, request.url(), notifyData);
270 m_pluginLoadObservers.append(observer);
271 WebDataSourceImpl::setNextPluginLoadObserver(observer);
274 FrameLoadRequest frameRequest(request.toResourceRequest());
275 frameRequest.setFrameName(target);
277 frame->loader()->loadFrameRequest(
279 false, // lock history
280 false, // lock back forward list
286 void WebPluginContainerImpl::didReceiveResponse(const ResourceResponse& response)
288 // Make sure that the plugin receives window geometry before data, or else
289 // plugins misbehave.
292 WrappedResourceResponse urlResponse(response);
293 m_webPlugin->didReceiveResponse(urlResponse);
296 void WebPluginContainerImpl::didReceiveData(const char *data, int dataLength)
298 m_webPlugin->didReceiveData(data, dataLength);
301 void WebPluginContainerImpl::didFinishLoading()
303 m_webPlugin->didFinishLoading();
306 void WebPluginContainerImpl::didFailLoading(const ResourceError& error)
308 m_webPlugin->didFailLoading(error);
311 NPObject* WebPluginContainerImpl::scriptableObject()
313 return m_webPlugin->scriptableObject();
316 void WebPluginContainerImpl::willDestroyPluginLoadObserver(WebPluginLoadObserver* observer)
318 size_t pos = m_pluginLoadObservers.find(observer);
321 m_pluginLoadObservers.remove(pos);
324 // Private methods -------------------------------------------------------------
326 WebPluginContainerImpl::~WebPluginContainerImpl()
328 for (size_t i = 0; i < m_pluginLoadObservers.size(); ++i)
329 m_pluginLoadObservers[i]->clearPluginContainer();
330 m_webPlugin->destroy();
333 void WebPluginContainerImpl::handleMouseEvent(MouseEvent* event)
335 ASSERT(parent()->isFrameView());
337 // We cache the parent FrameView here as the plugin widget could be deleted
338 // in the call to HandleEvent. See http://b/issue?id=1362948
339 FrameView* parentView = static_cast<FrameView*>(parent());
341 WebMouseEventBuilder webEvent(parentView, *event);
342 if (webEvent.type == WebInputEvent::Undefined)
345 if (event->type() == eventNames().mousedownEvent) {
346 // Ensure that the frame containing the plugin has focus.
347 Frame* containingFrame = parentView->frame();
348 if (Page* currentPage = containingFrame->page())
349 currentPage->focusController()->setFocusedFrame(containingFrame);
350 // Give focus to our containing HTMLPluginElement.
351 containingFrame->document()->setFocusedNode(m_element);
354 WebCursorInfo cursorInfo;
355 bool handled = m_webPlugin->handleInputEvent(webEvent, cursorInfo);
356 #if !PLATFORM(DARWIN)
357 // TODO(pkasting): http://b/1119691 This conditional seems exactly
358 // backwards, but if I reverse it, giving focus to a transparent
359 // (windowless) plugin fails.
361 // TODO(awalker): oddly, the above is not true in Mac builds. Looking
362 // at Apple's corresponding code for Mac and Windows (PluginViewMac and
363 // PluginViewWin), setDefaultHandled() gets called when handleInputEvent()
364 // returns true, which then indicates to WebCore that the plugin wants to
365 // swallow the event--which is what we want. Calling setDefaultHandled()
366 // fixes several Mac Chromium bugs, but does indeed prevent windowless plugins
367 // from getting focus in Windows builds, as pkasting notes above. So for
368 // now, we only do so in Mac builds.
371 event->setDefaultHandled();
373 // A windowless plugin can change the cursor in response to a mouse move
374 // event. We need to reflect the changed cursor in the frame view as the
375 // mouse is moved in the boundaries of the windowless plugin.
376 Page* page = parentView->frame()->page();
379 ChromeClientImpl* chromeClient =
380 static_cast<ChromeClientImpl*>(page->chrome()->client());
381 chromeClient->setCursorForPlugin(cursorInfo);
384 void WebPluginContainerImpl::handleKeyboardEvent(KeyboardEvent* event)
386 WebKeyboardEventBuilder webEvent(*event);
387 if (webEvent.type == WebInputEvent::Undefined)
390 WebCursorInfo cursor_info;
391 bool handled = m_webPlugin->handleInputEvent(webEvent, cursor_info);
392 #if !PLATFORM(DARWIN)
393 // TODO(pkasting): http://b/1119691 See above.
397 event->setDefaultHandled();
400 void WebPluginContainerImpl::calculateGeometry(const IntRect& frameRect,
403 Vector<IntRect>& cutOutRects)
405 windowRect = IntRect(
406 parent()->contentsToWindow(frameRect.location()), frameRect.size());
408 // Calculate a clip-rect so that we don't overlap the scrollbars, etc.
409 clipRect = windowClipRect();
410 clipRect.move(-windowRect.x(), -windowRect.y());
412 windowCutOutRects(frameRect, cutOutRects);
413 // Convert to the plugin position.
414 for (size_t i = 0; i < cutOutRects.size(); i++)
415 cutOutRects[i].move(-frameRect.x(), -frameRect.y());
418 WebCore::IntRect WebPluginContainerImpl::windowClipRect() const
420 // Start by clipping to our bounds.
422 convertToContainingWindow(IntRect(0, 0, width(), height()));
424 // document()->renderer() can be 0 when we receive messages from the
425 // plugins while we are destroying a frame.
426 if (m_element->renderer()->document()->renderer()) {
427 // Take our element and get the clip rect from the enclosing layer and
429 RenderLayer* layer = m_element->renderer()->enclosingLayer();
431 m_element->document()->view()->windowClipRectForLayer(layer, true));
437 static void getObjectStack(const RenderObject* ro,
438 Vector<const RenderObject*>* roStack)
447 // Returns true if stack1 is at or above stack2
448 static bool checkStackOnTop(
449 const Vector<const RenderObject*>& iframeZstack,
450 const Vector<const RenderObject*>& pluginZstack)
452 for (size_t i1 = 0, i2 = 0;
453 i1 < iframeZstack.size() && i2 < pluginZstack.size();
455 // The root is at the end of these stacks. We want to iterate
456 // root-downwards so we index backwards from the end.
457 const RenderObject* ro1 = iframeZstack[iframeZstack.size() - 1 - i1];
458 const RenderObject* ro2 = pluginZstack[pluginZstack.size() - 1 - i2];
461 // When we find nodes in the stack that are not the same, then
462 // we've found the nodes just below the lowest comment ancestor.
463 // Determine which should be on top.
465 // See if z-index determines an order.
466 if (ro1->style() && ro2->style()) {
467 int z1 = ro1->style()->zIndex();
468 int z2 = ro2->style()->zIndex();
475 // For compatibility with IE: when the plugin is not positioned,
476 // it stacks behind the iframe, even if it's later in the
478 if (ro2->style()->position() == StaticPosition)
481 // Inspect the document order. Later order means higher
483 const RenderObject* parent = ro1->parent();
486 ASSERT(parent == ro2->parent());
488 for (const RenderObject* ro = parent->firstChild(); ro; ro = ro->nextSibling()) {
494 ASSERT(false); // We should have seen ro1 and ro2 by now.
501 // Return a set of rectangles that should not be overdrawn by the
502 // plugin ("cutouts"). This helps implement the "iframe shim"
503 // technique of overlaying a windowed plugin with content from the
504 // page. In a nutshell, iframe elements should occlude plugins when
505 // they occur higher in the stacking order.
506 void WebPluginContainerImpl::windowCutOutRects(const IntRect& frameRect,
507 Vector<IntRect>& cutOutRects)
509 RenderObject* pluginNode = m_element->renderer();
511 if (!pluginNode->style())
513 Vector<const RenderObject*> pluginZstack;
514 Vector<const RenderObject*> iframeZstack;
515 getObjectStack(pluginNode, &pluginZstack);
517 // Get the parent widget
518 Widget* parentWidget = this->parent();
519 if (!parentWidget->isFrameView())
522 FrameView* parentFrameView = static_cast<FrameView*>(parentWidget);
524 const HashSet<RefPtr<Widget> >* children = parentFrameView->children();
525 for (HashSet<RefPtr<Widget> >::const_iterator it = children->begin(); it != children->end(); ++it) {
526 // We only care about FrameView's because iframes show up as FrameViews.
527 if (!(*it)->isFrameView())
530 const FrameView* frameView =
531 static_cast<const FrameView*>((*it).get());
532 // Check to make sure we can get both the element and the RenderObject
533 // for this FrameView, if we can't just move on to the next object.
534 if (!frameView->frame() || !frameView->frame()->ownerElement()
535 || !frameView->frame()->ownerElement()->renderer())
538 HTMLElement* element = frameView->frame()->ownerElement();
539 RenderObject* iframeRenderer = element->renderer();
541 if (element->hasTagName(HTMLNames::iframeTag)
542 && iframeRenderer->absoluteBoundingBoxRect().intersects(frameRect)
543 && (!iframeRenderer->style() || iframeRenderer->style()->visibility() == VISIBLE)) {
544 getObjectStack(iframeRenderer, &iframeZstack);
545 if (checkStackOnTop(iframeZstack, pluginZstack)) {
547 roundedIntPoint(iframeRenderer->localToAbsolute());
548 RenderBox* rbox = toRenderBox(iframeRenderer);
549 IntSize size(rbox->width(), rbox->height());
550 cutOutRects.append(IntRect(point, size));
556 } // namespace WebKit