2 * Copyright (C) 2009 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
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
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.
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.
32 #include "WebPluginContainerImpl.h"
35 #include "ChromeClientImpl.h"
36 #include "PluginLayerChromium.h"
37 #include "ScrollbarGroup.h"
38 #include "WebClipboard.h"
39 #include "WebCursorInfo.h"
40 #include "WebDataSourceImpl.h"
41 #include "WebElement.h"
42 #include "WebInputEvent.h"
43 #include "WebInputEventConversion.h"
45 #include "WebKitPlatformSupport.h"
46 #include "WebPlugin.h"
48 #include "WebString.h"
50 #include "WebURLError.h"
51 #include "WebURLRequest.h"
52 #include "WebVector.h"
53 #include "WebViewImpl.h"
54 #include "WrappedResourceResponse.h"
56 #include "EventNames.h"
57 #include "FocusController.h"
58 #include "FormState.h"
60 #include "FrameLoadRequest.h"
61 #include "FrameView.h"
62 #include "GraphicsContext.h"
63 #include "HostWindow.h"
64 #include "HTMLFormElement.h"
65 #include "HTMLNames.h"
66 #include "HTMLPlugInElement.h"
67 #include "IFrameShimSupport.h"
68 #include "KeyboardCodes.h"
69 #include "KeyboardEvent.h"
70 #include "MouseEvent.h"
72 #include "RenderBox.h"
73 #include "ScrollAnimator.h"
74 #include "ScrollView.h"
75 #include "ScrollbarTheme.h"
76 #include "UserGestureIndicator.h"
77 #include "WheelEvent.h"
79 #if ENABLE(GESTURE_EVENTS)
80 #include "PlatformGestureEvent.h"
84 #include "PlatformContextSkia.h"
87 using namespace WebCore;
91 // Public methods --------------------------------------------------------------
93 void WebPluginContainerImpl::setFrameRect(const IntRect& frameRect)
95 Widget::setFrameRect(frameRect);
99 void WebPluginContainerImpl::paint(GraphicsContext* gc, const IntRect& damageRect)
101 if (gc->updatingControlTints() && m_scrollbarGroup) {
102 // See comment in FrameView::updateControlTints().
103 if (m_scrollbarGroup->horizontalScrollbar())
104 m_scrollbarGroup->horizontalScrollbar()->invalidate();
105 if (m_scrollbarGroup->verticalScrollbar())
106 m_scrollbarGroup->verticalScrollbar()->invalidate();
109 if (gc->paintingDisabled())
115 // Don't paint anything if the plugin doesn't intersect the damage rect.
116 if (!frameRect().intersects(damageRect))
121 ASSERT(parent()->isFrameView());
122 ScrollView* view = parent();
124 // The plugin is positioned in window coordinates, so it needs to be painted
125 // in window coordinates.
126 IntPoint origin = view->windowToContents(IntPoint(0, 0));
127 gc->translate(static_cast<float>(origin.x()), static_cast<float>(origin.y()));
129 #if WEBKIT_USING_SKIA
130 WebCanvas* canvas = gc->platformContext()->canvas();
131 #elif WEBKIT_USING_CG
132 WebCanvas* canvas = gc->platformContext();
136 IntRect(view->contentsToWindow(damageRect.location()), damageRect.size());
137 m_webPlugin->paint(canvas, windowRect);
142 void WebPluginContainerImpl::invalidateRect(const IntRect& rect)
147 RenderBox* renderer = toRenderBox(m_element->renderer());
149 IntRect dirtyRect = rect;
150 dirtyRect.move(renderer->borderLeft() + renderer->paddingLeft(),
151 renderer->borderTop() + renderer->paddingTop());
152 renderer->repaintRectangle(dirtyRect);
155 void WebPluginContainerImpl::setFocus(bool focused)
157 Widget::setFocus(focused);
158 m_webPlugin->updateFocus(focused);
161 void WebPluginContainerImpl::show()
163 setSelfVisible(true);
164 m_webPlugin->updateVisibility(true);
169 void WebPluginContainerImpl::hide()
171 setSelfVisible(false);
172 m_webPlugin->updateVisibility(false);
177 void WebPluginContainerImpl::handleEvent(Event* event)
179 if (!m_webPlugin->acceptsInputEvents())
182 RefPtr<WebPluginContainerImpl> protector(this);
183 // The events we pass are defined at:
184 // http://devedge-temp.mozilla.org/library/manuals/2002/plugin/1.0/structures5.html#1000000
185 // Don't take the documentation as truth, however. There are many cases
186 // where mozilla behaves differently than the spec.
187 if (event->isMouseEvent())
188 handleMouseEvent(static_cast<MouseEvent*>(event));
189 else if (event->hasInterface(eventNames().interfaceForWheelEvent))
190 handleWheelEvent(static_cast<WheelEvent*>(event));
191 else if (event->isKeyboardEvent())
192 handleKeyboardEvent(static_cast<KeyboardEvent*>(event));
194 // FIXME: it would be cleaner if Widget::handleEvent returned true/false and
195 // HTMLPluginElement called setDefaultHandled or defaultEventHandler.
196 if (!event->defaultHandled())
197 m_element->Node::defaultEventHandler(event);
200 void WebPluginContainerImpl::frameRectsChanged()
202 Widget::frameRectsChanged();
206 void WebPluginContainerImpl::widgetPositionsUpdated()
208 Widget::widgetPositionsUpdated();
212 void WebPluginContainerImpl::setParentVisible(bool parentVisible)
214 // We override this function to make sure that geometry updates are sent
215 // over to the plugin. For e.g. when a plugin is instantiated it does not
216 // have a valid parent. As a result the first geometry update from webkit
217 // is ignored. This function is called when the plugin eventually gets a
220 if (isParentVisible() == parentVisible)
221 return; // No change.
223 Widget::setParentVisible(parentVisible);
224 if (!isSelfVisible())
225 return; // This widget has explicitely been marked as not visible.
227 m_webPlugin->updateVisibility(isVisible());
230 void WebPluginContainerImpl::setParent(ScrollView* view)
232 // We override this function so that if the plugin is windowed, we can call
233 // NPP_SetWindow at the first possible moment. This ensures that
234 // NPP_SetWindow is called before the manual load data is sent to a plugin.
235 // If this order is reversed, Flash won't load videos.
237 Widget::setParent(view);
242 bool WebPluginContainerImpl::supportsPaginatedPrint() const
244 return m_webPlugin->supportsPaginatedPrint();
247 bool WebPluginContainerImpl::isPrintScalingDisabled() const
249 return m_webPlugin->isPrintScalingDisabled();
252 int WebPluginContainerImpl::printBegin(const IntRect& printableArea,
253 int printerDPI) const
255 return m_webPlugin->printBegin(printableArea, printerDPI);
258 bool WebPluginContainerImpl::printPage(int pageNumber,
259 WebCore::GraphicsContext* gc)
262 #if WEBKIT_USING_SKIA
263 WebCanvas* canvas = gc->platformContext()->canvas();
264 #elif WEBKIT_USING_CG
265 WebCanvas* canvas = gc->platformContext();
267 bool ret = m_webPlugin->printPage(pageNumber, canvas);
272 void WebPluginContainerImpl::printEnd()
274 m_webPlugin->printEnd();
277 void WebPluginContainerImpl::copy()
279 if (!m_webPlugin->hasSelection())
282 webKitPlatformSupport()->clipboard()->writeHTML(m_webPlugin->selectionAsMarkup(), WebURL(), m_webPlugin->selectionAsText(), false);
285 WebElement WebPluginContainerImpl::element()
287 return WebElement(m_element);
290 void WebPluginContainerImpl::invalidate()
292 Widget::invalidate();
295 void WebPluginContainerImpl::invalidateRect(const WebRect& rect)
297 invalidateRect(static_cast<IntRect>(rect));
300 void WebPluginContainerImpl::scrollRect(int dx, int dy, const WebRect& rect)
302 Widget* parentWidget = parent();
303 if (parentWidget->isFrameView()) {
304 FrameView* parentFrameView = static_cast<FrameView*>(parentWidget);
305 if (!parentFrameView->isOverlapped()) {
306 IntRect damageRect = convertToContainingWindow(static_cast<IntRect>(rect));
307 IntSize scrollDelta(dx, dy);
308 // scroll() only uses the second rectangle, clipRect, and ignores the first
310 parent()->hostWindow()->scroll(scrollDelta, damageRect, damageRect);
315 // Use slow scrolling instead.
316 invalidateRect(rect);
319 void WebPluginContainerImpl::reportGeometry()
324 IntRect windowRect, clipRect;
325 Vector<IntRect> cutOutRects;
326 calculateGeometry(frameRect(), windowRect, clipRect, cutOutRects);
328 m_webPlugin->updateGeometry(windowRect, clipRect, cutOutRects, isVisible());
330 if (m_scrollbarGroup)
331 m_scrollbarGroup->scrollAnimator()->contentsResized();
334 void WebPluginContainerImpl::setBackingTextureId(unsigned id)
336 #if USE(ACCELERATED_COMPOSITING)
337 unsigned currId = m_platformLayer->textureId();
341 m_platformLayer->setTextureId(id);
342 // If anyone of the IDs is zero we need to switch between hardware
343 // and software compositing. This is done by triggering a style recalc
344 // on the container element.
346 m_element->setNeedsStyleRecalc(WebCore::SyntheticStyleChange);
350 void WebPluginContainerImpl::setBackingIOSurfaceId(int width,
352 uint32_t ioSurfaceId)
354 #if OS(DARWIN) && USE(ACCELERATED_COMPOSITING)
355 uint32_t currentId = m_platformLayer->getIOSurfaceId();
356 if (ioSurfaceId == currentId)
359 m_platformLayer->setIOSurfaceProperties(width, height, ioSurfaceId);
361 // If anyone of the IDs is zero we need to switch between hardware
362 // and software compositing. This is done by triggering a style recalc
363 // on the container element.
364 if (!(ioSurfaceId * currentId))
365 m_element->setNeedsStyleRecalc(WebCore::SyntheticStyleChange);
369 void WebPluginContainerImpl::commitBackingTexture()
371 #if USE(ACCELERATED_COMPOSITING)
373 platformLayer()->setNeedsDisplay();
377 void WebPluginContainerImpl::clearScriptObjects()
379 Frame* frame = m_element->document()->frame();
382 frame->script()->cleanupScriptObjectsForPlugin(this);
385 NPObject* WebPluginContainerImpl::scriptableObjectForElement()
387 return m_element->getNPObject();
390 WebString WebPluginContainerImpl::executeScriptURL(const WebURL& url, bool popupsAllowed)
392 Frame* frame = m_element->document()->frame();
396 const KURL& kurl = url;
397 ASSERT(kurl.protocolIs("javascript"));
399 String script = decodeURLEscapeSequences(
400 kurl.string().substring(strlen("javascript:")));
402 ScriptValue result = frame->script()->executeScript(script, popupsAllowed);
404 // Failure is reported as a null string.
406 result.getString(resultStr);
410 void WebPluginContainerImpl::loadFrameRequest(const WebURLRequest& request, const WebString& target, bool notifyNeeded, void* notifyData)
412 Frame* frame = m_element->document()->frame();
413 if (!frame || !frame->loader()->documentLoader())
414 return; // FIXME: send a notification in this case?
417 // FIXME: This is a bit of hack to allow us to observe completion of
418 // our frame request. It would be better to evolve FrameLoader to
419 // support a completion callback instead.
420 OwnPtr<WebPluginLoadObserver> observer = adoptPtr(new WebPluginLoadObserver(this, request.url(), notifyData));
421 // FIXME: Calling get here is dangerous! What if observer is freed?
422 m_pluginLoadObservers.append(observer.get());
423 WebDataSourceImpl::setNextPluginLoadObserver(observer.release());
426 FrameLoadRequest frameRequest(frame->document()->securityOrigin(), request.toResourceRequest(), target);
427 UserGestureIndicator gestureIndicator(request.hasUserGesture() ? DefinitelyProcessingUserGesture : PossiblyProcessingUserGesture);
428 frame->loader()->loadFrameRequest(frameRequest, false, false, 0, 0, MaybeSendReferrer);
431 void WebPluginContainerImpl::zoomLevelChanged(double zoomLevel)
433 WebViewImpl* view = WebViewImpl::fromPage(m_element->document()->frame()->page());
434 view->fullFramePluginZoomLevelChanged(zoomLevel);
437 void WebPluginContainerImpl::didReceiveResponse(const ResourceResponse& response)
439 // Make sure that the plugin receives window geometry before data, or else
440 // plugins misbehave.
443 WrappedResourceResponse urlResponse(response);
444 m_webPlugin->didReceiveResponse(urlResponse);
447 void WebPluginContainerImpl::didReceiveData(const char *data, int dataLength)
449 m_webPlugin->didReceiveData(data, dataLength);
452 void WebPluginContainerImpl::didFinishLoading()
454 m_webPlugin->didFinishLoading();
457 void WebPluginContainerImpl::didFailLoading(const ResourceError& error)
459 m_webPlugin->didFailLoading(error);
462 NPObject* WebPluginContainerImpl::scriptableObject()
464 return m_webPlugin->scriptableObject();
467 void WebPluginContainerImpl::willDestroyPluginLoadObserver(WebPluginLoadObserver* observer)
469 size_t pos = m_pluginLoadObservers.find(observer);
472 m_pluginLoadObservers.remove(pos);
475 #if USE(ACCELERATED_COMPOSITING)
476 WebCore::LayerChromium* WebPluginContainerImpl::platformLayer() const
478 return (m_platformLayer->textureId() || m_platformLayer->getIOSurfaceId()) ? m_platformLayer.get() : 0;
483 ScrollbarGroup* WebPluginContainerImpl::scrollbarGroup()
485 if (!m_scrollbarGroup)
486 m_scrollbarGroup = adoptPtr(new ScrollbarGroup(m_element->document()->frame()->page()));
487 return m_scrollbarGroup.get();
490 void WebPluginContainerImpl::willStartLiveResize()
492 if (m_scrollbarGroup)
493 m_scrollbarGroup->willStartLiveResize();
496 void WebPluginContainerImpl::willEndLiveResize()
498 if (m_scrollbarGroup)
499 m_scrollbarGroup->willEndLiveResize();
502 bool WebPluginContainerImpl::paintCustomOverhangArea(GraphicsContext* context, const IntRect& horizontalOverhangArea, const IntRect& verticalOverhangArea, const IntRect& dirtyRect)
505 context->setFillColor(Color(0xCC, 0xCC, 0xCC), ColorSpaceDeviceRGB);
506 context->fillRect(intersection(horizontalOverhangArea, dirtyRect));
507 context->fillRect(intersection(verticalOverhangArea, dirtyRect));
512 #if ENABLE(GESTURE_EVENTS)
513 bool WebPluginContainerImpl::handleGestureEvent(const WebCore::PlatformGestureEvent& gestureEvent)
515 if (m_scrollbarGroup) {
516 m_scrollbarGroup->handleGestureEvent(gestureEvent);
523 // Private methods -------------------------------------------------------------
525 WebPluginContainerImpl::WebPluginContainerImpl(WebCore::HTMLPlugInElement* element, WebPlugin* webPlugin)
526 : WebCore::PluginViewBase(0)
528 , m_webPlugin(webPlugin)
529 #if USE(ACCELERATED_COMPOSITING)
530 , m_platformLayer(PluginLayerChromium::create(0))
535 WebPluginContainerImpl::~WebPluginContainerImpl()
537 for (size_t i = 0; i < m_pluginLoadObservers.size(); ++i)
538 m_pluginLoadObservers[i]->clearPluginContainer();
539 m_webPlugin->destroy();
542 void WebPluginContainerImpl::handleMouseEvent(MouseEvent* event)
544 ASSERT(parent()->isFrameView());
546 // We cache the parent FrameView here as the plugin widget could be deleted
547 // in the call to HandleEvent. See http://b/issue?id=1362948
548 FrameView* parentView = static_cast<FrameView*>(parent());
550 WebMouseEventBuilder webEvent(this, *event);
551 if (webEvent.type == WebInputEvent::Undefined)
554 if (event->type() == eventNames().mousedownEvent) {
555 Frame* containingFrame = parentView->frame();
556 if (Page* currentPage = containingFrame->page())
557 currentPage->focusController()->setFocusedNode(m_element, containingFrame);
559 containingFrame->document()->setFocusedNode(m_element);
562 if (m_scrollbarGroup) {
563 // This needs to be set before the other callbacks in this scope, since
564 // the scroll animator class might query the position in response.
565 m_scrollbarGroup->setLastMousePosition(IntPoint(event->x(), event->y()));
566 if (event->type() == eventNames().mousemoveEvent)
567 m_scrollbarGroup->scrollAnimator()->mouseMovedInContentArea();
568 else if (event->type() == eventNames().mouseoverEvent)
569 m_scrollbarGroup->scrollAnimator()->mouseEnteredContentArea();
570 else if (event->type() == eventNames().mouseoutEvent)
571 m_scrollbarGroup->scrollAnimator()->mouseExitedContentArea();
574 WebCursorInfo cursorInfo;
575 if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
576 event->setDefaultHandled();
578 // A windowless plugin can change the cursor in response to a mouse move
579 // event. We need to reflect the changed cursor in the frame view as the
580 // mouse is moved in the boundaries of the windowless plugin.
581 Page* page = parentView->frame()->page();
584 ChromeClientImpl* chromeClient =
585 static_cast<ChromeClientImpl*>(page->chrome()->client());
586 chromeClient->setCursorForPlugin(cursorInfo);
589 void WebPluginContainerImpl::handleWheelEvent(WheelEvent* event)
591 WebMouseWheelEventBuilder webEvent(this, *event);
592 if (webEvent.type == WebInputEvent::Undefined)
595 WebCursorInfo cursorInfo;
596 if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
597 event->setDefaultHandled();
600 void WebPluginContainerImpl::handleKeyboardEvent(KeyboardEvent* event)
602 WebKeyboardEventBuilder webEvent(*event);
603 if (webEvent.type == WebInputEvent::Undefined)
606 if (webEvent.type == WebInputEvent::KeyDown) {
608 if (webEvent.modifiers == WebInputEvent::MetaKey
610 if (webEvent.modifiers == WebInputEvent::ControlKey
612 && webEvent.windowsKeyCode == VKEY_C
613 // Only copy if there's a selection, so that we only ever do this
614 // for Pepper plugins that support copying. Windowless NPAPI
615 // plugins will get the event as before.
616 && m_webPlugin->hasSelection()) {
618 event->setDefaultHandled();
623 const WebInputEvent* currentInputEvent = WebViewImpl::currentInputEvent();
625 // Copy stashed info over, and only copy here in order not to interfere
626 // the ctrl-c logic above.
627 if (currentInputEvent
628 && WebInputEvent::isKeyboardEventType(currentInputEvent->type)) {
629 webEvent.modifiers |= currentInputEvent->modifiers &
630 (WebInputEvent::CapsLockOn | WebInputEvent::NumLockOn);
633 WebCursorInfo cursorInfo;
634 if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
635 event->setDefaultHandled();
638 void WebPluginContainerImpl::calculateGeometry(const IntRect& frameRect,
641 Vector<IntRect>& cutOutRects)
643 windowRect = IntRect(
644 parent()->contentsToWindow(frameRect.location()), frameRect.size());
646 // Calculate a clip-rect so that we don't overlap the scrollbars, etc.
647 clipRect = windowClipRect();
648 clipRect.move(-windowRect.x(), -windowRect.y());
650 getPluginOcclusions(m_element, this->parent(), frameRect, cutOutRects);
651 // Convert to the plugin position.
652 for (size_t i = 0; i < cutOutRects.size(); i++)
653 cutOutRects[i].move(-frameRect.x(), -frameRect.y());
656 WebCore::IntRect WebPluginContainerImpl::windowClipRect() const
658 // Start by clipping to our bounds.
660 convertToContainingWindow(IntRect(0, 0, width(), height()));
662 // document()->renderer() can be 0 when we receive messages from the
663 // plugins while we are destroying a frame.
664 if (m_element->renderer()->document()->renderer()) {
665 // Take our element and get the clip rect from the enclosing layer and
667 RenderLayer* layer = m_element->renderer()->enclosingLayer();
669 m_element->document()->view()->windowClipRectForLayer(layer, true));
675 } // namespace WebKit