OSDN Git Service

Merge "Initial messaging model for project 'smoke'"
[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 "Chrome.h"
35 #include "ChromeClientImpl.h"
36 #include "WebCursorInfo.h"
37 #include "WebDataSourceImpl.h"
38 #include "WebElement.h"
39 #include "WebInputEvent.h"
40 #include "WebInputEventConversion.h"
41 #include "WebKit.h"
42 #include "WebPlugin.h"
43 #include "WebRect.h"
44 #include "WebURLError.h"
45 #include "WebURLRequest.h"
46 #include "WebVector.h"
47 #include "WrappedResourceResponse.h"
48
49 #include "EventNames.h"
50 #include "FocusController.h"
51 #include "FormState.h"
52 #include "Frame.h"
53 #include "FrameLoadRequest.h"
54 #include "FrameView.h"
55 #include "GraphicsContext.h"
56 #include "HostWindow.h"
57 #include "HTMLFormElement.h"
58 #include "HTMLNames.h"
59 #include "HTMLPlugInElement.h"
60 #include "KeyboardEvent.h"
61 #include "MouseEvent.h"
62 #include "Page.h"
63 #include "RenderBox.h"
64 #include "ScrollView.h"
65 #include "WheelEvent.h"
66
67 #if WEBKIT_USING_SKIA
68 #include "PlatformContextSkia.h"
69 #endif
70
71 using namespace WebCore;
72
73 namespace WebKit {
74
75 // Public methods --------------------------------------------------------------
76
77 void WebPluginContainerImpl::setFrameRect(const IntRect& frameRect)
78 {
79     Widget::setFrameRect(frameRect);
80     reportGeometry();
81 }
82
83 void WebPluginContainerImpl::paint(GraphicsContext* gc, const IntRect& damageRect)
84 {
85     if (gc->paintingDisabled())
86         return;
87
88     if (!parent())
89         return;
90
91     // Don't paint anything if the plugin doesn't intersect the damage rect.
92     if (!frameRect().intersects(damageRect))
93         return;
94
95     gc->save();
96
97     ASSERT(parent()->isFrameView());
98     ScrollView* view = parent();
99
100     // The plugin is positioned in window coordinates, so it needs to be painted
101     // in window coordinates.
102     IntPoint origin = view->windowToContents(IntPoint(0, 0));
103     gc->translate(static_cast<float>(origin.x()), static_cast<float>(origin.y()));
104
105 #if WEBKIT_USING_SKIA
106     WebCanvas* canvas = gc->platformContext()->canvas();
107 #elif WEBKIT_USING_CG
108     WebCanvas* canvas = gc->platformContext();
109 #endif
110
111     IntRect windowRect =
112         IntRect(view->contentsToWindow(damageRect.location()), damageRect.size());
113     m_webPlugin->paint(canvas, windowRect);
114
115     gc->restore();
116 }
117
118 void WebPluginContainerImpl::invalidateRect(const IntRect& rect)
119 {
120     if (!parent())
121         return;
122
123     IntRect damageRect = convertToContainingWindow(rect);
124
125     // Get our clip rect and intersect with it to ensure we don't invalidate
126     // too much.
127     IntRect clipRect = parent()->windowClipRect();
128     damageRect.intersect(clipRect);
129
130     parent()->hostWindow()->invalidateContentsAndWindow(damageRect, false /*immediate*/);
131 }
132
133 void WebPluginContainerImpl::setFocus(bool focused)
134 {
135     Widget::setFocus(focused);
136     m_webPlugin->updateFocus(focused);
137 }
138
139 void WebPluginContainerImpl::show()
140 {
141     setSelfVisible(true);
142     m_webPlugin->updateVisibility(true);
143
144     Widget::show();
145 }
146
147 void WebPluginContainerImpl::hide()
148 {
149     setSelfVisible(false);
150     m_webPlugin->updateVisibility(false);
151
152     Widget::hide();
153 }
154
155 void WebPluginContainerImpl::handleEvent(Event* event)
156 {
157     if (!m_webPlugin->acceptsInputEvents())
158         return;
159
160     // The events we pass are defined at:
161     //    http://devedge-temp.mozilla.org/library/manuals/2002/plugin/1.0/structures5.html#1000000
162     // Don't take the documentation as truth, however.  There are many cases
163     // where mozilla behaves differently than the spec.
164     if (event->isMouseEvent())
165         handleMouseEvent(static_cast<MouseEvent*>(event));
166     else if (event->isWheelEvent())
167         handleWheelEvent(static_cast<WheelEvent*>(event));
168     else if (event->isKeyboardEvent())
169         handleKeyboardEvent(static_cast<KeyboardEvent*>(event));
170 }
171
172 void WebPluginContainerImpl::frameRectsChanged()
173 {
174     Widget::frameRectsChanged();
175     reportGeometry();
176 }
177
178 void WebPluginContainerImpl::widgetPositionsUpdated()
179 {
180     Widget::widgetPositionsUpdated();
181     reportGeometry();
182 }
183
184 void WebPluginContainerImpl::setParentVisible(bool parentVisible)
185 {
186     // We override this function to make sure that geometry updates are sent
187     // over to the plugin. For e.g. when a plugin is instantiated it does not
188     // have a valid parent. As a result the first geometry update from webkit
189     // is ignored. This function is called when the plugin eventually gets a
190     // parent.
191
192     if (isParentVisible() == parentVisible)
193         return;  // No change.
194
195     Widget::setParentVisible(parentVisible);
196     if (!isSelfVisible())
197         return;  // This widget has explicitely been marked as not visible.
198
199     m_webPlugin->updateVisibility(isVisible());
200 }
201
202 void WebPluginContainerImpl::setParent(ScrollView* view)
203 {
204     // We override this function so that if the plugin is windowed, we can call
205     // NPP_SetWindow at the first possible moment.  This ensures that
206     // NPP_SetWindow is called before the manual load data is sent to a plugin.
207     // If this order is reversed, Flash won't load videos.
208
209     Widget::setParent(view);
210     if (view)
211         reportGeometry();
212 }
213
214 bool WebPluginContainerImpl::supportsPaginatedPrint() const
215 {
216     return m_webPlugin->supportsPaginatedPrint();
217 }
218
219 int WebPluginContainerImpl::printBegin(const IntRect& printableArea,
220                                        int printerDPI) const
221 {
222     return m_webPlugin->printBegin(printableArea, printerDPI);
223 }
224
225 bool WebPluginContainerImpl::printPage(int pageNumber,
226                                        WebCore::GraphicsContext* gc)
227 {
228     gc->save();
229 #if WEBKIT_USING_SKIA
230     WebCanvas* canvas = gc->platformContext()->canvas();
231 #elif WEBKIT_USING_CG
232     WebCanvas* canvas = gc->platformContext();
233 #endif
234     bool ret = m_webPlugin->printPage(pageNumber, canvas);
235     gc->restore();
236     return ret;
237 }
238
239 void WebPluginContainerImpl::printEnd()
240 {
241     return m_webPlugin->printEnd();
242 }
243
244 WebElement WebPluginContainerImpl::element()
245 {
246     return WebElement(m_element);
247 }
248
249 void WebPluginContainerImpl::invalidate()
250 {
251     Widget::invalidate();
252 }
253
254 void WebPluginContainerImpl::invalidateRect(const WebRect& rect)
255 {
256     invalidateRect(static_cast<IntRect>(rect));
257 }
258
259 void WebPluginContainerImpl::reportGeometry()
260 {
261     if (!parent())
262         return;
263
264     IntRect windowRect, clipRect;
265     Vector<IntRect> cutOutRects;
266     calculateGeometry(frameRect(), windowRect, clipRect, cutOutRects);
267
268     m_webPlugin->updateGeometry(windowRect, clipRect, cutOutRects, isVisible());
269 }
270
271 void WebPluginContainerImpl::clearScriptObjects()
272 {
273     Frame* frame = m_element->document()->frame();
274     if (!frame)
275         return;
276     frame->script()->cleanupScriptObjectsForPlugin(this);
277 }
278
279 NPObject* WebPluginContainerImpl::scriptableObjectForElement()
280 {
281     return m_element->getNPObject();
282 }
283
284 WebString WebPluginContainerImpl::executeScriptURL(const WebURL& url, bool popupsAllowed)
285 {
286     Frame* frame = m_element->document()->frame();
287     if (!frame)
288         return WebString();
289
290     const KURL& kurl = url;
291     ASSERT(kurl.protocolIs("javascript"));
292
293     String script = decodeURLEscapeSequences(
294         kurl.string().substring(strlen("javascript:")));
295
296     ScriptValue result = frame->script()->executeScript(script, popupsAllowed);
297
298     // Failure is reported as a null string.
299     String resultStr;
300     result.getString(resultStr);
301     return resultStr;
302 }
303
304 void WebPluginContainerImpl::loadFrameRequest(
305     const WebURLRequest& request, const WebString& target, bool notifyNeeded, void* notifyData)
306 {
307     Frame* frame = m_element->document()->frame();
308     if (!frame)
309         return;  // FIXME: send a notification in this case?
310
311     if (notifyNeeded) {
312         // FIXME: This is a bit of hack to allow us to observe completion of
313         // our frame request.  It would be better to evolve FrameLoader to
314         // support a completion callback instead.
315         WebPluginLoadObserver* observer =
316             new WebPluginLoadObserver(this, request.url(), notifyData);
317         m_pluginLoadObservers.append(observer);
318         WebDataSourceImpl::setNextPluginLoadObserver(observer);
319     }
320
321     FrameLoadRequest frameRequest(request.toResourceRequest());
322     frameRequest.setFrameName(target);
323
324     frame->loader()->loadFrameRequest(
325         frameRequest,
326         false,  // lock history
327         false,  // lock back forward list
328         0,      // event
329         0,     // form state
330         SendReferrer);
331 }
332
333 void WebPluginContainerImpl::didReceiveResponse(const ResourceResponse& response)
334 {
335     // Make sure that the plugin receives window geometry before data, or else
336     // plugins misbehave.
337     frameRectsChanged();
338
339     WrappedResourceResponse urlResponse(response);
340     m_webPlugin->didReceiveResponse(urlResponse);
341 }
342
343 void WebPluginContainerImpl::didReceiveData(const char *data, int dataLength)
344 {
345     m_webPlugin->didReceiveData(data, dataLength);
346 }
347
348 void WebPluginContainerImpl::didFinishLoading()
349 {
350     m_webPlugin->didFinishLoading();
351 }
352
353 void WebPluginContainerImpl::didFailLoading(const ResourceError& error)
354 {
355     m_webPlugin->didFailLoading(error);
356 }
357
358 NPObject* WebPluginContainerImpl::scriptableObject()
359 {
360     return m_webPlugin->scriptableObject();
361 }
362
363 void WebPluginContainerImpl::willDestroyPluginLoadObserver(WebPluginLoadObserver* observer)
364 {
365     size_t pos = m_pluginLoadObservers.find(observer);
366     if (pos == notFound)
367         return;
368     m_pluginLoadObservers.remove(pos);
369 }
370
371 // Private methods -------------------------------------------------------------
372
373 WebPluginContainerImpl::~WebPluginContainerImpl()
374 {
375     for (size_t i = 0; i < m_pluginLoadObservers.size(); ++i)
376         m_pluginLoadObservers[i]->clearPluginContainer();
377     m_webPlugin->destroy();
378 }
379
380 void WebPluginContainerImpl::handleMouseEvent(MouseEvent* event)
381 {
382     ASSERT(parent()->isFrameView());
383
384     // We cache the parent FrameView here as the plugin widget could be deleted
385     // in the call to HandleEvent. See http://b/issue?id=1362948
386     FrameView* parentView = static_cast<FrameView*>(parent());
387
388     WebMouseEventBuilder webEvent(parentView, *event);
389     if (webEvent.type == WebInputEvent::Undefined)
390         return;
391
392     if (event->type() == eventNames().mousedownEvent) {
393         // Ensure that the frame containing the plugin has focus.
394         Frame* containingFrame = parentView->frame();
395         if (Page* currentPage = containingFrame->page())
396             currentPage->focusController()->setFocusedFrame(containingFrame);
397         // Give focus to our containing HTMLPluginElement.
398         containingFrame->document()->setFocusedNode(m_element);
399     }
400
401     WebCursorInfo cursorInfo;
402     if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
403         event->setDefaultHandled();
404
405     // A windowless plugin can change the cursor in response to a mouse move
406     // event.  We need to reflect the changed cursor in the frame view as the
407     // mouse is moved in the boundaries of the windowless plugin.
408     Page* page = parentView->frame()->page();
409     if (!page)
410         return;
411     ChromeClientImpl* chromeClient =
412         static_cast<ChromeClientImpl*>(page->chrome()->client());
413     chromeClient->setCursorForPlugin(cursorInfo);
414 }
415
416 void WebPluginContainerImpl::handleWheelEvent(WheelEvent* event)
417 {
418     FrameView* parentView = static_cast<FrameView*>(parent());
419     WebMouseWheelEventBuilder webEvent(parentView, *event);
420     if (webEvent.type == WebInputEvent::Undefined)
421         return;
422
423     WebCursorInfo cursorInfo;
424     if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
425         event->setDefaultHandled();
426 }
427
428 void WebPluginContainerImpl::handleKeyboardEvent(KeyboardEvent* event)
429 {
430     WebKeyboardEventBuilder webEvent(*event);
431     if (webEvent.type == WebInputEvent::Undefined)
432         return;
433
434     WebCursorInfo cursorInfo;
435     if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
436         event->setDefaultHandled();
437 }
438
439 void WebPluginContainerImpl::calculateGeometry(const IntRect& frameRect,
440                                                IntRect& windowRect,
441                                                IntRect& clipRect,
442                                                Vector<IntRect>& cutOutRects)
443 {
444     windowRect = IntRect(
445         parent()->contentsToWindow(frameRect.location()), frameRect.size());
446
447     // Calculate a clip-rect so that we don't overlap the scrollbars, etc.
448     clipRect = windowClipRect();
449     clipRect.move(-windowRect.x(), -windowRect.y());
450
451     windowCutOutRects(frameRect, cutOutRects);
452     // Convert to the plugin position.
453     for (size_t i = 0; i < cutOutRects.size(); i++)
454         cutOutRects[i].move(-frameRect.x(), -frameRect.y());
455 }
456
457 WebCore::IntRect WebPluginContainerImpl::windowClipRect() const
458 {
459     // Start by clipping to our bounds.
460     IntRect clipRect =
461         convertToContainingWindow(IntRect(0, 0, width(), height()));
462
463     // document()->renderer() can be 0 when we receive messages from the
464     // plugins while we are destroying a frame.
465     if (m_element->renderer()->document()->renderer()) {
466         // Take our element and get the clip rect from the enclosing layer and
467         // frame view.
468         RenderLayer* layer = m_element->renderer()->enclosingLayer();
469         clipRect.intersect(
470             m_element->document()->view()->windowClipRectForLayer(layer, true));
471     }
472
473     return clipRect;
474 }
475
476 static void getObjectStack(const RenderObject* ro,
477                            Vector<const RenderObject*>* roStack)
478 {
479     roStack->clear();
480     while (ro) {
481         roStack->append(ro);
482         ro = ro->parent();
483     }
484 }
485
486 // Returns true if stack1 is at or above stack2
487 static bool checkStackOnTop(
488         const Vector<const RenderObject*>& iframeZstack,
489         const Vector<const RenderObject*>& pluginZstack)
490 {
491     for (size_t i1 = 0, i2 = 0;
492          i1 < iframeZstack.size() && i2 < pluginZstack.size();
493          i1++, i2++) {
494         // The root is at the end of these stacks.  We want to iterate
495         // root-downwards so we index backwards from the end.
496         const RenderObject* ro1 = iframeZstack[iframeZstack.size() - 1 - i1];
497         const RenderObject* ro2 = pluginZstack[pluginZstack.size() - 1 - i2];
498
499         if (ro1 != ro2) {
500             // When we find nodes in the stack that are not the same, then
501             // we've found the nodes just below the lowest comment ancestor.
502             // Determine which should be on top.
503
504             // See if z-index determines an order.
505             if (ro1->style() && ro2->style()) {
506                 int z1 = ro1->style()->zIndex();
507                 int z2 = ro2->style()->zIndex();
508                 if (z1 > z2)
509                     return true;
510                 if (z1 < z2)
511                     return false;
512             }
513
514             // For compatibility with IE: when the plugin is not positioned,
515             // it stacks behind the iframe, even if it's later in the
516             // document order.
517             if (ro2->style()->position() == StaticPosition)
518                 return true;
519
520             // Inspect the document order.  Later order means higher
521             // stacking.
522             const RenderObject* parent = ro1->parent();
523             if (!parent)
524                 return false;
525             ASSERT(parent == ro2->parent());
526
527             for (const RenderObject* ro = parent->firstChild(); ro; ro = ro->nextSibling()) {
528                 if (ro == ro1)
529                     return false;
530                 if (ro == ro2)
531                     return true;
532             }
533             ASSERT(false);  // We should have seen ro1 and ro2 by now.
534             return false;
535         }
536     }
537     return true;
538 }
539
540 // Return a set of rectangles that should not be overdrawn by the
541 // plugin ("cutouts").  This helps implement the "iframe shim"
542 // technique of overlaying a windowed plugin with content from the
543 // page.  In a nutshell, iframe elements should occlude plugins when
544 // they occur higher in the stacking order.
545 void WebPluginContainerImpl::windowCutOutRects(const IntRect& frameRect,
546                                                Vector<IntRect>& cutOutRects)
547 {
548     RenderObject* pluginNode = m_element->renderer();
549     ASSERT(pluginNode);
550     if (!pluginNode->style())
551         return;
552     Vector<const RenderObject*> pluginZstack;
553     Vector<const RenderObject*> iframeZstack;
554     getObjectStack(pluginNode, &pluginZstack);
555
556     // Get the parent widget
557     Widget* parentWidget = this->parent();
558     if (!parentWidget->isFrameView())
559         return;
560
561     FrameView* parentFrameView = static_cast<FrameView*>(parentWidget);
562
563     const HashSet<RefPtr<Widget> >* children = parentFrameView->children();
564     for (HashSet<RefPtr<Widget> >::const_iterator it = children->begin(); it != children->end(); ++it) {
565         // We only care about FrameView's because iframes show up as FrameViews.
566         if (!(*it)->isFrameView())
567             continue;
568
569         const FrameView* frameView =
570             static_cast<const FrameView*>((*it).get());
571         // Check to make sure we can get both the element and the RenderObject
572         // for this FrameView, if we can't just move on to the next object.
573         if (!frameView->frame() || !frameView->frame()->ownerElement()
574             || !frameView->frame()->ownerElement()->renderer())
575             continue;
576
577         HTMLElement* element = frameView->frame()->ownerElement();
578         RenderObject* iframeRenderer = element->renderer();
579
580         if (element->hasTagName(HTMLNames::iframeTag)
581             && iframeRenderer->absoluteBoundingBoxRect().intersects(frameRect)
582             && (!iframeRenderer->style() || iframeRenderer->style()->visibility() == VISIBLE)) {
583             getObjectStack(iframeRenderer, &iframeZstack);
584             if (checkStackOnTop(iframeZstack, pluginZstack)) {
585                 IntPoint point =
586                     roundedIntPoint(iframeRenderer->localToAbsolute());
587                 RenderBox* rbox = toRenderBox(iframeRenderer);
588                 IntSize size(rbox->width(), rbox->height());
589                 cutOutRects.append(IntRect(point, size));
590             }
591         }
592     }
593 }
594
595 } // namespace WebKit