Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / web / 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 "web/WebPluginContainerImpl.h"
33
34 #include "core/page/Chrome.h"
35 #include "core/page/EventHandler.h"
36 #include "platform/exported/WrappedResourceResponse.h"
37 #include "public/web/WebElement.h"
38 #include "public/web/WebInputEvent.h"
39 #include "public/web/WebPlugin.h"
40 #include "public/web/WebViewClient.h"
41 #include "web/ChromeClientImpl.h"
42 #include "web/ScrollbarGroup.h"
43 #include "web/WebDataSourceImpl.h"
44 #include "web/WebInputEventConversion.h"
45 #include "web/WebViewImpl.h"
46
47 #include "HTMLNames.h"
48 #include "bindings/v8/ScriptController.h"
49 #include "core/clipboard/Clipboard.h"
50 #include "core/clipboard/DataObject.h"
51 #include "core/events/GestureEvent.h"
52 #include "core/events/KeyboardEvent.h"
53 #include "core/events/MouseEvent.h"
54 #include "core/events/TouchEvent.h"
55 #include "core/events/WheelEvent.h"
56 #include "core/frame/FrameView.h"
57 #include "core/frame/LocalFrame.h"
58 #include "core/html/HTMLFormElement.h"
59 #include "core/html/HTMLPlugInElement.h"
60 #include "core/loader/FormState.h"
61 #include "core/loader/FrameLoadRequest.h"
62 #include "core/page/FocusController.h"
63 #include "core/page/Page.h"
64 #include "core/page/scrolling/ScrollingCoordinator.h"
65 #include "core/plugins/PluginOcclusionSupport.h"
66 #include "core/rendering/HitTestResult.h"
67 #include "core/rendering/RenderBox.h"
68 #include "platform/HostWindow.h"
69 #include "platform/KeyboardCodes.h"
70 #include "platform/PlatformGestureEvent.h"
71 #include "platform/UserGestureIndicator.h"
72 #include "platform/graphics/GraphicsContext.h"
73 #include "platform/graphics/GraphicsLayer.h"
74 #include "platform/scroll/ScrollAnimator.h"
75 #include "platform/scroll/ScrollView.h"
76 #include "platform/scroll/ScrollbarTheme.h"
77 #include "public/platform/Platform.h"
78 #include "public/platform/WebClipboard.h"
79 #include "public/platform/WebCompositorSupport.h"
80 #include "public/platform/WebCursorInfo.h"
81 #include "public/platform/WebDragData.h"
82 #include "public/platform/WebExternalTextureLayer.h"
83 #include "public/platform/WebRect.h"
84 #include "public/platform/WebString.h"
85 #include "public/platform/WebURL.h"
86 #include "public/platform/WebURLError.h"
87 #include "public/platform/WebURLRequest.h"
88 #include "public/platform/WebVector.h"
89 #include "public/web/WebPrintParams.h"
90
91 using namespace WebCore;
92
93 namespace blink {
94
95 // Public methods --------------------------------------------------------------
96
97 void WebPluginContainerImpl::setFrameRect(const IntRect& frameRect)
98 {
99     Widget::setFrameRect(frameRect);
100     reportGeometry();
101 }
102
103 void WebPluginContainerImpl::paint(GraphicsContext* gc, const IntRect& damageRect)
104 {
105     if (gc->updatingControlTints() && m_scrollbarGroup) {
106         // See comment in FrameView::updateControlTints().
107         if (m_scrollbarGroup->horizontalScrollbar())
108             m_scrollbarGroup->horizontalScrollbar()->invalidate();
109         if (m_scrollbarGroup->verticalScrollbar())
110             m_scrollbarGroup->verticalScrollbar()->invalidate();
111     }
112
113     if (gc->paintingDisabled())
114         return;
115
116     if (!parent())
117         return;
118
119     // Don't paint anything if the plugin doesn't intersect the damage rect.
120     if (!frameRect().intersects(damageRect))
121         return;
122
123     gc->save();
124
125     ASSERT(parent()->isFrameView());
126     ScrollView* view =  toScrollView(parent());
127
128     // The plugin is positioned in window coordinates, so it needs to be painted
129     // in window coordinates.
130     IntPoint origin = view->contentsToWindow(IntPoint(0, 0));
131     gc->translate(static_cast<float>(-origin.x()), static_cast<float>(-origin.y()));
132
133     WebCanvas* canvas = gc->canvas();
134
135     IntRect windowRect = view->contentsToWindow(damageRect);
136     m_webPlugin->paint(canvas, windowRect);
137
138     gc->restore();
139 }
140
141 void WebPluginContainerImpl::invalidateRect(const IntRect& rect)
142 {
143     if (!parent())
144         return;
145
146     RenderBox* renderer = toRenderBox(m_element->renderer());
147
148     IntRect dirtyRect = rect;
149     dirtyRect.move(renderer->borderLeft() + renderer->paddingLeft(),
150                    renderer->borderTop() + renderer->paddingTop());
151     renderer->repaintRectangle(dirtyRect);
152 }
153
154 void WebPluginContainerImpl::setFocus(bool focused)
155 {
156     Widget::setFocus(focused);
157     m_webPlugin->updateFocus(focused);
158 }
159
160 void WebPluginContainerImpl::show()
161 {
162     setSelfVisible(true);
163     m_webPlugin->updateVisibility(true);
164
165     Widget::show();
166 }
167
168 void WebPluginContainerImpl::hide()
169 {
170     setSelfVisible(false);
171     m_webPlugin->updateVisibility(false);
172
173     Widget::hide();
174 }
175
176 void WebPluginContainerImpl::handleEvent(Event* event)
177 {
178     if (!m_webPlugin->acceptsInputEvents())
179         return;
180
181     RefPtr<WebPluginContainerImpl> protector(this);
182     // The events we pass are defined at:
183     //    http://devedge-temp.mozilla.org/library/manuals/2002/plugin/1.0/structures5.html#1000000
184     // Don't take the documentation as truth, however.  There are many cases
185     // where mozilla behaves differently than the spec.
186     if (event->isMouseEvent())
187         handleMouseEvent(toMouseEvent(event));
188     else if (event->isWheelEvent())
189         handleWheelEvent(toWheelEvent(event));
190     else if (event->isKeyboardEvent())
191         handleKeyboardEvent(toKeyboardEvent(event));
192     else if (event->isTouchEvent())
193         handleTouchEvent(toTouchEvent(event));
194     else if (event->isGestureEvent())
195         handleGestureEvent(toGestureEvent(event));
196
197     // FIXME: it would be cleaner if Widget::handleEvent returned true/false and
198     // HTMLPluginElement called setDefaultHandled or defaultEventHandler.
199     if (!event->defaultHandled())
200         m_element->Node::defaultEventHandler(event);
201 }
202
203 void WebPluginContainerImpl::frameRectsChanged()
204 {
205     Widget::frameRectsChanged();
206     reportGeometry();
207 }
208
209 void WebPluginContainerImpl::widgetPositionsUpdated()
210 {
211     Widget::widgetPositionsUpdated();
212     reportGeometry();
213 }
214
215 void WebPluginContainerImpl::eventListenersRemoved()
216 {
217     // We're no longer registered to receive touch events, so don't try to remove
218     // the touch event handlers in our destructor.
219     m_touchEventRequestType = TouchEventRequestTypeNone;
220 }
221
222 void WebPluginContainerImpl::setParentVisible(bool parentVisible)
223 {
224     // We override this function to make sure that geometry updates are sent
225     // over to the plugin. For e.g. when a plugin is instantiated it does not
226     // have a valid parent. As a result the first geometry update from webkit
227     // is ignored. This function is called when the plugin eventually gets a
228     // parent.
229
230     if (isParentVisible() == parentVisible)
231         return;  // No change.
232
233     Widget::setParentVisible(parentVisible);
234     if (!isSelfVisible())
235         return;  // This widget has explicitely been marked as not visible.
236
237     m_webPlugin->updateVisibility(isVisible());
238 }
239
240 void WebPluginContainerImpl::setParent(Widget* widget)
241 {
242     // We override this function so that if the plugin is windowed, we can call
243     // NPP_SetWindow at the first possible moment.  This ensures that
244     // NPP_SetWindow is called before the manual load data is sent to a plugin.
245     // If this order is reversed, Flash won't load videos.
246
247     Widget::setParent(widget);
248     if (widget)
249         reportGeometry();
250     else if (m_webPlugin)
251         m_webPlugin->containerDidDetachFromParent();
252 }
253
254 void WebPluginContainerImpl::setPlugin(WebPlugin* plugin)
255 {
256     if (plugin != m_webPlugin) {
257         m_element->resetInstance();
258         m_webPlugin = plugin;
259     }
260 }
261
262 float WebPluginContainerImpl::deviceScaleFactor()
263 {
264     Page* page = m_element->document().page();
265     if (!page)
266         return 1.0;
267     return page->deviceScaleFactor();
268 }
269
270 float WebPluginContainerImpl::pageScaleFactor()
271 {
272     Page* page = m_element->document().page();
273     if (!page)
274         return 1.0;
275     return page->pageScaleFactor();
276 }
277
278 float WebPluginContainerImpl::pageZoomFactor()
279 {
280     LocalFrame* frame = m_element->document().frame();
281     if (!frame)
282         return 1.0;
283     return frame->pageZoomFactor();
284 }
285
286 void WebPluginContainerImpl::setWebLayer(WebLayer* layer)
287 {
288     if (m_webLayer == layer)
289         return;
290
291     // If anyone of the layers is null we need to switch between hardware
292     // and software compositing.
293     if (!m_webLayer || !layer)
294         m_element->scheduleLayerUpdate();
295     if (m_webLayer)
296         GraphicsLayer::unregisterContentsLayer(m_webLayer);
297     if (layer)
298         GraphicsLayer::registerContentsLayer(layer);
299     m_webLayer = layer;
300 }
301
302 bool WebPluginContainerImpl::supportsPaginatedPrint() const
303 {
304     return m_webPlugin->supportsPaginatedPrint();
305 }
306
307 bool WebPluginContainerImpl::isPrintScalingDisabled() const
308 {
309     return m_webPlugin->isPrintScalingDisabled();
310 }
311
312 int WebPluginContainerImpl::printBegin(const WebPrintParams& printParams) const
313 {
314     return m_webPlugin->printBegin(printParams);
315 }
316
317 bool WebPluginContainerImpl::printPage(int pageNumber,
318                                        WebCore::GraphicsContext* gc)
319 {
320     if (gc->paintingDisabled())
321         return true;
322     gc->save();
323     WebCanvas* canvas = gc->canvas();
324     bool ret = m_webPlugin->printPage(pageNumber, canvas);
325     gc->restore();
326     return ret;
327 }
328
329 void WebPluginContainerImpl::printEnd()
330 {
331     m_webPlugin->printEnd();
332 }
333
334 void WebPluginContainerImpl::copy()
335 {
336     if (!m_webPlugin->hasSelection())
337         return;
338
339     blink::Platform::current()->clipboard()->writeHTML(m_webPlugin->selectionAsMarkup(), WebURL(), m_webPlugin->selectionAsText(), false);
340 }
341
342 bool WebPluginContainerImpl::executeEditCommand(const WebString& name)
343 {
344     if (m_webPlugin->executeEditCommand(name))
345         return true;
346
347     if (name != "Copy")
348         return false;
349
350     copy();
351     return true;
352 }
353
354 bool WebPluginContainerImpl::executeEditCommand(const WebString& name, const WebString& value)
355 {
356     return m_webPlugin->executeEditCommand(name, value);
357 }
358
359 WebElement WebPluginContainerImpl::element()
360 {
361     return WebElement(m_element);
362 }
363
364 void WebPluginContainerImpl::invalidate()
365 {
366     Widget::invalidate();
367 }
368
369 void WebPluginContainerImpl::invalidateRect(const WebRect& rect)
370 {
371     invalidateRect(static_cast<IntRect>(rect));
372 }
373
374 void WebPluginContainerImpl::scrollRect(int dx, int dy, const WebRect& rect)
375 {
376     Widget* parentWidget = parent();
377     if (parentWidget->isFrameView()) {
378         FrameView* parentFrameView = toFrameView(parentWidget);
379         if (!parentFrameView->isOverlapped()) {
380             IntRect damageRect = convertToContainingWindow(static_cast<IntRect>(rect));
381             IntSize scrollDelta(dx, dy);
382             // scroll() only uses the second rectangle, clipRect, and ignores the first
383             // rectangle.
384             parent()->hostWindow()->scroll(scrollDelta, damageRect, damageRect);
385             return;
386         }
387     }
388
389     // Use slow scrolling instead.
390     invalidateRect(rect);
391 }
392
393 void WebPluginContainerImpl::reportGeometry()
394 {
395     if (!parent())
396         return;
397
398     IntRect windowRect, clipRect;
399     Vector<IntRect> cutOutRects;
400     calculateGeometry(frameRect(), windowRect, clipRect, cutOutRects);
401
402     m_webPlugin->updateGeometry(windowRect, clipRect, cutOutRects, isVisible());
403
404     if (m_scrollbarGroup) {
405         m_scrollbarGroup->scrollAnimator()->contentsResized();
406         m_scrollbarGroup->setFrameRect(frameRect());
407     }
408 }
409
410 void WebPluginContainerImpl::allowScriptObjects()
411 {
412 }
413
414 void WebPluginContainerImpl::clearScriptObjects()
415 {
416     LocalFrame* frame = m_element->document().frame();
417     if (!frame)
418         return;
419     frame->script().cleanupScriptObjectsForPlugin(this);
420 }
421
422 NPObject* WebPluginContainerImpl::scriptableObjectForElement()
423 {
424     return m_element->getNPObject();
425 }
426
427 WebString WebPluginContainerImpl::executeScriptURL(const WebURL& url, bool popupsAllowed)
428 {
429     LocalFrame* frame = m_element->document().frame();
430     if (!frame)
431         return WebString();
432
433     const KURL& kurl = url;
434     ASSERT(kurl.protocolIs("javascript"));
435
436     String script = decodeURLEscapeSequences(
437         kurl.string().substring(strlen("javascript:")));
438
439     UserGestureIndicator gestureIndicator(popupsAllowed ? DefinitelyProcessingNewUserGesture : PossiblyProcessingUserGesture);
440     ScriptValue result = frame->script().executeScriptInMainWorldAndReturnValue(ScriptSourceCode(script));
441
442     // Failure is reported as a null string.
443     String resultString;
444     result.toString(resultString);
445     return resultString;
446 }
447
448 void WebPluginContainerImpl::loadFrameRequest(const WebURLRequest& request, const WebString& target, bool notifyNeeded, void* notifyData)
449 {
450     LocalFrame* frame = m_element->document().frame();
451     if (!frame || !frame->loader().documentLoader())
452         return;  // FIXME: send a notification in this case?
453
454     if (notifyNeeded) {
455         // FIXME: This is a bit of hack to allow us to observe completion of
456         // our frame request.  It would be better to evolve FrameLoader to
457         // support a completion callback instead.
458         OwnPtr<WebPluginLoadObserver> observer = adoptPtr(new WebPluginLoadObserver(this, request.url(), notifyData));
459         // FIXME: Calling get here is dangerous! What if observer is freed?
460         m_pluginLoadObservers.append(observer.get());
461         WebDataSourceImpl::setNextPluginLoadObserver(observer.release());
462     }
463
464     FrameLoadRequest frameRequest(frame->document(), request.toResourceRequest(), target);
465     UserGestureIndicator gestureIndicator(request.hasUserGesture() ? DefinitelyProcessingNewUserGesture : PossiblyProcessingUserGesture);
466     frame->loader().load(frameRequest);
467 }
468
469 void WebPluginContainerImpl::zoomLevelChanged(double zoomLevel)
470 {
471     WebViewImpl* view = WebViewImpl::fromPage(m_element->document().frame()->page());
472     view->fullFramePluginZoomLevelChanged(zoomLevel);
473 }
474
475 bool WebPluginContainerImpl::isRectTopmost(const WebRect& rect)
476 {
477     LocalFrame* frame = m_element->document().frame();
478     if (!frame)
479         return false;
480
481     // hitTestResultAtPoint() takes a padding rectangle.
482     // FIXME: We'll be off by 1 when the width or height is even.
483     IntRect documentRect(x() + rect.x, y() + rect.y, rect.width, rect.height);
484     LayoutPoint center = documentRect.center();
485     // Make the rect we're checking (the point surrounded by padding rects) contained inside the requested rect. (Note that -1/2 is 0.)
486     LayoutSize padding((documentRect.width() - 1) / 2, (documentRect.height() - 1) / 2);
487     HitTestResult result = frame->eventHandler().hitTestResultAtPoint(center, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent, padding);
488     const HitTestResult::NodeSet& nodes = result.rectBasedTestResult();
489     if (nodes.size() != 1)
490         return false;
491     return nodes.first().get() == m_element;
492 }
493
494 void WebPluginContainerImpl::requestTouchEventType(TouchEventRequestType requestType)
495 {
496     if (m_touchEventRequestType == requestType)
497         return;
498
499     if (requestType != TouchEventRequestTypeNone && m_touchEventRequestType == TouchEventRequestTypeNone)
500         m_element->document().didAddTouchEventHandler(m_element);
501     else if (requestType == TouchEventRequestTypeNone && m_touchEventRequestType != TouchEventRequestTypeNone)
502         m_element->document().didRemoveTouchEventHandler(m_element);
503     m_touchEventRequestType = requestType;
504 }
505
506 void WebPluginContainerImpl::setWantsWheelEvents(bool wantsWheelEvents)
507 {
508     if (m_wantsWheelEvents == wantsWheelEvents)
509         return;
510     m_wantsWheelEvents = wantsWheelEvents;
511     if (Page* page = m_element->document().page()) {
512         if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator()) {
513             if (parent() && parent()->isFrameView())
514                 scrollingCoordinator->notifyLayoutUpdated();
515         }
516     }
517 }
518
519 WebPoint WebPluginContainerImpl::windowToLocalPoint(const WebPoint& point)
520 {
521     ScrollView* view = toScrollView(parent());
522     if (!view)
523         return point;
524     WebPoint windowPoint = view->windowToContents(point);
525     return roundedIntPoint(m_element->renderer()->absoluteToLocal(LayoutPoint(windowPoint), UseTransforms));
526 }
527
528 WebPoint WebPluginContainerImpl::localToWindowPoint(const WebPoint& point)
529 {
530     ScrollView* view = toScrollView(parent());
531     if (!view)
532         return point;
533     IntPoint absolutePoint = roundedIntPoint(m_element->renderer()->localToAbsolute(LayoutPoint(point), UseTransforms));
534     return view->contentsToWindow(absolutePoint);
535 }
536
537 void WebPluginContainerImpl::didReceiveResponse(const ResourceResponse& response)
538 {
539     // Make sure that the plugin receives window geometry before data, or else
540     // plugins misbehave.
541     frameRectsChanged();
542
543     WrappedResourceResponse urlResponse(response);
544     m_webPlugin->didReceiveResponse(urlResponse);
545 }
546
547 void WebPluginContainerImpl::didReceiveData(const char *data, int dataLength)
548 {
549     m_webPlugin->didReceiveData(data, dataLength);
550 }
551
552 void WebPluginContainerImpl::didFinishLoading()
553 {
554     m_webPlugin->didFinishLoading();
555 }
556
557 void WebPluginContainerImpl::didFailLoading(const ResourceError& error)
558 {
559     m_webPlugin->didFailLoading(error);
560 }
561
562 WebLayer* WebPluginContainerImpl::platformLayer() const
563 {
564     return m_webLayer;
565 }
566
567 NPObject* WebPluginContainerImpl::scriptableObject()
568 {
569     return m_webPlugin->scriptableObject();
570 }
571
572 bool WebPluginContainerImpl::getFormValue(String& value)
573 {
574     WebString webValue;
575     if (m_webPlugin->getFormValue(webValue)) {
576         value = webValue;
577         return true;
578     }
579     return false;
580 }
581
582 bool WebPluginContainerImpl::supportsKeyboardFocus() const
583 {
584     return m_webPlugin->supportsKeyboardFocus();
585 }
586
587 bool WebPluginContainerImpl::supportsInputMethod() const
588 {
589     return m_webPlugin->supportsInputMethod();
590 }
591
592 bool WebPluginContainerImpl::canProcessDrag() const
593 {
594     return m_webPlugin->canProcessDrag();
595 }
596
597 bool WebPluginContainerImpl::wantsWheelEvents()
598 {
599     return m_wantsWheelEvents;
600 }
601
602 void WebPluginContainerImpl::willDestroyPluginLoadObserver(WebPluginLoadObserver* observer)
603 {
604     size_t pos = m_pluginLoadObservers.find(observer);
605     if (pos == kNotFound)
606         return;
607     m_pluginLoadObservers.remove(pos);
608 }
609
610 ScrollbarGroup* WebPluginContainerImpl::scrollbarGroup()
611 {
612     if (!m_scrollbarGroup)
613         m_scrollbarGroup = adoptPtr(new ScrollbarGroup(m_element->document().frame()->view(), frameRect()));
614     return m_scrollbarGroup.get();
615 }
616
617 void WebPluginContainerImpl::willStartLiveResize()
618 {
619     if (m_scrollbarGroup)
620         m_scrollbarGroup->willStartLiveResize();
621 }
622
623 void WebPluginContainerImpl::willEndLiveResize()
624 {
625     if (m_scrollbarGroup)
626         m_scrollbarGroup->willEndLiveResize();
627 }
628
629 bool WebPluginContainerImpl::paintCustomOverhangArea(GraphicsContext* context, const IntRect& horizontalOverhangArea, const IntRect& verticalOverhangArea, const IntRect& dirtyRect)
630 {
631     context->save();
632     context->setFillColor(Color(0xCC, 0xCC, 0xCC));
633     context->fillRect(intersection(horizontalOverhangArea, dirtyRect));
634     context->fillRect(intersection(verticalOverhangArea, dirtyRect));
635     context->restore();
636     return true;
637 }
638
639 // Private methods -------------------------------------------------------------
640
641 WebPluginContainerImpl::WebPluginContainerImpl(WebCore::HTMLPlugInElement* element, WebPlugin* webPlugin)
642     : m_element(element)
643     , m_webPlugin(webPlugin)
644     , m_webLayer(0)
645     , m_touchEventRequestType(TouchEventRequestTypeNone)
646     , m_wantsWheelEvents(false)
647 {
648 }
649
650 WebPluginContainerImpl::~WebPluginContainerImpl()
651 {
652     if (m_touchEventRequestType != TouchEventRequestTypeNone)
653         m_element->document().didRemoveTouchEventHandler(m_element);
654
655     for (size_t i = 0; i < m_pluginLoadObservers.size(); ++i)
656         m_pluginLoadObservers[i]->clearPluginContainer();
657     m_webPlugin->destroy();
658     if (m_webLayer)
659         GraphicsLayer::unregisterContentsLayer(m_webLayer);
660 }
661
662 void WebPluginContainerImpl::handleMouseEvent(MouseEvent* event)
663 {
664     ASSERT(parent()->isFrameView());
665
666     if (event->isDragEvent()) {
667         if (m_webPlugin->canProcessDrag())
668             handleDragEvent(event);
669         return;
670     }
671
672     // We cache the parent FrameView here as the plugin widget could be deleted
673     // in the call to HandleEvent. See http://b/issue?id=1362948
674     FrameView* parentView = toFrameView(parent());
675
676     WebMouseEventBuilder webEvent(this, m_element->renderer(), *event);
677     if (webEvent.type == WebInputEvent::Undefined)
678         return;
679
680     if (event->type() == EventTypeNames::mousedown)
681         focusPlugin();
682
683     if (m_scrollbarGroup) {
684         // This needs to be set before the other callbacks in this scope, since
685         // the scroll animator class might query the position in response.
686         m_scrollbarGroup->setLastMousePosition(IntPoint(event->x(), event->y()));
687         if (event->type() == EventTypeNames::mousemove)
688             m_scrollbarGroup->scrollAnimator()->mouseMovedInContentArea();
689         else if (event->type() == EventTypeNames::mouseover)
690             m_scrollbarGroup->scrollAnimator()->mouseEnteredContentArea();
691         else if (event->type() == EventTypeNames::mouseout)
692             m_scrollbarGroup->scrollAnimator()->mouseExitedContentArea();
693     }
694
695     WebCursorInfo cursorInfo;
696     if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
697         event->setDefaultHandled();
698
699     // A windowless plugin can change the cursor in response to a mouse move
700     // event.  We need to reflect the changed cursor in the frame view as the
701     // mouse is moved in the boundaries of the windowless plugin.
702     Page* page = parentView->frame().page();
703     if (!page)
704         return;
705     toChromeClientImpl(page->chrome().client()).setCursorForPlugin(cursorInfo);
706 }
707
708 void WebPluginContainerImpl::handleDragEvent(MouseEvent* event)
709 {
710     ASSERT(event->isDragEvent());
711
712     WebDragStatus dragStatus = WebDragStatusUnknown;
713     if (event->type() == EventTypeNames::dragenter)
714         dragStatus = WebDragStatusEnter;
715     else if (event->type() == EventTypeNames::dragleave)
716         dragStatus = WebDragStatusLeave;
717     else if (event->type() == EventTypeNames::dragover)
718         dragStatus = WebDragStatusOver;
719     else if (event->type() == EventTypeNames::drop)
720         dragStatus = WebDragStatusDrop;
721
722     if (dragStatus == WebDragStatusUnknown)
723         return;
724
725     Clipboard* clipboard = event->dataTransfer();
726     WebDragData dragData(clipboard->dataObject());
727     WebDragOperationsMask dragOperationMask = static_cast<WebDragOperationsMask>(clipboard->sourceOperation());
728     WebPoint dragScreenLocation(event->screenX(), event->screenY());
729     WebPoint dragLocation(event->absoluteLocation().x() - location().x(), event->absoluteLocation().y() - location().y());
730
731     m_webPlugin->handleDragStatusUpdate(dragStatus, dragData, dragOperationMask, dragLocation, dragScreenLocation);
732 }
733
734 void WebPluginContainerImpl::handleWheelEvent(WheelEvent* event)
735 {
736     WebMouseWheelEventBuilder webEvent(this, m_element->renderer(), *event);
737     if (webEvent.type == WebInputEvent::Undefined)
738         return;
739
740     WebCursorInfo cursorInfo;
741     if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
742         event->setDefaultHandled();
743 }
744
745 void WebPluginContainerImpl::handleKeyboardEvent(KeyboardEvent* event)
746 {
747     WebKeyboardEventBuilder webEvent(*event);
748     if (webEvent.type == WebInputEvent::Undefined)
749         return;
750
751     if (webEvent.type == WebInputEvent::KeyDown) {
752 #if OS(MACOSX)
753         if (webEvent.modifiers == WebInputEvent::MetaKey
754 #else
755         if (webEvent.modifiers == WebInputEvent::ControlKey
756 #endif
757             && webEvent.windowsKeyCode == VKEY_C
758             // Only copy if there's a selection, so that we only ever do this
759             // for Pepper plugins that support copying.  Windowless NPAPI
760             // plugins will get the event as before.
761             && m_webPlugin->hasSelection()) {
762             copy();
763             event->setDefaultHandled();
764             return;
765         }
766     }
767
768     const WebInputEvent* currentInputEvent = WebViewImpl::currentInputEvent();
769
770     // Copy stashed info over, and only copy here in order not to interfere
771     // the ctrl-c logic above.
772     if (currentInputEvent
773         && WebInputEvent::isKeyboardEventType(currentInputEvent->type)) {
774         webEvent.modifiers |= currentInputEvent->modifiers &
775             (WebInputEvent::CapsLockOn | WebInputEvent::NumLockOn);
776     }
777
778     // Give the client a chance to issue edit comamnds.
779     WebViewImpl* view = WebViewImpl::fromPage(m_element->document().frame()->page());
780     if (m_webPlugin->supportsEditCommands() && view->client())
781         view->client()->handleCurrentKeyboardEvent();
782
783     WebCursorInfo cursorInfo;
784     if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
785         event->setDefaultHandled();
786 }
787
788 void WebPluginContainerImpl::handleTouchEvent(TouchEvent* event)
789 {
790     switch (m_touchEventRequestType) {
791     case TouchEventRequestTypeNone:
792         return;
793     case TouchEventRequestTypeRaw: {
794         WebTouchEventBuilder webEvent(this, m_element->renderer(), *event);
795         if (webEvent.type == WebInputEvent::Undefined)
796             return;
797
798         if (event->type() == EventTypeNames::touchstart)
799             focusPlugin();
800
801         WebCursorInfo cursorInfo;
802         if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
803             event->setDefaultHandled();
804         // FIXME: Can a plugin change the cursor from a touch-event callback?
805         return;
806     }
807     case TouchEventRequestTypeSynthesizedMouse:
808         synthesizeMouseEventIfPossible(event);
809         return;
810     }
811 }
812
813 static inline bool gestureScrollHelper(ScrollbarGroup* scrollbarGroup, ScrollDirection positiveDirection, ScrollDirection negativeDirection, float delta)
814 {
815     if (!delta)
816         return false;
817     float absDelta = delta > 0 ? delta : -delta;
818     return scrollbarGroup->scroll(delta < 0 ? negativeDirection : positiveDirection, ScrollByPrecisePixel, absDelta);
819 }
820
821 void WebPluginContainerImpl::handleGestureEvent(GestureEvent* event)
822 {
823     WebGestureEventBuilder webEvent(this, m_element->renderer(), *event);
824     if (webEvent.type == WebInputEvent::Undefined)
825         return;
826     WebCursorInfo cursorInfo;
827     if (m_webPlugin->handleInputEvent(webEvent, cursorInfo)) {
828         event->setDefaultHandled();
829         return;
830     }
831
832     if (webEvent.type == WebInputEvent::GestureScrollUpdate || webEvent.type == WebInputEvent::GestureScrollUpdateWithoutPropagation) {
833         if (!m_scrollbarGroup)
834             return;
835         if (gestureScrollHelper(m_scrollbarGroup.get(), ScrollLeft, ScrollRight, webEvent.data.scrollUpdate.deltaX))
836             event->setDefaultHandled();
837         if (gestureScrollHelper(m_scrollbarGroup.get(), ScrollUp, ScrollDown, webEvent.data.scrollUpdate.deltaY))
838             event->setDefaultHandled();
839     }
840     // FIXME: Can a plugin change the cursor from a touch-event callback?
841 }
842
843 void WebPluginContainerImpl::synthesizeMouseEventIfPossible(TouchEvent* event)
844 {
845     WebMouseEventBuilder webEvent(this, m_element->renderer(), *event);
846     if (webEvent.type == WebInputEvent::Undefined)
847         return;
848
849     WebCursorInfo cursorInfo;
850     if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
851         event->setDefaultHandled();
852 }
853
854 void WebPluginContainerImpl::focusPlugin()
855 {
856     LocalFrame& containingFrame = toFrameView(parent())->frame();
857     if (Page* currentPage = containingFrame.page())
858         currentPage->focusController().setFocusedElement(m_element, &containingFrame);
859     else
860         containingFrame.document()->setFocusedElement(m_element);
861 }
862
863 void WebPluginContainerImpl::calculateGeometry(const IntRect& frameRect,
864                                                IntRect& windowRect,
865                                                IntRect& clipRect,
866                                                Vector<IntRect>& cutOutRects)
867 {
868     windowRect = toScrollView(parent())->contentsToWindow(frameRect);
869
870     // Calculate a clip-rect so that we don't overlap the scrollbars, etc.
871     clipRect = windowClipRect();
872     clipRect.move(-windowRect.x(), -windowRect.y());
873
874     getPluginOcclusions(m_element, this->parent(), frameRect, cutOutRects);
875     // Convert to the plugin position.
876     for (size_t i = 0; i < cutOutRects.size(); i++)
877         cutOutRects[i].move(-frameRect.x(), -frameRect.y());
878 }
879
880 WebCore::IntRect WebPluginContainerImpl::windowClipRect() const
881 {
882     // Start by clipping to our bounds.
883     IntRect clipRect =
884         convertToContainingWindow(IntRect(0, 0, width(), height()));
885
886     // document().renderer() can be 0 when we receive messages from the
887     // plugins while we are destroying a frame.
888     // FIXME: Can we just check m_element->document().isActive() ?
889     if (m_element->renderer()->document().renderer()) {
890         // Take our element and get the clip rect from the enclosing layer and
891         // frame view.
892         clipRect.intersect(
893             m_element->document().view()->windowClipRectForFrameOwner(m_element));
894     }
895
896     return clipRect;
897 }
898
899 bool WebPluginContainerImpl::pluginShouldPersist() const
900 {
901     return m_webPlugin->shouldPersist();
902 }
903
904 } // namespace blink