OSDN Git Service

Merge WebKit at r78450: Initial merge by git.
[android-x86/external-webkit.git] / Source / 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 "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"
43 #include "WebKit.h"
44 #include "WebKitClient.h"
45 #include "WebPlugin.h"
46 #include "WebRect.h"
47 #include "WebString.h"
48 #include "WebURL.h"
49 #include "WebURLError.h"
50 #include "WebURLRequest.h"
51 #include "WebVector.h"
52 #include "WebViewImpl.h"
53 #include "WrappedResourceResponse.h"
54
55 #include "EventNames.h"
56 #include "FocusController.h"
57 #include "FormState.h"
58 #include "Frame.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"
70 #include "Page.h"
71 #include "RenderBox.h"
72 #include "ScrollView.h"
73 #include "UserGestureIndicator.h"
74 #include "WheelEvent.h"
75
76 #if WEBKIT_USING_SKIA
77 #include "PlatformContextSkia.h"
78 #endif
79
80 using namespace WebCore;
81
82 namespace WebKit {
83
84 // Public methods --------------------------------------------------------------
85
86 void WebPluginContainerImpl::setFrameRect(const IntRect& frameRect)
87 {
88     Widget::setFrameRect(frameRect);
89     reportGeometry();
90 }
91
92 void WebPluginContainerImpl::paint(GraphicsContext* gc, const IntRect& damageRect)
93 {
94     if (gc->paintingDisabled())
95         return;
96
97     if (!parent())
98         return;
99
100     // Don't paint anything if the plugin doesn't intersect the damage rect.
101     if (!frameRect().intersects(damageRect))
102         return;
103
104     gc->save();
105
106     ASSERT(parent()->isFrameView());
107     ScrollView* view = parent();
108
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()));
113
114 #if WEBKIT_USING_SKIA
115     WebCanvas* canvas = gc->platformContext()->canvas();
116 #elif WEBKIT_USING_CG
117     WebCanvas* canvas = gc->platformContext();
118 #endif
119
120     IntRect windowRect =
121         IntRect(view->contentsToWindow(damageRect.location()), damageRect.size());
122     m_webPlugin->paint(canvas, windowRect);
123
124     gc->restore();
125 }
126
127 void WebPluginContainerImpl::invalidateRect(const IntRect& rect)
128 {
129     if (!parent())
130         return;
131
132     RenderBox* renderer = toRenderBox(m_element->renderer());
133
134     IntRect dirtyRect = rect;
135     dirtyRect.move(renderer->borderLeft() + renderer->paddingLeft(),
136                    renderer->borderTop() + renderer->paddingTop());
137     renderer->repaintRectangle(dirtyRect);
138 }
139
140 void WebPluginContainerImpl::setFocus(bool focused)
141 {
142     Widget::setFocus(focused);
143     m_webPlugin->updateFocus(focused);
144 }
145
146 void WebPluginContainerImpl::show()
147 {
148     setSelfVisible(true);
149     m_webPlugin->updateVisibility(true);
150
151     Widget::show();
152 }
153
154 void WebPluginContainerImpl::hide()
155 {
156     setSelfVisible(false);
157     m_webPlugin->updateVisibility(false);
158
159     Widget::hide();
160 }
161
162 void WebPluginContainerImpl::handleEvent(Event* event)
163 {
164     if (!m_webPlugin->acceptsInputEvents())
165         return;
166
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));
177
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);
182 }
183
184 void WebPluginContainerImpl::frameRectsChanged()
185 {
186     Widget::frameRectsChanged();
187     reportGeometry();
188 }
189
190 void WebPluginContainerImpl::widgetPositionsUpdated()
191 {
192     Widget::widgetPositionsUpdated();
193     reportGeometry();
194 }
195
196 void WebPluginContainerImpl::setParentVisible(bool parentVisible)
197 {
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
202     // parent.
203
204     if (isParentVisible() == parentVisible)
205         return;  // No change.
206
207     Widget::setParentVisible(parentVisible);
208     if (!isSelfVisible())
209         return;  // This widget has explicitely been marked as not visible.
210
211     m_webPlugin->updateVisibility(isVisible());
212 }
213
214 void WebPluginContainerImpl::setParent(ScrollView* view)
215 {
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.
220
221     Widget::setParent(view);
222     if (view)
223         reportGeometry();
224 }
225
226 bool WebPluginContainerImpl::supportsPaginatedPrint() const
227 {
228     return m_webPlugin->supportsPaginatedPrint();
229 }
230
231 int WebPluginContainerImpl::printBegin(const IntRect& printableArea,
232                                        int printerDPI) const
233 {
234     return m_webPlugin->printBegin(printableArea, printerDPI);
235 }
236
237 bool WebPluginContainerImpl::printPage(int pageNumber,
238                                        WebCore::GraphicsContext* gc)
239 {
240     gc->save();
241 #if WEBKIT_USING_SKIA
242     WebCanvas* canvas = gc->platformContext()->canvas();
243 #elif WEBKIT_USING_CG
244     WebCanvas* canvas = gc->platformContext();
245 #endif
246     bool ret = m_webPlugin->printPage(pageNumber, canvas);
247     gc->restore();
248     return ret;
249 }
250
251 void WebPluginContainerImpl::printEnd()
252 {
253     return m_webPlugin->printEnd();
254 }
255
256 void WebPluginContainerImpl::copy()
257 {
258     if (!m_webPlugin->hasSelection())
259         return;
260
261     webKitClient()->clipboard()->writeHTML(m_webPlugin->selectionAsMarkup(), WebURL(), m_webPlugin->selectionAsText(), false);
262 }
263
264 WebElement WebPluginContainerImpl::element()
265 {
266     return WebElement(m_element);
267 }
268
269 void WebPluginContainerImpl::invalidate()
270 {
271     Widget::invalidate();
272 }
273
274 void WebPluginContainerImpl::invalidateRect(const WebRect& rect)
275 {
276     invalidateRect(static_cast<IntRect>(rect));
277 }
278
279 void WebPluginContainerImpl::scrollRect(int dx, int dy, const WebRect& rect)
280 {
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
288             // rectangle.
289             parent()->hostWindow()->scroll(scrollDelta, damageRect, damageRect);
290             return;
291         }
292     }
293
294     // Use slow scrolling instead.
295     invalidateRect(rect);
296 }
297
298 void WebPluginContainerImpl::reportGeometry()
299 {
300     if (!parent())
301         return;
302
303     IntRect windowRect, clipRect;
304     Vector<IntRect> cutOutRects;
305     calculateGeometry(frameRect(), windowRect, clipRect, cutOutRects);
306
307     m_webPlugin->updateGeometry(windowRect, clipRect, cutOutRects, isVisible());
308 }
309
310 void WebPluginContainerImpl::commitBackingTexture()
311 {
312 #if USE(ACCELERATED_COMPOSITING)
313     if (platformLayer())
314         platformLayer()->setNeedsDisplay();
315 #endif
316 }
317
318 void WebPluginContainerImpl::clearScriptObjects()
319 {
320     Frame* frame = m_element->document()->frame();
321     if (!frame)
322         return;
323     frame->script()->cleanupScriptObjectsForPlugin(this);
324 }
325
326 NPObject* WebPluginContainerImpl::scriptableObjectForElement()
327 {
328     return m_element->getNPObject();
329 }
330
331 WebString WebPluginContainerImpl::executeScriptURL(const WebURL& url, bool popupsAllowed)
332 {
333     Frame* frame = m_element->document()->frame();
334     if (!frame)
335         return WebString();
336
337     const KURL& kurl = url;
338     ASSERT(kurl.protocolIs("javascript"));
339
340     String script = decodeURLEscapeSequences(
341         kurl.string().substring(strlen("javascript:")));
342
343     ScriptValue result = frame->script()->executeScript(script, popupsAllowed);
344
345     // Failure is reported as a null string.
346     String resultStr;
347     result.getString(resultStr);
348     return resultStr;
349 }
350
351 void WebPluginContainerImpl::loadFrameRequest(
352     const WebURLRequest& request, const WebString& target, bool notifyNeeded, void* notifyData)
353 {
354     Frame* frame = m_element->document()->frame();
355     if (!frame)
356         return;  // FIXME: send a notification in this case?
357
358     if (notifyNeeded) {
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);
366     }
367
368     FrameLoadRequest frameRequest(frame->document()->securityOrigin(),
369         request.toResourceRequest(), target);
370
371     UserGestureIndicator gestureIndicator(request.hasUserGesture() ?
372         DefinitelyProcessingUserGesture : DefinitelyNotProcessingUserGesture);
373
374     frame->loader()->loadFrameRequest(
375         frameRequest,
376         false,  // lock history
377         false,  // lock back forward list
378         0,      // event
379         0,     // form state
380         SendReferrer);
381 }
382
383 void WebPluginContainerImpl::zoomLevelChanged(double zoomLevel)
384 {
385     WebViewImpl* view = WebViewImpl::fromPage(m_element->document()->frame()->page());
386     view->fullFramePluginZoomLevelChanged(zoomLevel);
387 }
388
389 void WebPluginContainerImpl::didReceiveResponse(const ResourceResponse& response)
390 {
391     // Make sure that the plugin receives window geometry before data, or else
392     // plugins misbehave.
393     frameRectsChanged();
394
395     WrappedResourceResponse urlResponse(response);
396     m_webPlugin->didReceiveResponse(urlResponse);
397 }
398
399 void WebPluginContainerImpl::didReceiveData(const char *data, int dataLength)
400 {
401     m_webPlugin->didReceiveData(data, dataLength);
402 }
403
404 void WebPluginContainerImpl::didFinishLoading()
405 {
406     m_webPlugin->didFinishLoading();
407 }
408
409 void WebPluginContainerImpl::didFailLoading(const ResourceError& error)
410 {
411     m_webPlugin->didFailLoading(error);
412 }
413
414 NPObject* WebPluginContainerImpl::scriptableObject()
415 {
416     return m_webPlugin->scriptableObject();
417 }
418
419 void WebPluginContainerImpl::willDestroyPluginLoadObserver(WebPluginLoadObserver* observer)
420 {
421     size_t pos = m_pluginLoadObservers.find(observer);
422     if (pos == notFound)
423         return;
424     m_pluginLoadObservers.remove(pos);
425 }
426
427 #if USE(ACCELERATED_COMPOSITING)
428 WebCore::LayerChromium* WebPluginContainerImpl::platformLayer() const
429 {
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)
434         return 0;
435
436     m_platformLayer->setTextureId(backingTextureId);
437
438     return m_platformLayer.get();
439 }
440 #endif
441
442 // Private methods -------------------------------------------------------------
443
444 WebPluginContainerImpl::WebPluginContainerImpl(WebCore::HTMLPlugInElement* element, WebPlugin* webPlugin)
445     : WebCore::PluginViewBase(0)
446     , m_element(element)
447     , m_webPlugin(webPlugin)
448 #if USE(ACCELERATED_COMPOSITING)
449     , m_platformLayer(PluginLayerChromium::create(0))
450 #endif
451 {
452 }
453
454 WebPluginContainerImpl::~WebPluginContainerImpl()
455 {
456     for (size_t i = 0; i < m_pluginLoadObservers.size(); ++i)
457         m_pluginLoadObservers[i]->clearPluginContainer();
458     m_webPlugin->destroy();
459 }
460
461 void WebPluginContainerImpl::handleMouseEvent(MouseEvent* event)
462 {
463     ASSERT(parent()->isFrameView());
464
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());
468
469     WebMouseEventBuilder webEvent(this, *event);
470     if (webEvent.type == WebInputEvent::Undefined)
471         return;
472
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);
480     }
481
482     WebCursorInfo cursorInfo;
483     if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
484         event->setDefaultHandled();
485
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();
490     if (!page)
491         return;
492     ChromeClientImpl* chromeClient =
493         static_cast<ChromeClientImpl*>(page->chrome()->client());
494     chromeClient->setCursorForPlugin(cursorInfo);
495 }
496
497 void WebPluginContainerImpl::handleWheelEvent(WheelEvent* event)
498 {
499     WebMouseWheelEventBuilder webEvent(this, *event);
500     if (webEvent.type == WebInputEvent::Undefined)
501         return;
502
503     WebCursorInfo cursorInfo;
504     if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
505         event->setDefaultHandled();
506 }
507
508 void WebPluginContainerImpl::handleKeyboardEvent(KeyboardEvent* event)
509 {
510     WebKeyboardEventBuilder webEvent(*event);
511     if (webEvent.type == WebInputEvent::Undefined)
512         return;
513
514     if (webEvent.type == WebInputEvent::KeyDown) {
515 #if defined(OS_MACOSX)
516         if (webEvent.modifiers == WebInputEvent::MetaKey
517 #else
518         if (webEvent.modifiers == WebInputEvent::ControlKey
519 #endif
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()) {
525             copy();
526             event->setDefaultHandled();
527             return;
528         }
529     }
530
531     const WebInputEvent* currentInputEvent = WebViewImpl::currentInputEvent();
532
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);
539     }
540
541     WebCursorInfo cursorInfo;
542     if (m_webPlugin->handleInputEvent(webEvent, cursorInfo))
543         event->setDefaultHandled();
544 }
545
546 void WebPluginContainerImpl::calculateGeometry(const IntRect& frameRect,
547                                                IntRect& windowRect,
548                                                IntRect& clipRect,
549                                                Vector<IntRect>& cutOutRects)
550 {
551     windowRect = IntRect(
552         parent()->contentsToWindow(frameRect.location()), frameRect.size());
553
554     // Calculate a clip-rect so that we don't overlap the scrollbars, etc.
555     clipRect = windowClipRect();
556     clipRect.move(-windowRect.x(), -windowRect.y());
557
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());
562 }
563
564 WebCore::IntRect WebPluginContainerImpl::windowClipRect() const
565 {
566     // Start by clipping to our bounds.
567     IntRect clipRect =
568         convertToContainingWindow(IntRect(0, 0, width(), height()));
569
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
574         // frame view.
575         RenderLayer* layer = m_element->renderer()->enclosingLayer();
576         clipRect.intersect(
577             m_element->document()->view()->windowClipRectForLayer(layer, true));
578     }
579
580     return clipRect;
581 }
582
583 } // namespace WebKit