OSDN Git Service

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