2
* Copyright (C) 2010, 2012 Apple 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
7
* 1. Redistributions of source code must retain the above copyright
8
* notice, this list of conditions and the following disclaimer.
9
* 2. Redistributions in binary form must reproduce the above copyright
10
* notice, this list of conditions and the following disclaimer in the
11
* documentation and/or other materials provided with the distribution.
13
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23
* THE POSSIBILITY OF SUCH DAMAGE.
27
#include "PluginView.h"
29
#include "NPRuntimeUtilities.h"
31
#include "ShareableBitmap.h"
32
#include "WebCoreArgumentCoders.h"
35
#include "WebPageProxyMessages.h"
36
#include "WebProcess.h"
37
#include <WebCore/Chrome.h>
38
#include <WebCore/CookieJar.h>
39
#include <WebCore/Credential.h>
40
#include <WebCore/CredentialStorage.h>
41
#include <WebCore/DocumentLoader.h>
42
#include <WebCore/MouseEvent.h>
43
#include <WebCore/FocusController.h>
44
#include <WebCore/Frame.h>
45
#include <WebCore/FrameLoadRequest.h>
46
#include <WebCore/FrameLoaderClient.h>
47
#include <WebCore/FrameView.h>
48
#include <WebCore/GraphicsContext.h>
49
#include <WebCore/HTMLPlugInElement.h>
50
#include <WebCore/HostWindow.h>
51
#include <WebCore/NetscapePlugInStreamLoader.h>
52
#include <WebCore/NetworkingContext.h>
53
#include <WebCore/Page.h>
54
#include <WebCore/ProtectionSpace.h>
55
#include <WebCore/ProxyServer.h>
56
#include <WebCore/RenderEmbeddedObject.h>
57
#include <WebCore/ResourceLoadScheduler.h>
58
#include <WebCore/ScriptValue.h>
59
#include <WebCore/ScrollView.h>
60
#include <WebCore/SecurityOrigin.h>
61
#include <WebCore/SecurityPolicy.h>
62
#include <WebCore/Settings.h>
63
#include <WebCore/UserGestureIndicator.h>
64
#include <wtf/text/StringBuilder.h>
67
using namespace WebCore;
71
// This simulated mouse click delay in HTMLPlugInImageElement.cpp should generally be the same or shorter than this delay.
72
static const double pluginSnapshotTimerDelay = 1.1;
74
class PluginView::URLRequest : public RefCounted<URLRequest> {
76
static PassRefPtr<PluginView::URLRequest> create(uint64_t requestID, const FrameLoadRequest& request, bool allowPopups)
78
return adoptRef(new URLRequest(requestID, request, allowPopups));
81
uint64_t requestID() const { return m_requestID; }
82
const String& target() const { return m_request.frameName(); }
83
const ResourceRequest & request() const { return m_request.resourceRequest(); }
84
bool allowPopups() const { return m_allowPopups; }
87
URLRequest(uint64_t requestID, const FrameLoadRequest& request, bool allowPopups)
88
: m_requestID(requestID)
90
, m_allowPopups(allowPopups)
95
FrameLoadRequest m_request;
99
class PluginView::Stream : public RefCounted<PluginView::Stream>, NetscapePlugInStreamLoaderClient {
101
static PassRefPtr<Stream> create(PluginView* pluginView, uint64_t streamID, const ResourceRequest& request)
103
return adoptRef(new Stream(pluginView, streamID, request));
110
uint64_t streamID() const { return m_streamID; }
113
Stream(PluginView* pluginView, uint64_t streamID, const ResourceRequest& request)
114
: m_pluginView(pluginView)
115
, m_streamID(streamID)
117
, m_streamWasCancelled(false)
121
// NetscapePluginStreamLoaderClient
122
virtual void didReceiveResponse(NetscapePlugInStreamLoader*, const ResourceResponse&);
123
virtual void didReceiveData(NetscapePlugInStreamLoader*, const char*, int);
124
virtual void didFail(NetscapePlugInStreamLoader*, const ResourceError&);
125
virtual void didFinishLoading(NetscapePlugInStreamLoader*);
127
PluginView* m_pluginView;
129
const ResourceRequest m_request;
131
// True if the stream was explicitly cancelled by calling cancel().
132
// (As opposed to being cancelled by the user hitting the stop button for example.
133
bool m_streamWasCancelled;
135
RefPtr<NetscapePlugInStreamLoader> m_loader;
138
PluginView::Stream::~Stream()
140
ASSERT(!m_pluginView);
143
void PluginView::Stream::start()
147
Frame* frame = m_pluginView->m_pluginElement->document()->frame();
150
m_loader = resourceLoadScheduler()->schedulePluginStreamLoad(frame, this, m_request);
153
void PluginView::Stream::cancel()
157
m_streamWasCancelled = true;
158
m_loader->cancel(m_loader->cancelledError());
162
static String buildHTTPHeaders(const ResourceResponse& response, long long& expectedContentLength)
164
if (!response.isHTTP())
167
StringBuilder stringBuilder;
169
String statusLine = String::format("HTTP %d ", response.httpStatusCode());
170
stringBuilder.append(statusLine);
171
stringBuilder.append(response.httpStatusText());
172
stringBuilder.append('\n');
174
HTTPHeaderMap::const_iterator end = response.httpHeaderFields().end();
175
for (HTTPHeaderMap::const_iterator it = response.httpHeaderFields().begin(); it != end; ++it) {
176
stringBuilder.append(it->key);
177
stringBuilder.appendLiteral(": ");
178
stringBuilder.append(it->value);
179
stringBuilder.append('\n');
182
String headers = stringBuilder.toString();
184
// If the content is encoded (most likely compressed), then don't send its length to the plugin,
185
// which is only interested in the decoded length, not yet known at the moment.
186
// <rdar://problem/4470599> tracks a request for -[NSURLResponse expectedContentLength] to incorporate this logic.
187
String contentEncoding = response.httpHeaderField("Content-Encoding");
188
if (!contentEncoding.isNull() && contentEncoding != "identity")
189
expectedContentLength = -1;
194
void PluginView::Stream::didReceiveResponse(NetscapePlugInStreamLoader*, const ResourceResponse& response)
196
// Compute the stream related data from the resource response.
197
const KURL& responseURL = response.url();
198
const String& mimeType = response.mimeType();
199
long long expectedContentLength = response.expectedContentLength();
201
String headers = buildHTTPHeaders(response, expectedContentLength);
203
uint32_t streamLength = 0;
204
if (expectedContentLength > 0)
205
streamLength = expectedContentLength;
207
m_pluginView->m_plugin->streamDidReceiveResponse(m_streamID, responseURL, streamLength, response.lastModifiedDate(), mimeType, headers, response.suggestedFilename());
210
void PluginView::Stream::didReceiveData(NetscapePlugInStreamLoader*, const char* bytes, int length)
212
m_pluginView->m_plugin->streamDidReceiveData(m_streamID, bytes, length);
215
void PluginView::Stream::didFail(NetscapePlugInStreamLoader*, const ResourceError& error)
217
// Calling streamDidFail could cause us to be deleted, so we hold on to a reference here.
218
RefPtr<Stream> protect(this);
220
// We only want to call streamDidFail if the stream was not explicitly cancelled by the plug-in.
221
if (!m_streamWasCancelled)
222
m_pluginView->m_plugin->streamDidFail(m_streamID, error.isCancellation());
224
m_pluginView->removeStream(this);
228
void PluginView::Stream::didFinishLoading(NetscapePlugInStreamLoader*)
230
// Calling streamDidFinishLoading could cause us to be deleted, so we hold on to a reference here.
231
RefPtr<Stream> protectStream(this);
233
#if ENABLE(NETSCAPE_PLUGIN_API)
234
// Protect the plug-in while we're calling into it.
235
NPRuntimeObjectMap::PluginProtector pluginProtector(&m_pluginView->m_npRuntimeObjectMap);
237
m_pluginView->m_plugin->streamDidFinishLoading(m_streamID);
239
m_pluginView->removeStream(this);
243
static inline WebPage* webPage(HTMLPlugInElement* pluginElement)
245
Frame* frame = pluginElement->document()->frame();
248
WebPage* webPage = static_cast<WebFrameLoaderClient*>(frame->loader()->client())->webFrame()->page();
254
PassRefPtr<PluginView> PluginView::create(PassRefPtr<HTMLPlugInElement> pluginElement, PassRefPtr<Plugin> plugin, const Plugin::Parameters& parameters)
256
return adoptRef(new PluginView(pluginElement, plugin, parameters));
259
PluginView::PluginView(PassRefPtr<HTMLPlugInElement> pluginElement, PassRefPtr<Plugin> plugin, const Plugin::Parameters& parameters)
261
, m_pluginElement(pluginElement)
263
, m_webPage(webPage(m_pluginElement.get()))
264
, m_parameters(parameters)
265
, m_isInitialized(false)
266
, m_isWaitingForSynchronousInitialization(false)
267
, m_isWaitingUntilMediaCanStart(false)
268
, m_isBeingDestroyed(false)
269
, m_pendingURLRequestsTimer(RunLoop::main(), this, &PluginView::pendingURLRequestsTimerFired)
270
#if ENABLE(NETSCAPE_PLUGIN_API)
271
, m_npRuntimeObjectMap(this)
273
, m_manualStreamState(StreamStateInitial)
274
, m_pluginSnapshotTimer(this, &PluginView::pluginSnapshotTimerFired, pluginSnapshotTimerDelay)
275
, m_pageScaleFactor(1)
277
m_webPage->addPluginView(this);
280
PluginView::~PluginView()
283
m_webPage->removePluginView(this);
285
ASSERT(!m_isBeingDestroyed);
287
if (m_isWaitingUntilMediaCanStart)
288
m_pluginElement->document()->removeMediaCanStartListener(this);
290
destroyPluginAndReset();
292
// Null out the plug-in element explicitly so we'll crash earlier if we try to use
293
// the plug-in view after it's been destroyed.
294
m_pluginElement = nullptr;
297
void PluginView::destroyPluginAndReset()
299
// Cancel all pending frame loads.
300
for (FrameLoadMap::iterator it = m_pendingFrameLoads.begin(), end = m_pendingFrameLoads.end(); it != end; ++it)
301
it->key->setLoadListener(0);
304
m_isBeingDestroyed = true;
305
m_plugin->destroyPlugin();
306
m_isBeingDestroyed = false;
309
pluginFocusOrWindowFocusChanged(false);
313
#if ENABLE(NETSCAPE_PLUGIN_API)
314
// Invalidate the object map.
315
m_npRuntimeObjectMap.invalidate();
321
void PluginView::recreateAndInitialize(PassRefPtr<Plugin> plugin)
324
if (m_pluginSnapshotTimer.isActive())
325
m_pluginSnapshotTimer.stop();
326
destroyPluginAndReset();
329
// Reset member variables to initial values.
331
m_isInitialized = false;
332
m_isWaitingForSynchronousInitialization = false;
333
m_isWaitingUntilMediaCanStart = false;
334
m_isBeingDestroyed = false;
335
m_manualStreamState = StreamStateInitial;
336
m_transientPaintingSnapshot = nullptr;
341
Frame* PluginView::frame() const
343
return m_pluginElement->document()->frame();
346
void PluginView::manualLoadDidReceiveResponse(const ResourceResponse& response)
348
// The plug-in can be null here if it failed to initialize.
352
if (!m_isInitialized) {
353
ASSERT(m_manualStreamState == StreamStateInitial);
354
m_manualStreamState = StreamStateHasReceivedResponse;
355
m_manualStreamResponse = response;
359
// Compute the stream related data from the resource response.
360
const KURL& responseURL = response.url();
361
const String& mimeType = response.mimeType();
362
long long expectedContentLength = response.expectedContentLength();
364
String headers = buildHTTPHeaders(response, expectedContentLength);
366
uint32_t streamLength = 0;
367
if (expectedContentLength > 0)
368
streamLength = expectedContentLength;
370
m_plugin->manualStreamDidReceiveResponse(responseURL, streamLength, response.lastModifiedDate(), mimeType, headers, response.suggestedFilename());
373
void PluginView::manualLoadDidReceiveData(const char* bytes, int length)
375
// The plug-in can be null here if it failed to initialize.
379
if (!m_isInitialized) {
380
ASSERT(m_manualStreamState == StreamStateHasReceivedResponse);
381
if (!m_manualStreamData)
382
m_manualStreamData = SharedBuffer::create();
384
m_manualStreamData->append(bytes, length);
388
m_plugin->manualStreamDidReceiveData(bytes, length);
391
void PluginView::manualLoadDidFinishLoading()
393
// The plug-in can be null here if it failed to initialize.
397
if (!m_isInitialized) {
398
ASSERT(m_manualStreamState == StreamStateHasReceivedResponse);
399
m_manualStreamState = StreamStateFinished;
403
m_plugin->manualStreamDidFinishLoading();
406
void PluginView::manualLoadDidFail(const ResourceError& error)
408
// The plug-in can be null here if it failed to initialize.
412
if (!m_isInitialized) {
413
m_manualStreamState = StreamStateFinished;
414
m_manualStreamError = error;
415
m_manualStreamData = nullptr;
419
m_plugin->manualStreamDidFail(error.isCancellation());
422
RenderBoxModelObject* PluginView::renderer() const
424
return toRenderBoxModelObject(m_pluginElement->renderer());
427
void PluginView::pageScaleFactorDidChange()
429
viewGeometryDidChange();
432
void PluginView::setPageScaleFactor(double scaleFactor, IntPoint)
434
m_pageScaleFactor = scaleFactor;
435
m_webPage->send(Messages::WebPageProxy::PageScaleFactorDidChange(scaleFactor));
436
pageScaleFactorDidChange();
439
double PluginView::pageScaleFactor()
441
return m_pageScaleFactor;
444
void PluginView::webPageDestroyed()
450
void PluginView::setWindowIsVisible(bool windowIsVisible)
452
if (!m_isInitialized || !m_plugin)
455
m_plugin->windowVisibilityChanged(windowIsVisible);
458
void PluginView::setWindowIsFocused(bool windowIsFocused)
460
if (!m_isInitialized || !m_plugin)
463
m_plugin->windowFocusChanged(windowIsFocused);
466
void PluginView::setDeviceScaleFactor(float scaleFactor)
468
if (!m_isInitialized || !m_plugin)
471
m_plugin->contentsScaleFactorChanged(scaleFactor);
474
void PluginView::windowAndViewFramesChanged(const IntRect& windowFrameInScreenCoordinates, const IntRect& viewFrameInWindowCoordinates)
476
if (!m_isInitialized || !m_plugin)
479
m_plugin->windowAndViewFramesChanged(windowFrameInScreenCoordinates, viewFrameInWindowCoordinates);
482
bool PluginView::sendComplexTextInput(uint64_t pluginComplexTextInputIdentifier, const String& textInput)
487
if (m_plugin->pluginComplexTextInputIdentifier() != pluginComplexTextInputIdentifier)
490
m_plugin->sendComplexTextInput(textInput);
494
void PluginView::setLayerHostingMode(LayerHostingMode layerHostingMode)
499
if (!m_isInitialized) {
500
m_parameters.layerHostingMode = layerHostingMode;
504
m_plugin->setLayerHostingMode(layerHostingMode);
509
void PluginView::initializePlugin()
515
// We've already tried and failed to initialize the plug-in.
519
if (Frame* frame = m_pluginElement->document()->frame()) {
520
if (Page* page = frame->page()) {
522
// We shouldn't initialize the plug-in right now, add a listener.
523
if (!page->canStartMedia()) {
524
if (m_isWaitingUntilMediaCanStart)
527
m_isWaitingUntilMediaCanStart = true;
528
m_pluginElement->document()->addMediaCanStartListener(this);
534
m_plugin->initialize(this, m_parameters);
536
// Plug-in initialization continued in didFailToInitializePlugin() or didInitializePlugin().
539
void PluginView::didFailToInitializePlugin()
542
m_webPage->send(Messages::WebPageProxy::DidFailToInitializePlugin(m_parameters.mimeType));
545
void PluginView::didInitializePlugin()
547
m_isInitialized = true;
550
windowAndViewFramesChanged(m_webPage->windowFrameInScreenCoordinates(), m_webPage->viewFrameInWindowCoordinates());
553
viewGeometryDidChange();
555
redeliverManualStream();
558
if (m_pluginElement->displayState() < HTMLPlugInElement::PlayingWithPendingMouseClick)
559
m_pluginSnapshotTimer.restart();
561
if (m_plugin->pluginLayer()) {
563
frame()->view()->enterCompositingMode();
564
m_pluginElement->setNeedsStyleRecalc(SyntheticStyleChange);
567
if (m_pluginElement->displayState() < HTMLPlugInElement::Playing)
568
m_pluginElement->dispatchPendingMouseClick();
571
setWindowIsVisible(m_webPage->windowIsVisible());
572
setWindowIsFocused(m_webPage->windowIsFocused());
575
if (wantsWheelEvents()) {
576
if (Frame* frame = m_pluginElement->document()->frame()) {
577
if (FrameView* frameView = frame->view())
578
frameView->setNeedsLayout();
584
PlatformLayer* PluginView::platformLayer() const
586
// The plug-in can be null here if it failed to initialize.
587
if (!m_isInitialized || !m_plugin)
590
return m_plugin->pluginLayer();
594
JSObject* PluginView::scriptObject(JSGlobalObject* globalObject)
596
// If we're already waiting for synchronous initialization of the plugin,
597
// calls to scriptObject() are from the plug-in itself and need to return 0;
598
if (m_isWaitingForSynchronousInitialization)
601
// We might not have started initialization of the plug-in yet, the plug-in might be in the middle
602
// of being initializing asynchronously, or initialization might have previously failed.
603
if (!m_isInitialized || !m_plugin)
606
#if ENABLE(NETSCAPE_PLUGIN_API)
607
NPObject* scriptableNPObject = m_plugin->pluginScriptableNPObject();
608
if (!scriptableNPObject)
611
JSObject* jsObject = m_npRuntimeObjectMap.getOrCreateJSObject(globalObject, scriptableNPObject);
612
releaseNPObject(scriptableNPObject);
616
UNUSED_PARAM(globalObject);
621
void PluginView::storageBlockingStateChanged()
623
// The plug-in can be null here if it failed to initialize.
624
if (!m_isInitialized || !m_plugin)
627
bool storageBlockingPolicy = !frame()->document()->securityOrigin()->canAccessPluginStorage(frame()->tree()->top()->document()->securityOrigin());
629
m_plugin->storageBlockingStateChanged(storageBlockingPolicy);
632
void PluginView::privateBrowsingStateChanged(bool privateBrowsingEnabled)
634
// The plug-in can be null here if it failed to initialize.
635
if (!m_isInitialized || !m_plugin)
638
m_plugin->privateBrowsingStateChanged(privateBrowsingEnabled);
641
bool PluginView::getFormValue(String& formValue)
643
// The plug-in can be null here if it failed to initialize.
644
if (!m_isInitialized || !m_plugin)
647
return m_plugin->getFormValue(formValue);
650
bool PluginView::scroll(ScrollDirection direction, ScrollGranularity granularity)
652
// The plug-in can be null here if it failed to initialize.
653
if (!m_isInitialized || !m_plugin)
656
return m_plugin->handleScroll(direction, granularity);
659
Scrollbar* PluginView::horizontalScrollbar()
661
// The plug-in can be null here if it failed to initialize.
662
if (!m_isInitialized || !m_plugin)
665
return m_plugin->horizontalScrollbar();
668
Scrollbar* PluginView::verticalScrollbar()
670
// The plug-in can be null here if it failed to initialize.
671
if (!m_isInitialized || !m_plugin)
674
return m_plugin->verticalScrollbar();
677
bool PluginView::wantsWheelEvents()
679
// The plug-in can be null here if it failed to initialize.
680
if (!m_isInitialized || !m_plugin)
683
return m_plugin->wantsWheelEvents();
686
void PluginView::setFrameRect(const WebCore::IntRect& rect)
688
Widget::setFrameRect(rect);
689
viewGeometryDidChange();
692
void PluginView::paint(GraphicsContext* context, const IntRect& /*dirtyRect*/)
694
if (!m_plugin || !m_isInitialized || m_pluginElement->displayState() < HTMLPlugInElement::PlayingWithPendingMouseClick)
697
if (context->paintingDisabled()) {
698
if (context->updatingControlTints())
699
m_plugin->updateControlTints(context);
703
// FIXME: We should try to intersect the dirty rect with the plug-in's clip rect here.
704
IntRect paintRect = IntRect(IntPoint(), frameRect().size());
706
if (paintRect.isEmpty())
709
if (m_transientPaintingSnapshot) {
710
m_transientPaintingSnapshot->paint(*context, contentsScaleFactor(), frameRect().location(), m_transientPaintingSnapshot->bounds());
714
GraphicsContextStateSaver stateSaver(*context);
716
// Translate the coordinate system so that the origin is in the top-left corner of the plug-in.
717
context->translate(frameRect().location().x(), frameRect().location().y());
719
m_plugin->paint(context, paintRect);
722
void PluginView::frameRectsChanged()
724
Widget::frameRectsChanged();
725
viewGeometryDidChange();
728
void PluginView::setParent(ScrollView* scrollView)
730
Widget::setParent(scrollView);
736
PassOwnPtr<WebEvent> PluginView::createWebEvent(MouseEvent* event) const
738
WebEvent::Type type = WebEvent::NoType;
739
unsigned clickCount = 1;
740
if (event->type() == eventNames().mousedownEvent)
741
type = WebEvent::MouseDown;
742
else if (event->type() == eventNames().mouseupEvent)
743
type = WebEvent::MouseUp;
744
else if (event->type() == eventNames().mouseoverEvent) {
745
type = WebEvent::MouseMove;
747
} else if (event->type() == eventNames().clickEvent)
750
ASSERT_NOT_REACHED();
752
WebMouseEvent::Button button = WebMouseEvent::NoButton;
753
switch (event->button()) {
754
case WebCore::LeftButton:
755
button = WebMouseEvent::LeftButton;
757
case WebCore::MiddleButton:
758
button = WebMouseEvent::MiddleButton;
760
case WebCore::RightButton:
761
button = WebMouseEvent::RightButton;
764
ASSERT_NOT_REACHED();
768
unsigned modifiers = 0;
769
if (event->shiftKey())
770
modifiers |= WebEvent::ShiftKey;
771
if (event->ctrlKey())
772
modifiers |= WebEvent::ControlKey;
774
modifiers |= WebEvent::AltKey;
775
if (event->metaKey())
776
modifiers |= WebEvent::MetaKey;
778
return adoptPtr(new WebMouseEvent(type, button, m_plugin->convertToRootView(IntPoint(event->offsetX(), event->offsetY())), event->screenLocation(), 0, 0, 0, clickCount, static_cast<WebEvent::Modifiers>(modifiers), 0));
781
void PluginView::handleEvent(Event* event)
783
if (!m_isInitialized || !m_plugin)
786
const WebEvent* currentEvent = WebPage::currentEvent();
787
OwnPtr<WebEvent> simulatedWebEvent;
788
if (event->isMouseEvent() && toMouseEvent(event)->isSimulated()) {
789
simulatedWebEvent = createWebEvent(toMouseEvent(event));
790
currentEvent = simulatedWebEvent.get();
795
bool didHandleEvent = false;
797
if ((event->type() == eventNames().mousemoveEvent && currentEvent->type() == WebEvent::MouseMove)
798
|| (event->type() == eventNames().mousedownEvent && currentEvent->type() == WebEvent::MouseDown)
799
|| (event->type() == eventNames().mouseupEvent && currentEvent->type() == WebEvent::MouseUp)) {
800
// We have a mouse event.
802
// FIXME: Clicking in a scroll bar should not change focus.
803
if (currentEvent->type() == WebEvent::MouseDown) {
804
focusPluginElement();
805
frame()->eventHandler()->setCapturingMouseEventsNode(m_pluginElement.get());
806
} else if (currentEvent->type() == WebEvent::MouseUp)
807
frame()->eventHandler()->setCapturingMouseEventsNode(0);
809
didHandleEvent = m_plugin->handleMouseEvent(static_cast<const WebMouseEvent&>(*currentEvent));
810
} else if (event->type() == eventNames().mousewheelEvent && currentEvent->type() == WebEvent::Wheel && m_plugin->wantsWheelEvents()) {
811
// We have a wheel event.
812
didHandleEvent = m_plugin->handleWheelEvent(static_cast<const WebWheelEvent&>(*currentEvent));
813
} else if (event->type() == eventNames().mouseoverEvent && currentEvent->type() == WebEvent::MouseMove) {
814
// We have a mouse enter event.
815
didHandleEvent = m_plugin->handleMouseEnterEvent(static_cast<const WebMouseEvent&>(*currentEvent));
816
} else if (event->type() == eventNames().mouseoutEvent && currentEvent->type() == WebEvent::MouseMove) {
817
// We have a mouse leave event.
818
didHandleEvent = m_plugin->handleMouseLeaveEvent(static_cast<const WebMouseEvent&>(*currentEvent));
819
} else if (event->type() == eventNames().contextmenuEvent && currentEvent->type() == WebEvent::MouseDown) {
820
// We have a context menu event.
821
didHandleEvent = m_plugin->handleContextMenuEvent(static_cast<const WebMouseEvent&>(*currentEvent));
822
} else if ((event->type() == eventNames().keydownEvent && currentEvent->type() == WebEvent::KeyDown)
823
|| (event->type() == eventNames().keyupEvent && currentEvent->type() == WebEvent::KeyUp)) {
824
// We have a keyboard event.
825
didHandleEvent = m_plugin->handleKeyboardEvent(static_cast<const WebKeyboardEvent&>(*currentEvent));
829
event->setDefaultHandled();
832
bool PluginView::handleEditingCommand(const String& commandName, const String& argument)
834
if (!m_isInitialized || !m_plugin)
837
return m_plugin->handleEditingCommand(commandName, argument);
840
bool PluginView::isEditingCommandEnabled(const String& commandName)
842
if (!m_isInitialized || !m_plugin)
845
return m_plugin->isEditingCommandEnabled(commandName);
848
bool PluginView::shouldAllowScripting()
850
if (!m_isInitialized || !m_plugin)
853
return m_plugin->shouldAllowScripting();
856
void PluginView::notifyWidget(WidgetNotification notification)
858
switch (notification) {
859
case WillPaintFlattened:
860
if (m_plugin && m_isInitialized)
861
m_transientPaintingSnapshot = m_plugin->snapshot();
863
case DidPaintFlattened:
864
m_transientPaintingSnapshot = nullptr;
869
void PluginView::show()
871
bool wasVisible = isVisible();
873
setSelfVisible(true);
876
viewVisibilityDidChange();
881
void PluginView::hide()
883
bool wasVisible = isVisible();
885
setSelfVisible(false);
888
viewVisibilityDidChange();
893
bool PluginView::transformsAffectFrameRect()
898
void PluginView::viewGeometryDidChange()
900
if (!m_isInitialized || !m_plugin || !parent())
904
float pageScaleFactor = frame()->page() ? frame()->page()->pageScaleFactor() : 1;
906
IntPoint scaledFrameRectLocation(frameRect().location().x() * pageScaleFactor, frameRect().location().y() * pageScaleFactor);
907
IntPoint scaledLocationInRootViewCoordinates(parent()->contentsToRootView(scaledFrameRectLocation));
909
// FIXME: We still don't get the right coordinates for transformed plugins.
910
AffineTransform transform;
911
transform.translate(scaledLocationInRootViewCoordinates.x(), scaledLocationInRootViewCoordinates.y());
912
transform.scale(pageScaleFactor);
914
// FIXME: The way we calculate this clip rect isn't correct.
915
// But it is still important to distinguish between empty and non-empty rects so we can notify the plug-in when it becomes invisible.
916
// Making the rect actually correct is covered by https://bugs.webkit.org/show_bug.cgi?id=95362
917
IntRect clipRect = boundsRect();
919
// FIXME: We can only get a semi-reliable answer from clipRectInWindowCoordinates() when the page is not scaled.
920
// Fixing that is tracked in <rdar://problem/9026611> - Make the Widget hierarchy play nicely with transforms, for zoomed plug-ins and iframes
921
if (pageScaleFactor == 1) {
922
clipRect = clipRectInWindowCoordinates();
923
if (!clipRect.isEmpty())
924
clipRect = boundsRect();
927
m_plugin->geometryDidChange(size(), clipRect, transform);
930
void PluginView::viewVisibilityDidChange()
932
if (!m_isInitialized || !m_plugin || !parent())
935
m_plugin->visibilityDidChange();
938
IntRect PluginView::clipRectInWindowCoordinates() const
940
// Get the frame rect in window coordinates.
941
IntRect frameRectInWindowCoordinates = parent()->contentsToWindow(frameRect());
943
Frame* frame = this->frame();
945
// Get the window clip rect for the plugin element (in window coordinates).
946
IntRect windowClipRect = frame->view()->windowClipRectForFrameOwner(m_pluginElement.get(), true);
948
// Intersect the two rects to get the view clip rect in window coordinates.
949
frameRectInWindowCoordinates.intersect(windowClipRect);
951
return frameRectInWindowCoordinates;
954
void PluginView::focusPluginElement()
958
if (Page* page = frame()->page())
959
page->focusController()->setFocusedNode(m_pluginElement.get(), frame());
961
frame()->document()->setFocusedNode(m_pluginElement);
964
void PluginView::pendingURLRequestsTimerFired()
966
ASSERT(!m_pendingURLRequests.isEmpty());
968
RefPtr<URLRequest> urlRequest = m_pendingURLRequests.takeFirst();
970
// If there are more requests to perform, reschedule the timer.
971
if (!m_pendingURLRequests.isEmpty())
972
m_pendingURLRequestsTimer.startOneShot(0);
974
performURLRequest(urlRequest.get());
977
void PluginView::performURLRequest(URLRequest* request)
979
// This protector is needed to make sure the PluginView is not destroyed while it is still needed.
980
RefPtr<PluginView> protect(this);
982
// First, check if this is a javascript: url.
983
if (protocolIsJavaScript(request->request().url())) {
984
performJavaScriptURLRequest(request);
988
if (!request->target().isNull()) {
989
performFrameLoadURLRequest(request);
993
// This request is to load a URL and create a stream.
994
RefPtr<Stream> stream = PluginView::Stream::create(this, request->requestID(), request->request());
995
addStream(stream.get());
999
void PluginView::performFrameLoadURLRequest(URLRequest* request)
1001
ASSERT(!request->target().isNull());
1003
Frame* frame = m_pluginElement->document()->frame();
1007
if (!m_pluginElement->document()->securityOrigin()->canDisplay(request->request().url())) {
1008
// We can't load the request, send back a reply to the plug-in.
1009
m_plugin->frameDidFail(request->requestID(), false);
1013
// First, try to find a target frame.
1014
Frame* targetFrame = frame->loader()->findFrameForNavigation(request->target());
1016
// We did not find a target frame. Ask our frame to load the page. This may or may not create a popup window.
1017
FrameLoadRequest frameRequest(frame, request->request());
1018
frameRequest.setFrameName(request->target());
1019
frameRequest.setShouldCheckNewWindowPolicy(true);
1020
frame->loader()->load(frameRequest);
1022
// FIXME: We don't know whether the window was successfully created here so we just assume that it worked.
1023
// It's better than not telling the plug-in anything.
1024
m_plugin->frameDidFinishLoading(request->requestID());
1028
// Now ask the frame to load the request.
1029
targetFrame->loader()->load(FrameLoadRequest(targetFrame, request->request()));
1031
WebFrame* targetWebFrame = static_cast<WebFrameLoaderClient*>(targetFrame->loader()->client())->webFrame();
1032
if (WebFrame::LoadListener* loadListener = targetWebFrame->loadListener()) {
1033
// Check if another plug-in view or even this view is waiting for the frame to load.
1034
// If it is, tell it that the load was cancelled because it will be anyway.
1035
loadListener->didFailLoad(targetWebFrame, true);
1038
m_pendingFrameLoads.set(targetWebFrame, request);
1039
targetWebFrame->setLoadListener(this);
1042
void PluginView::performJavaScriptURLRequest(URLRequest* request)
1044
ASSERT(protocolIsJavaScript(request->request().url()));
1046
RefPtr<Frame> frame = m_pluginElement->document()->frame();
1050
String jsString = decodeURLEscapeSequences(request->request().url().string().substring(sizeof("javascript:") - 1));
1052
if (!request->target().isNull()) {
1053
// For security reasons, only allow JS requests to be made on the frame that contains the plug-in.
1054
if (frame->tree()->find(request->target()) != frame) {
1055
// Let the plug-in know that its frame load failed.
1056
m_plugin->frameDidFail(request->requestID(), false);
1061
// Evaluate the JavaScript code. Note that running JavaScript here could cause the plug-in to be destroyed, so we
1062
// grab references to the plug-in here.
1063
RefPtr<Plugin> plugin = m_plugin;
1064
ScriptValue result = frame->script()->executeScript(jsString, request->allowPopups());
1066
// Check if evaluating the JavaScript destroyed the plug-in.
1067
if (!plugin->controller())
1070
// Don't notify the plug-in at all about targeted javascript: requests. This matches Mozilla and WebKit1.
1071
if (!request->target().isNull())
1074
ScriptState* scriptState = frame->script()->globalObject(pluginWorld())->globalExec();
1075
String resultString;
1076
result.getString(scriptState, resultString);
1078
// Send the result back to the plug-in.
1079
plugin->didEvaluateJavaScript(request->requestID(), resultString);
1082
void PluginView::addStream(Stream* stream)
1084
ASSERT(!m_streams.contains(stream->streamID()));
1085
m_streams.set(stream->streamID(), stream);
1088
void PluginView::removeStream(Stream* stream)
1090
ASSERT(m_streams.get(stream->streamID()) == stream);
1092
m_streams.remove(stream->streamID());
1095
void PluginView::cancelAllStreams()
1097
Vector<RefPtr<Stream> > streams;
1098
copyValuesToVector(m_streams, streams);
1100
for (size_t i = 0; i < streams.size(); ++i)
1101
streams[i]->cancel();
1103
// Cancelling a stream removes it from the m_streams map, so if we cancel all streams the map should be empty.
1104
ASSERT(m_streams.isEmpty());
1107
void PluginView::redeliverManualStream()
1109
if (m_manualStreamState == StreamStateInitial) {
1114
if (m_manualStreamState == StreamStateFailed) {
1115
manualLoadDidFail(m_manualStreamError);
1119
// Deliver the response.
1120
manualLoadDidReceiveResponse(m_manualStreamResponse);
1122
// Deliver the data.
1123
if (m_manualStreamData) {
1125
unsigned position = 0;
1127
while (unsigned length = m_manualStreamData->getSomeData(data, position)) {
1128
manualLoadDidReceiveData(data, length);
1132
m_manualStreamData = nullptr;
1135
if (m_manualStreamState == StreamStateFinished)
1136
manualLoadDidFinishLoading();
1139
void PluginView::invalidateRect(const IntRect& dirtyRect)
1141
if (!parent() || !m_plugin || !m_isInitialized)
1145
if (m_plugin->pluginLayer())
1149
if (m_pluginElement->displayState() < HTMLPlugInElement::PlayingWithPendingMouseClick)
1152
RenderBoxModelObject* renderer = toRenderBoxModelObject(m_pluginElement->renderer());
1156
IntRect contentRect(dirtyRect);
1157
contentRect.move(renderer->borderLeft() + renderer->paddingLeft(), renderer->borderTop() + renderer->paddingTop());
1158
renderer->repaintRectangle(contentRect);
1161
void PluginView::setFocus(bool hasFocus)
1163
Widget::setFocus(hasFocus);
1165
if (!m_isInitialized || !m_plugin)
1168
m_plugin->setFocus(hasFocus);
1171
void PluginView::mediaCanStart()
1173
ASSERT(m_isWaitingUntilMediaCanStart);
1174
m_isWaitingUntilMediaCanStart = false;
1179
bool PluginView::isPluginVisible()
1184
void PluginView::invalidate(const IntRect& dirtyRect)
1186
invalidateRect(dirtyRect);
1189
String PluginView::userAgent()
1191
Frame* frame = m_pluginElement->document()->frame();
1195
return frame->loader()->client()->userAgent(KURL());
1198
void PluginView::loadURL(uint64_t requestID, const String& method, const String& urlString, const String& target,
1199
const HTTPHeaderMap& headerFields, const Vector<uint8_t>& httpBody, bool allowPopups)
1201
FrameLoadRequest frameLoadRequest(m_pluginElement->document()->securityOrigin());
1202
frameLoadRequest.resourceRequest().setHTTPMethod(method);
1203
frameLoadRequest.resourceRequest().setURL(m_pluginElement->document()->completeURL(urlString));
1204
frameLoadRequest.resourceRequest().addHTTPHeaderFields(headerFields);
1205
frameLoadRequest.resourceRequest().setHTTPBody(FormData::create(httpBody.data(), httpBody.size()));
1206
frameLoadRequest.setFrameName(target);
1208
String referrer = SecurityPolicy::generateReferrerHeader(frame()->document()->referrerPolicy(), frameLoadRequest.resourceRequest().url(), frame()->loader()->outgoingReferrer());
1209
if (!referrer.isEmpty())
1210
frameLoadRequest.resourceRequest().setHTTPReferrer(referrer);
1212
m_pendingURLRequests.append(URLRequest::create(requestID, frameLoadRequest, allowPopups));
1213
m_pendingURLRequestsTimer.startOneShot(0);
1216
void PluginView::cancelStreamLoad(uint64_t streamID)
1218
// Keep a reference to the stream. Stream::cancel might remove the stream from the map, and thus
1219
// releasing its last reference.
1220
RefPtr<Stream> stream = m_streams.get(streamID).get();
1224
// Cancelling the stream here will remove it from the map.
1226
ASSERT(!m_streams.contains(streamID));
1229
void PluginView::cancelManualStreamLoad()
1234
DocumentLoader* documentLoader = frame()->loader()->activeDocumentLoader();
1235
ASSERT(documentLoader);
1237
if (documentLoader->isLoadingMainResource())
1238
documentLoader->cancelMainResourceLoad(frame()->loader()->cancelledError(m_parameters.url));
1241
#if ENABLE(NETSCAPE_PLUGIN_API)
1242
NPObject* PluginView::windowScriptNPObject()
1247
if (!frame()->script()->canExecuteScripts(NotAboutToExecuteScript)) {
1248
// FIXME: Investigate if other browsers allow plug-ins to access JavaScript objects even if JavaScript is disabled.
1252
return m_npRuntimeObjectMap.getOrCreateNPObject(*pluginWorld()->globalData(), frame()->script()->windowShell(pluginWorld())->window());
1255
NPObject* PluginView::pluginElementNPObject()
1260
if (!frame()->script()->canExecuteScripts(NotAboutToExecuteScript)) {
1261
// FIXME: Investigate if other browsers allow plug-ins to access JavaScript objects even if JavaScript is disabled.
1265
JSObject* object = frame()->script()->jsObjectForPluginElement(m_pluginElement.get());
1268
return m_npRuntimeObjectMap.getOrCreateNPObject(*pluginWorld()->globalData(), object);
1271
bool PluginView::evaluate(NPObject* npObject, const String& scriptString, NPVariant* result, bool allowPopups)
1273
// FIXME: Is this check necessary?
1274
if (!m_pluginElement->document()->frame())
1277
// Calling evaluate will run JavaScript that can potentially remove the plug-in element, so we need to
1278
// protect the plug-in view from destruction.
1279
NPRuntimeObjectMap::PluginProtector pluginProtector(&m_npRuntimeObjectMap);
1281
UserGestureIndicator gestureIndicator(allowPopups ? DefinitelyProcessingUserGesture : PossiblyProcessingUserGesture);
1282
return m_npRuntimeObjectMap.evaluate(npObject, scriptString, result);
1286
void PluginView::setStatusbarText(const String& statusbarText)
1291
Page* page = frame()->page();
1295
page->chrome()->setStatusbarText(frame(), statusbarText);
1298
bool PluginView::isAcceleratedCompositingEnabled()
1303
Settings* settings = frame()->settings();
1307
if (m_pluginElement->displayState() < HTMLPlugInElement::PlayingWithPendingMouseClick)
1309
return settings->acceleratedCompositingEnabled();
1312
void PluginView::pluginProcessCrashed()
1314
if (!m_pluginElement->renderer())
1317
// FIXME: The renderer could also be a RenderApplet, we should handle that.
1318
if (!m_pluginElement->renderer()->isEmbeddedObject())
1321
RenderEmbeddedObject* renderer = toRenderEmbeddedObject(m_pluginElement->renderer());
1322
renderer->setPluginUnavailabilityReason(RenderEmbeddedObject::PluginCrashed);
1324
Widget::invalidate();
1327
void PluginView::willSendEventToPlugin()
1329
// If we're sending an event to a plug-in, we can't control how long the plug-in
1330
// takes to process it (e.g. it may display a context menu), so we tell the UI process
1331
// to stop the responsiveness timer in this case.
1332
m_webPage->send(Messages::WebPageProxy::StopResponsivenessTimer());
1336
HWND PluginView::nativeParentWindow()
1338
return m_webPage->nativeWindow();
1341
void PluginView::scheduleWindowedPluginGeometryUpdate(const WindowGeometry& geometry)
1343
m_webPage->drawingArea()->scheduleChildWindowGeometryUpdate(geometry);
1348
void PluginView::pluginFocusOrWindowFocusChanged(bool pluginHasFocusAndWindowHasFocus)
1351
m_webPage->send(Messages::WebPageProxy::PluginFocusOrWindowFocusChanged(m_plugin->pluginComplexTextInputIdentifier(), pluginHasFocusAndWindowHasFocus));
1354
void PluginView::setComplexTextInputState(PluginComplexTextInputState pluginComplexTextInputState)
1357
m_webPage->send(Messages::WebPageProxy::SetPluginComplexTextInputState(m_plugin->pluginComplexTextInputIdentifier(), pluginComplexTextInputState));
1360
mach_port_t PluginView::compositingRenderServerPort()
1362
return WebProcess::shared().compositingRenderServerPort();
1366
float PluginView::contentsScaleFactor()
1368
if (Page* page = frame() ? frame()->page() : 0)
1369
return page->deviceScaleFactor();
1374
String PluginView::proxiesForURL(const String& urlString)
1376
const FrameLoader* frameLoader = frame() ? frame()->loader() : 0;
1377
const NetworkingContext* context = frameLoader ? frameLoader->networkingContext() : 0;
1378
Vector<ProxyServer> proxyServers = proxyServersForURL(KURL(KURL(), urlString), context);
1379
return toString(proxyServers);
1382
String PluginView::cookiesForURL(const String& urlString)
1384
return cookies(m_pluginElement->document(), KURL(KURL(), urlString));
1387
void PluginView::setCookiesForURL(const String& urlString, const String& cookieString)
1389
setCookies(m_pluginElement->document(), KURL(KURL(), urlString), cookieString);
1392
bool PluginView::getAuthenticationInfo(const ProtectionSpace& protectionSpace, String& username, String& password)
1394
Credential credential = CredentialStorage::get(protectionSpace);
1395
if (credential.isEmpty())
1396
credential = CredentialStorage::getFromPersistentStorage(protectionSpace);
1398
if (!credential.hasPassword())
1401
username = credential.user();
1402
password = credential.password();
1407
bool PluginView::isPrivateBrowsingEnabled()
1409
// If we can't get the real setting, we'll assume that private browsing is enabled.
1413
if (!frame()->document()->securityOrigin()->canAccessPluginStorage(frame()->tree()->top()->document()->securityOrigin()))
1416
Settings* settings = frame()->settings();
1420
return settings->privateBrowsingEnabled();
1423
bool PluginView::asynchronousPluginInitializationEnabled() const
1425
return m_webPage->asynchronousPluginInitializationEnabled();
1428
bool PluginView::asynchronousPluginInitializationEnabledForAllPlugins() const
1430
return m_webPage->asynchronousPluginInitializationEnabledForAllPlugins();
1433
bool PluginView::artificialPluginInitializationDelayEnabled() const
1435
return m_webPage->artificialPluginInitializationDelayEnabled();
1438
void PluginView::protectPluginFromDestruction()
1440
if (!m_isBeingDestroyed)
1444
static void derefPluginView(PluginView* pluginView)
1446
pluginView->deref();
1449
void PluginView::unprotectPluginFromDestruction()
1451
if (m_isBeingDestroyed)
1454
// A plug-in may ask us to evaluate JavaScript that removes the plug-in from the
1455
// page, but expect the object to still be alive when the call completes. Flash,
1456
// for example, may crash if the plug-in is destroyed and we return to code for
1457
// the destroyed object higher on the stack. To prevent this, if the plug-in has
1458
// only one remaining reference, call deref() asynchronously.
1460
RunLoop::main()->dispatch(bind(derefPluginView, this));
1465
void PluginView::didFinishLoad(WebFrame* webFrame)
1467
RefPtr<URLRequest> request = m_pendingFrameLoads.take(webFrame);
1469
webFrame->setLoadListener(0);
1471
m_plugin->frameDidFinishLoading(request->requestID());
1474
void PluginView::didFailLoad(WebFrame* webFrame, bool wasCancelled)
1476
RefPtr<URLRequest> request = m_pendingFrameLoads.take(webFrame);
1478
webFrame->setLoadListener(0);
1480
m_plugin->frameDidFail(request->requestID(), wasCancelled);
1483
#if PLUGIN_ARCHITECTURE(X11)
1484
uint64_t PluginView::createPluginContainer()
1486
uint64_t windowID = 0;
1487
m_webPage->sendSync(Messages::WebPageProxy::CreatePluginContainer(), Messages::WebPageProxy::CreatePluginContainer::Reply(windowID));
1491
void PluginView::windowedPluginGeometryDidChange(const WebCore::IntRect& frameRect, const WebCore::IntRect& clipRect, uint64_t windowID)
1493
m_webPage->send(Messages::WebPageProxy::WindowedPluginGeometryDidChange(frameRect, clipRect, windowID));
1497
void PluginView::pluginSnapshotTimerFired(DeferrableOneShotTimer<PluginView>* timer)
1499
ASSERT_UNUSED(timer, timer == &m_pluginSnapshotTimer);
1502
// Snapshot might be 0 if plugin size is 0x0.
1503
RefPtr<ShareableBitmap> snapshot = m_plugin->snapshot();
1504
RefPtr<Image> snapshotImage;
1506
snapshotImage = snapshot->createImage();
1507
m_pluginElement->updateSnapshot(snapshotImage.release());
1508
destroyPluginAndReset();
1512
} // namespace WebKit