OSDN Git Service

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