OSDN Git Service

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