OSDN Git Service

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