• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2009 Google Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
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
13  * distribution.
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.
17  *
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.
29  */
30 
31 #include "config.h"
32 #include "WebPluginContainerImpl.h"
33 
34 #include "Chrome.h"
35 #include "ChromeClientImpl.h"
36 #include "WebCursorInfo.h"
37 #include "WebDataSourceImpl.h"
38 #include "WebInputEvent.h"
39 #include "WebInputEventConversion.h"
40 #include "WebKit.h"
41 #include "WebPlugin.h"
42 #include "WebRect.h"
43 #include "WebURLError.h"
44 #include "WebURLRequest.h"
45 #include "WebVector.h"
46 #include "WrappedResourceResponse.h"
47 
48 #include "EventNames.h"
49 #include "FocusController.h"
50 #include "FormState.h"
51 #include "Frame.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"
61 #include "Page.h"
62 #include "ScrollView.h"
63 
64 #if WEBKIT_USING_SKIA
65 #include "PlatformContextSkia.h"
66 #endif
67 
68 using namespace WebCore;
69 
70 namespace WebKit {
71 
72 // Public methods --------------------------------------------------------------
73 
setFrameRect(const IntRect & frameRect)74 void WebPluginContainerImpl::setFrameRect(const IntRect& frameRect)
75 {
76     Widget::setFrameRect(frameRect);
77     reportGeometry();
78 }
79 
paint(GraphicsContext * gc,const IntRect & damageRect)80 void WebPluginContainerImpl::paint(GraphicsContext* gc, const IntRect& damageRect)
81 {
82     if (gc->paintingDisabled())
83         return;
84 
85     if (!parent())
86         return;
87 
88     // Don't paint anything if the plugin doesn't intersect the damage rect.
89     if (!frameRect().intersects(damageRect))
90         return;
91 
92     gc->save();
93 
94     ASSERT(parent()->isFrameView());
95     ScrollView* view = parent();
96 
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()));
101 
102 #if WEBKIT_USING_SKIA
103     WebCanvas* canvas = gc->platformContext()->canvas();
104 #elif WEBKIT_USING_CG
105     WebCanvas* canvas = gc->platformContext();
106 #endif
107 
108     IntRect windowRect =
109         IntRect(view->contentsToWindow(damageRect.location()), damageRect.size());
110     m_webPlugin->paint(canvas, windowRect);
111 
112     gc->restore();
113 }
114 
invalidateRect(const IntRect & rect)115 void WebPluginContainerImpl::invalidateRect(const IntRect& rect)
116 {
117     if (!parent())
118         return;
119 
120     IntRect damageRect = convertToContainingWindow(rect);
121 
122     // Get our clip rect and intersect with it to ensure we don't invalidate
123     // too much.
124     IntRect clipRect = parent()->windowClipRect();
125     damageRect.intersect(clipRect);
126 
127     parent()->hostWindow()->repaint(damageRect, true);
128 }
129 
setFocus()130 void WebPluginContainerImpl::setFocus()
131 {
132     Widget::setFocus();
133     m_webPlugin->updateFocus(true);
134 }
135 
show()136 void WebPluginContainerImpl::show()
137 {
138     setSelfVisible(true);
139     m_webPlugin->updateVisibility(true);
140 
141     Widget::show();
142 }
143 
hide()144 void WebPluginContainerImpl::hide()
145 {
146     setSelfVisible(false);
147     m_webPlugin->updateVisibility(false);
148 
149     Widget::hide();
150 }
151 
handleEvent(Event * event)152 void WebPluginContainerImpl::handleEvent(Event* event)
153 {
154     if (!m_webPlugin->acceptsInputEvents())
155         return;
156 
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));
165 }
166 
frameRectsChanged()167 void WebPluginContainerImpl::frameRectsChanged()
168 {
169     Widget::frameRectsChanged();
170     reportGeometry();
171 }
172 
setParentVisible(bool parentVisible)173 void WebPluginContainerImpl::setParentVisible(bool parentVisible)
174 {
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
179     // parent.
180 
181     if (isParentVisible() == parentVisible)
182         return;  // No change.
183 
184     Widget::setParentVisible(parentVisible);
185     if (!isSelfVisible())
186         return;  // This widget has explicitely been marked as not visible.
187 
188     m_webPlugin->updateVisibility(isVisible());
189 }
190 
setParent(ScrollView * view)191 void WebPluginContainerImpl::setParent(ScrollView* view)
192 {
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.
197 
198     Widget::setParent(view);
199     if (view)
200         reportGeometry();
201 }
202 
invalidate()203 void WebPluginContainerImpl::invalidate()
204 {
205     Widget::invalidate();
206 }
207 
invalidateRect(const WebRect & rect)208 void WebPluginContainerImpl::invalidateRect(const WebRect& rect)
209 {
210     invalidateRect(static_cast<IntRect>(rect));
211 }
212 
reportGeometry()213 void WebPluginContainerImpl::reportGeometry()
214 {
215     if (!parent())
216         return;
217 
218     IntRect windowRect, clipRect;
219     Vector<IntRect> cutOutRects;
220     calculateGeometry(frameRect(), windowRect, clipRect, cutOutRects);
221 
222     m_webPlugin->updateGeometry(windowRect, clipRect, cutOutRects, isVisible());
223 }
224 
clearScriptObjects()225 void WebPluginContainerImpl::clearScriptObjects()
226 {
227     Frame* frame = m_element->document()->frame();
228     if (!frame)
229         return;
230     frame->script()->cleanupScriptObjectsForPlugin(this);
231 }
232 
scriptableObjectForElement()233 NPObject* WebPluginContainerImpl::scriptableObjectForElement()
234 {
235     return m_element->getNPObject();
236 }
237 
executeScriptURL(const WebURL & url,bool popupsAllowed)238 WebString WebPluginContainerImpl::executeScriptURL(const WebURL& url, bool popupsAllowed)
239 {
240     Frame* frame = m_element->document()->frame();
241     if (!frame)
242         return WebString();
243 
244     const KURL& kurl = url;
245     ASSERT(kurl.protocolIs("javascript"));
246 
247     String script = decodeURLEscapeSequences(
248         kurl.string().substring(strlen("javascript:")));
249 
250     ScriptValue result = frame->script()->executeScript(script, popupsAllowed);
251 
252     // Failure is reported as a null string.
253     String resultStr;
254     result.getString(resultStr);
255     return resultStr;
256 }
257 
loadFrameRequest(const WebURLRequest & request,const WebString & target,bool notifyNeeded,void * notifyData)258 void WebPluginContainerImpl::loadFrameRequest(
259     const WebURLRequest& request, const WebString& target, bool notifyNeeded, void* notifyData)
260 {
261     Frame* frame = m_element->document()->frame();
262     if (!frame)
263         return;  // FIXME: send a notification in this case?
264 
265     if (notifyNeeded) {
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);
273     }
274 
275     FrameLoadRequest frameRequest(request.toResourceRequest());
276     frameRequest.setFrameName(target);
277 
278     frame->loader()->loadFrameRequest(
279         frameRequest,
280         false,  // lock history
281         false,  // lock back forward list
282         0,      // event
283         0,     // form state
284         SendReferrer);
285 }
286 
didReceiveResponse(const ResourceResponse & response)287 void WebPluginContainerImpl::didReceiveResponse(const ResourceResponse& response)
288 {
289     // Make sure that the plugin receives window geometry before data, or else
290     // plugins misbehave.
291     frameRectsChanged();
292 
293     WrappedResourceResponse urlResponse(response);
294     m_webPlugin->didReceiveResponse(urlResponse);
295 }
296 
didReceiveData(const char * data,int dataLength)297 void WebPluginContainerImpl::didReceiveData(const char *data, int dataLength)
298 {
299     m_webPlugin->didReceiveData(data, dataLength);
300 }
301 
didFinishLoading()302 void WebPluginContainerImpl::didFinishLoading()
303 {
304     m_webPlugin->didFinishLoading();
305 }
306 
didFailLoading(const ResourceError & error)307 void WebPluginContainerImpl::didFailLoading(const ResourceError& error)
308 {
309     m_webPlugin->didFailLoading(error);
310 }
311 
scriptableObject()312 NPObject* WebPluginContainerImpl::scriptableObject()
313 {
314     return m_webPlugin->scriptableObject();
315 }
316 
willDestroyPluginLoadObserver(WebPluginLoadObserver * observer)317 void WebPluginContainerImpl::willDestroyPluginLoadObserver(WebPluginLoadObserver* observer)
318 {
319     size_t pos = m_pluginLoadObservers.find(observer);
320     if (pos == notFound)
321         return;
322     m_pluginLoadObservers.remove(pos);
323 }
324 
325 // Private methods -------------------------------------------------------------
326 
~WebPluginContainerImpl()327 WebPluginContainerImpl::~WebPluginContainerImpl()
328 {
329     for (size_t i = 0; i < m_pluginLoadObservers.size(); ++i)
330         m_pluginLoadObservers[i]->clearPluginContainer();
331     m_webPlugin->destroy();
332 }
333 
handleMouseEvent(MouseEvent * event)334 void WebPluginContainerImpl::handleMouseEvent(MouseEvent* event)
335 {
336     ASSERT(parent()->isFrameView());
337 
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());
341 
342     WebMouseEventBuilder webEvent(parentView, *event);
343     if (webEvent.type == WebInputEvent::Undefined)
344         return;
345 
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);
353     }
354 
355     WebCursorInfo cursorInfo;
356     bool handled = m_webPlugin->handleInputEvent(webEvent, cursorInfo);
357 #if !OS(DARWIN)
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.
361     handled = !handled;
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.
370 #endif
371     if (handled)
372         event->setDefaultHandled();
373 
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();
378     if (!page)
379         return;
380     ChromeClientImpl* chromeClient =
381         static_cast<ChromeClientImpl*>(page->chrome()->client());
382     chromeClient->setCursorForPlugin(cursorInfo);
383 }
384 
handleKeyboardEvent(KeyboardEvent * event)385 void WebPluginContainerImpl::handleKeyboardEvent(KeyboardEvent* event)
386 {
387     WebKeyboardEventBuilder webEvent(*event);
388     if (webEvent.type == WebInputEvent::Undefined)
389         return;
390 
391     WebCursorInfo cursor_info;
392     bool handled = m_webPlugin->handleInputEvent(webEvent, cursor_info);
393 #if !OS(DARWIN)
394     // TODO(pkasting): http://b/1119691 See above.
395     handled = !handled;
396 #endif
397     if (handled)
398         event->setDefaultHandled();
399 }
400 
calculateGeometry(const IntRect & frameRect,IntRect & windowRect,IntRect & clipRect,Vector<IntRect> & cutOutRects)401 void WebPluginContainerImpl::calculateGeometry(const IntRect& frameRect,
402                                                IntRect& windowRect,
403                                                IntRect& clipRect,
404                                                Vector<IntRect>& cutOutRects)
405 {
406     windowRect = IntRect(
407         parent()->contentsToWindow(frameRect.location()), frameRect.size());
408 
409     // Calculate a clip-rect so that we don't overlap the scrollbars, etc.
410     clipRect = windowClipRect();
411     clipRect.move(-windowRect.x(), -windowRect.y());
412 
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());
417 }
418 
windowClipRect() const419 WebCore::IntRect WebPluginContainerImpl::windowClipRect() const
420 {
421     // Start by clipping to our bounds.
422     IntRect clipRect =
423         convertToContainingWindow(IntRect(0, 0, width(), height()));
424 
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
429         // frame view.
430         RenderLayer* layer = m_element->renderer()->enclosingLayer();
431         clipRect.intersect(
432             m_element->document()->view()->windowClipRectForLayer(layer, true));
433     }
434 
435     return clipRect;
436 }
437 
getObjectStack(const RenderObject * ro,Vector<const RenderObject * > * roStack)438 static void getObjectStack(const RenderObject* ro,
439                            Vector<const RenderObject*>* roStack)
440 {
441     roStack->clear();
442     while (ro) {
443         roStack->append(ro);
444         ro = ro->parent();
445     }
446 }
447 
448 // Returns true if stack1 is at or above stack2
checkStackOnTop(const Vector<const RenderObject * > & iframeZstack,const Vector<const RenderObject * > & pluginZstack)449 static bool checkStackOnTop(
450         const Vector<const RenderObject*>& iframeZstack,
451         const Vector<const RenderObject*>& pluginZstack)
452 {
453     for (size_t i1 = 0, i2 = 0;
454          i1 < iframeZstack.size() && i2 < pluginZstack.size();
455          i1++, i2++) {
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];
460 
461         if (ro1 != ro2) {
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.
465 
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();
470                 if (z1 > z2)
471                     return true;
472                 if (z1 < z2)
473                     return false;
474             }
475 
476             // For compatibility with IE: when the plugin is not positioned,
477             // it stacks behind the iframe, even if it's later in the
478             // document order.
479             if (ro2->style()->position() == StaticPosition)
480                 return true;
481 
482             // Inspect the document order.  Later order means higher
483             // stacking.
484             const RenderObject* parent = ro1->parent();
485             if (!parent)
486                 return false;
487             ASSERT(parent == ro2->parent());
488 
489             for (const RenderObject* ro = parent->firstChild(); ro; ro = ro->nextSibling()) {
490                 if (ro == ro1)
491                     return false;
492                 if (ro == ro2)
493                     return true;
494             }
495             ASSERT(false);  // We should have seen ro1 and ro2 by now.
496             return false;
497         }
498     }
499     return true;
500 }
501 
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.
windowCutOutRects(const IntRect & frameRect,Vector<IntRect> & cutOutRects)507 void WebPluginContainerImpl::windowCutOutRects(const IntRect& frameRect,
508                                                Vector<IntRect>& cutOutRects)
509 {
510     RenderObject* pluginNode = m_element->renderer();
511     ASSERT(pluginNode);
512     if (!pluginNode->style())
513         return;
514     Vector<const RenderObject*> pluginZstack;
515     Vector<const RenderObject*> iframeZstack;
516     getObjectStack(pluginNode, &pluginZstack);
517 
518     // Get the parent widget
519     Widget* parentWidget = this->parent();
520     if (!parentWidget->isFrameView())
521         return;
522 
523     FrameView* parentFrameView = static_cast<FrameView*>(parentWidget);
524 
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())
529             continue;
530 
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())
537             continue;
538 
539         HTMLElement* element = frameView->frame()->ownerElement();
540         RenderObject* iframeRenderer = element->renderer();
541 
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)) {
547                 IntPoint point =
548                     roundedIntPoint(iframeRenderer->localToAbsolute());
549                 RenderBox* rbox = toRenderBox(iframeRenderer);
550                 IntSize size(rbox->width(), rbox->height());
551                 cutOutRects.append(IntRect(point, size));
552             }
553         }
554     }
555 }
556 
557 } // namespace WebKit
558