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 "WebClipboard.h"
38 #include "WebCursorInfo.h"
39 #include "WebDataSourceImpl.h"
40 #include "WebElement.h"
41 #include "WebInputEvent.h"
42 #include "WebInputEventConversion.h"
44 #include "WebKitClient.h"
45 #include "WebPlugin.h"
47 #include "WebString.h"
49 #include "WebURLError.h"
50 #include "WebURLRequest.h"
51 #include "WebVector.h"
52 #include "WebViewImpl.h"
53 #include "WrappedResourceResponse.h"
55 #include "EventNames.h"
56 #include "FocusController.h"
57 #include "FormState.h"
59 #include "FrameLoadRequest.h"
60 #include "FrameView.h"
61 #include "GraphicsContext.h"
62 #include "HostWindow.h"
63 #include "HTMLFormElement.h"
64 #include "HTMLNames.h"
65 #include "HTMLPlugInElement.h"
66 #include "IFrameShimSupport.h"
67 #include "KeyboardCodes.h"
68 #include "KeyboardEvent.h"
69 #include "MouseEvent.h"
71 #include "RenderBox.h"
72 #include "ScrollView.h"
73 #include "UserGestureIndicator.h"
74 #include "WheelEvent.h"
77 #include "PlatformContextSkia.h"
80 using namespace WebCore;
84 // Public methods --------------------------------------------------------------
86 void WebPluginContainerImpl::setFrameRect(const IntRect& frameRect)
88 Widget::setFrameRect(frameRect);
92 void WebPluginContainerImpl::paint(GraphicsContext* gc, const IntRect& damageRect)
94 if (gc->paintingDisabled())
100 // Don't paint anything if the plugin doesn't intersect the damage rect.
101 if (!frameRect().intersects(damageRect))
106 ASSERT(parent()->isFrameView());
107 ScrollView* view = parent();
109 // The plugin is positioned in window coordinates, so it needs to be painted
110 // in window coordinates.
111 IntPoint origin = view->windowToContents(IntPoint(0, 0));
112 gc->translate(static_cast<float>(origin.x()), static_cast<float>(origin.y()));
114 #if WEBKIT_USING_SKIA
115 WebCanvas* canvas = gc->platformContext()->canvas();
116 #elif WEBKIT_USING_CG
117 WebCanvas* canvas = gc->platformContext();
121 IntRect(view->contentsToWindow(damageRect.location()), damageRect.size());
122 m_webPlugin->paint(canvas, windowRect);
127 void WebPluginContainerImpl::invalidateRect(const IntRect& rect)
132 RenderBox* renderer = toRenderBox(m_element->renderer());
134 IntRect dirtyRect = rect;
135 dirtyRect.move(renderer->borderLeft() + renderer->paddingLeft(),
136 renderer->borderTop() + renderer->paddingTop());
137 renderer->repaintRectangle(dirtyRect);
140 void WebPluginContainerImpl::setFocus(bool focused)
142 Widget::setFocus(focused);
143 m_webPlugin->updateFocus(focused);
146 void WebPluginContainerImpl::show()
148 setSelfVisible(true);
149 m_webPlugin->updateVisibility(true);
154 void WebPluginContainerImpl::hide()
156 setSelfVisible(false);
157 m_webPlugin->updateVisibility(false);
162 void WebPluginContainerImpl::handleEvent(Event* event)
164 if (!m_webPlugin->acceptsInputEvents())
167 // The events we pass are defined at:
168 // http://devedge-temp.mozilla.org/library/manuals/2002/plugin/1.0/structures5.html#1000000
169 // Don't take the documentation as truth, however. There are many cases
170 // where mozilla behaves differently than the spec.
171 if (event->isMouseEvent())
172 handleMouseEvent(static_cast<MouseEvent*>(event));
173 else if (event->isWheelEvent())
174 handleWheelEvent(static_cast<WheelEvent*>(event));
175 else if (event->isKeyboardEvent())
176 handleKeyboardEvent(static_cast<KeyboardEvent*>(event));
178 // FIXME: it would be cleaner if Widget::handleEvent returned true/false and
179 // HTMLPluginElement called setDefaultHandled or defaultEventHandler.
180 if (!event->defaultHandled())
181 m_element->Node::defaultEventHandler(event);
184 void WebPluginContainerImpl::frameRectsChanged()
186 Widget::frameRectsChanged();
190 void WebPluginContainerImpl::widgetPositionsUpdated()
192 Widget::widgetPositionsUpdated();
196 void WebPluginContainerImpl::setParentVisible(bool parentVisible)
198 // We override this function to make sure that geometry updates are sent
199 // over to the plugin. For e.g. when a plugin is instantiated it does not
200 // have a valid parent. As a result the first geometry update from webkit
201 // is ignored. This function is called when the plugin eventually gets a
204 if (isParentVisible() == parentVisible)
205 return; // No change.
207 Widget::setParentVisible(parentVisible);
208 if (!isSelfVisible())
209 return; // This widget has explicitely been marked as not visible.
211 m_webPlugin->updateVisibility(isVisible());
214 void WebPluginContainerImpl::setParent(ScrollView* view)
216 // We override this function so that if the plugin is windowed, we can call
217 // NPP_SetWindow at the first possible moment. This ensures that
218 // NPP_SetWindow is called before the manual load data is sent to a plugin.
219 // If this order is reversed, Flash won't load videos.
221 Widget::setParent(view);
226 bool WebPluginContainerImpl::supportsPaginatedPrint() const
228 return m_webPlugin->supportsPaginatedPrint();
231 int WebPluginContainerImpl::printBegin(const IntRect& printableArea,
232 int printerDPI) const
234 return m_webPlugin->printBegin(printableArea, printerDPI);
237 bool WebPluginContainerImpl::printPage(int pageNumber,
238 WebCore::GraphicsContext* gc)
241 #if WEBKIT_USING_SKIA
242 WebCanvas* canvas = gc->platformContext()->canvas();
243 #elif WEBKIT_USING_CG
244 WebCanvas* canvas = gc->platformContext();
246 bool ret = m_webPlugin->printPage(pageNumber, canvas);
251 void WebPluginContainerImpl::printEnd()
253 return m_webPlugin->printEnd();
256 void WebPluginContainerImpl::copy()
258 if (!m_webPlugin->hasSelection())
261 webKitClient()->clipboard()->writeHTML(m_webPlugin->selectionAsMarkup(), WebURL(), m_webPlugin->selectionAsText(), false);
264 WebElement WebPluginContainerImpl::element()
266 return WebElement(m_element);
269 void WebPluginContainerImpl::invalidate()
271 Widget::invalidate();
274 void WebPluginContainerImpl::invalidateRect(const WebRect& rect)
276 invalidateRect(static_cast<IntRect>(rect));
279 void WebPluginContainerImpl::scrollRect(int dx, int dy, const WebRect& rect)
281 Widget* parentWidget = parent();
282 if (parentWidget->isFrameView()) {
283 FrameView* parentFrameView = static_cast<FrameView*>(parentWidget);
284 if (!parentFrameView->isOverlapped()) {
285 IntRect damageRect = convertToContainingWindow(static_cast<IntRect>(rect));
286 IntSize scrollDelta(dx, dy);
287 // scroll() only uses the second rectangle, clipRect, and ignores the first
289 parent()->hostWindow()->scroll(scrollDelta, damageRect, damageRect);
294 // Use slow scrolling instead.
295 invalidateRect(rect);
298 void WebPluginContainerImpl::reportGeometry()
303 IntRect windowRect, clipRect;
304 Vector<IntRect> cutOutRects;
305 calculateGeometry(frameRect(), windowRect, clipRect, cutOutRects);
307 m_webPlugin->updateGeometry(windowRect, clipRect, cutOutRects, isVisible());
310 void WebPluginContainerImpl::commitBackingTexture()
312 #if USE(ACCELERATED_COMPOSITING)
314 platformLayer()->setNeedsDisplay();
318 void WebPluginContainerImpl::clearScriptObjects()
320 Frame* frame = m_element->document()->frame();
323 frame->script()->cleanupScriptObjectsForPlugin(this);
326 NPObject* WebPluginContainerImpl::scriptableObjectForElement()
328 return m_element->getNPObject();
331 WebString WebPluginContainerImpl::executeScriptURL(const WebURL& url, bool popupsAllowed)
333 Frame* frame = m_element->document()->frame();
337 const KURL& kurl = url;
338 ASSERT(kurl.protocolIs("javascript"));
340 String script = decodeURLEscapeSequences(
341 kurl.string().substring(strlen("javascript:")));
343 ScriptValue result = frame->script()->executeScript(script, popupsAllowed);
345 // Failure is reported as a null string.
347 result.getString(resultStr);
351 void WebPluginContainerImpl::loadFrameRequest(
352 const WebURLRequest& request, const WebString& target, bool notifyNeeded, void* notifyData)
354 Frame* frame = m_element->document()->frame();
356 return; // FIXME: send a notification in this case?
359 // FIXME: This is a bit of hack to allow us to observe completion of
360 // our frame request. It would be better to evolve FrameLoader to
361 // support a completion callback instead.
362 WebPluginLoadObserver* observer =
363 new WebPluginLoadObserver(this, request.url(), notifyData);
364 m_pluginLoadObservers.append(observer);
365 WebDataSourceImpl::setNextPluginLoadObserver(observer);
368 FrameLoadRequest frameRequest(frame->document()->securityOrigin(),
369 request.toResourceRequest(), target);
371 UserGestureIndicator gestureIndicator(request.hasUserGesture() ?
372 DefinitelyProcessingUserGesture : DefinitelyNotProcessingUserGesture);
374 frame->loader()->loadFrameRequest(
376 false, // lock history
377 false, // lock back forward list
383 void WebPluginContainerImpl::zoomLevelChanged(double zoomLevel)
385 WebViewImpl* view = WebViewImpl::fromPage(m_element->document()->frame()->page());
386 view->fullFramePluginZoomLevelChanged(zoomLevel);
389 void WebPluginContainerImpl::didReceiveResponse(const ResourceResponse& response)
391 // Make sure that the plugin receives window geometry before data, or else
392 // plugins misbehave.
395 WrappedResourceResponse urlResponse(response);
396 m_webPlugin->didReceiveResponse(urlResponse);
399 void WebPluginContainerImpl::didReceiveData(const char *data, int dataLength)
401 m_webPlugin->didReceiveData(data, dataLength);
404 void WebPluginContainerImpl::didFinishLoading()
406 m_webPlugin->didFinishLoading();
409 void WebPluginContainerImpl::didFailLoading(const ResourceError& error)
411 m_webPlugin->didFailLoading(error);
414 NPObject* WebPluginContainerImpl::scriptableObject()
416 return m_webPlugin->scriptableObject();
419 void WebPluginContainerImpl::willDestroyPluginLoadObserver(WebPluginLoadObserver* observer)
421 size_t pos = m_pluginLoadObservers.find(observer);
424 m_pluginLoadObservers.remove(pos);
427 #if USE(ACCELERATED_COMPOSITING)
428 WebCore::LayerChromium* WebPluginContainerImpl::platformLayer() const
430 // FIXME: In the event of a context lost, the texture needs to be recreated on the compositor's
431 // context and rebound to the platform layer here.
432 unsigned backingTextureId = m_webPlugin->getBackingTextureId();
433 if (!backingTextureId)
436 m_platformLayer->setTextureId(backingTextureId);
438 return m_platformLayer.get();
442 // Private methods -------------------------------------------------------------
444 WebPluginContainerImpl::WebPluginContainerImpl(WebCore::HTMLPlugInElement* element, WebPlugin* webPlugin)
445 : WebCore::PluginViewBase(0)
447 , m_webPlugin(webPlugin)
448 #if USE(ACCELERATED_COMPOSITING)
449 , m_platformLayer(PluginLayerChromium::create(0))
454 WebPluginContainerImpl::~WebPluginContainerImpl()
456 for (size_t i = 0; i < m_pluginLoadObservers.size(); ++i)
457 m_pluginLoadObservers[i]->clearPluginContainer();
458 m_webPlugin->destroy();
461 void WebPluginContainerImpl::handleMouseEvent(MouseEvent* event)
463 ASSERT(parent()->isFrameView());
465 // We cache the parent FrameView here as the plugin widget could be deleted
466 // in the call to HandleEvent. See http://b/issue?id=1362948
467 FrameView* parentView = static_cast<FrameView*>(parent());
469 WebMouseEventBuilder webEvent(this, *event);
470 if (webEvent.type == WebInputEvent::Undefined)
473 if (event->type() == eventNames().mousedownEvent) {
474 // Ensure that the frame containing the plugin has focus.
475 Frame* containingFrame = parentView->frame();
476 if (Page* currentPage = containingFrame->page())
477 currentPage->focusController()->setFocusedFrame(containingFrame);
478 // Give focus to our containing HTMLPluginElement.
479 containingFrame->document()->setFocusedNode(m_element);
482 WebCursorInfo cursorInfo;
483 if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
484 event->setDefaultHandled();
486 // A windowless plugin can change the cursor in response to a mouse move
487 // event. We need to reflect the changed cursor in the frame view as the
488 // mouse is moved in the boundaries of the windowless plugin.
489 Page* page = parentView->frame()->page();
492 ChromeClientImpl* chromeClient =
493 static_cast<ChromeClientImpl*>(page->chrome()->client());
494 chromeClient->setCursorForPlugin(cursorInfo);
497 void WebPluginContainerImpl::handleWheelEvent(WheelEvent* event)
499 WebMouseWheelEventBuilder webEvent(this, *event);
500 if (webEvent.type == WebInputEvent::Undefined)
503 WebCursorInfo cursorInfo;
504 if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
505 event->setDefaultHandled();
508 void WebPluginContainerImpl::handleKeyboardEvent(KeyboardEvent* event)
510 WebKeyboardEventBuilder webEvent(*event);
511 if (webEvent.type == WebInputEvent::Undefined)
514 if (webEvent.type == WebInputEvent::KeyDown) {
515 #if defined(OS_MACOSX)
516 if (webEvent.modifiers == WebInputEvent::MetaKey
518 if (webEvent.modifiers == WebInputEvent::ControlKey
520 && webEvent.windowsKeyCode == VKEY_C
521 // Only copy if there's a selection, so that we only ever do this
522 // for Pepper plugins that support copying. Windowless NPAPI
523 // plugins will get the event as before.
524 && m_webPlugin->hasSelection()) {
526 event->setDefaultHandled();
531 const WebInputEvent* currentInputEvent = WebViewImpl::currentInputEvent();
533 // Copy stashed info over, and only copy here in order not to interfere
534 // the ctrl-c logic above.
535 if (currentInputEvent
536 && WebInputEvent::isKeyboardEventType(currentInputEvent->type)) {
537 webEvent.modifiers |= currentInputEvent->modifiers &
538 (WebInputEvent::CapsLockOn | WebInputEvent::NumLockOn);
541 WebCursorInfo cursorInfo;
542 if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
543 event->setDefaultHandled();
546 void WebPluginContainerImpl::calculateGeometry(const IntRect& frameRect,
549 Vector<IntRect>& cutOutRects)
551 windowRect = IntRect(
552 parent()->contentsToWindow(frameRect.location()), frameRect.size());
554 // Calculate a clip-rect so that we don't overlap the scrollbars, etc.
555 clipRect = windowClipRect();
556 clipRect.move(-windowRect.x(), -windowRect.y());
558 getPluginOcclusions(m_element, this->parent(), frameRect, cutOutRects);
559 // Convert to the plugin position.
560 for (size_t i = 0; i < cutOutRects.size(); i++)
561 cutOutRects[i].move(-frameRect.x(), -frameRect.y());
564 WebCore::IntRect WebPluginContainerImpl::windowClipRect() const
566 // Start by clipping to our bounds.
568 convertToContainingWindow(IntRect(0, 0, width(), height()));
570 // document()->renderer() can be 0 when we receive messages from the
571 // plugins while we are destroying a frame.
572 if (m_element->renderer()->document()->renderer()) {
573 // Take our element and get the clip rect from the enclosing layer and
575 RenderLayer* layer = m_element->renderer()->enclosingLayer();
577 m_element->document()->view()->windowClipRectForLayer(layer, true));
583 } // namespace WebKit