OSDN Git Service

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