PluginView.cpp 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749
  1. /*
  2. * Copyright (C) 2010, 2012 Apple 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
  6. * are met:
  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.
  12. *
  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.
  24. */
  25. #include "config.h"
  26. #include "PluginView.h"
  27. #include "NPRuntimeUtilities.h"
  28. #include "Plugin.h"
  29. #include "ShareableBitmap.h"
  30. #include "WebCoreArgumentCoders.h"
  31. #include "WebEvent.h"
  32. #include "WebPage.h"
  33. #include "WebPageProxyMessages.h"
  34. #include "WebProcess.h"
  35. #include <WebCore/BitmapImage.h>
  36. #include <WebCore/Chrome.h>
  37. #include <WebCore/CookieJar.h>
  38. #include <WebCore/Credential.h>
  39. #include <WebCore/CredentialStorage.h>
  40. #include <WebCore/DocumentLoader.h>
  41. #include <WebCore/EventHandler.h>
  42. #include <WebCore/FocusController.h>
  43. #include <WebCore/Frame.h>
  44. #include <WebCore/FrameLoadRequest.h>
  45. #include <WebCore/FrameLoader.h>
  46. #include <WebCore/FrameLoaderClient.h>
  47. #include <WebCore/FrameView.h>
  48. #include <WebCore/GraphicsContext.h>
  49. #include <WebCore/HTMLPlugInElement.h>
  50. #include <WebCore/HTMLPlugInImageElement.h>
  51. #include <WebCore/HostWindow.h>
  52. #include <WebCore/MIMETypeRegistry.h>
  53. #include <WebCore/MouseEvent.h>
  54. #include <WebCore/NetscapePlugInStreamLoader.h>
  55. #include <WebCore/NetworkingContext.h>
  56. #include <WebCore/Page.h>
  57. #include <WebCore/PageThrottler.h>
  58. #include <WebCore/PlatformMouseEvent.h>
  59. #include <WebCore/ProtectionSpace.h>
  60. #include <WebCore/ProxyServer.h>
  61. #include <WebCore/RenderEmbeddedObject.h>
  62. #include <WebCore/ResourceLoadScheduler.h>
  63. #include <WebCore/ScriptController.h>
  64. #include <WebCore/ScriptValue.h>
  65. #include <WebCore/ScrollView.h>
  66. #include <WebCore/SecurityOrigin.h>
  67. #include <WebCore/SecurityPolicy.h>
  68. #include <WebCore/Settings.h>
  69. #include <WebCore/UserGestureIndicator.h>
  70. #include <wtf/text/StringBuilder.h>
  71. using namespace JSC;
  72. using namespace WebCore;
  73. namespace WebKit {
  74. // This simulated mouse click delay in HTMLPlugInImageElement.cpp should generally be the same or shorter than this delay.
  75. static const double pluginSnapshotTimerDelay = 1.1;
  76. class PluginView::URLRequest : public RefCounted<URLRequest> {
  77. public:
  78. static PassRefPtr<PluginView::URLRequest> create(uint64_t requestID, const FrameLoadRequest& request, bool allowPopups)
  79. {
  80. return adoptRef(new URLRequest(requestID, request, allowPopups));
  81. }
  82. uint64_t requestID() const { return m_requestID; }
  83. const String& target() const { return m_request.frameName(); }
  84. const ResourceRequest & request() const { return m_request.resourceRequest(); }
  85. bool allowPopups() const { return m_allowPopups; }
  86. private:
  87. URLRequest(uint64_t requestID, const FrameLoadRequest& request, bool allowPopups)
  88. : m_requestID(requestID)
  89. , m_request(request)
  90. , m_allowPopups(allowPopups)
  91. {
  92. }
  93. uint64_t m_requestID;
  94. FrameLoadRequest m_request;
  95. bool m_allowPopups;
  96. };
  97. class PluginView::Stream : public RefCounted<PluginView::Stream>, NetscapePlugInStreamLoaderClient {
  98. public:
  99. static PassRefPtr<Stream> create(PluginView* pluginView, uint64_t streamID, const ResourceRequest& request)
  100. {
  101. return adoptRef(new Stream(pluginView, streamID, request));
  102. }
  103. ~Stream();
  104. void start();
  105. void cancel();
  106. uint64_t streamID() const { return m_streamID; }
  107. private:
  108. Stream(PluginView* pluginView, uint64_t streamID, const ResourceRequest& request)
  109. : m_pluginView(pluginView)
  110. , m_streamID(streamID)
  111. , m_request(request)
  112. , m_streamWasCancelled(false)
  113. {
  114. }
  115. // NetscapePluginStreamLoaderClient
  116. virtual void didReceiveResponse(NetscapePlugInStreamLoader*, const ResourceResponse&);
  117. virtual void didReceiveData(NetscapePlugInStreamLoader*, const char*, int);
  118. virtual void didFail(NetscapePlugInStreamLoader*, const ResourceError&);
  119. virtual void didFinishLoading(NetscapePlugInStreamLoader*);
  120. PluginView* m_pluginView;
  121. uint64_t m_streamID;
  122. const ResourceRequest m_request;
  123. // True if the stream was explicitly cancelled by calling cancel().
  124. // (As opposed to being cancelled by the user hitting the stop button for example.
  125. bool m_streamWasCancelled;
  126. RefPtr<NetscapePlugInStreamLoader> m_loader;
  127. };
  128. PluginView::Stream::~Stream()
  129. {
  130. ASSERT(!m_pluginView);
  131. }
  132. void PluginView::Stream::start()
  133. {
  134. ASSERT(m_pluginView->m_plugin);
  135. ASSERT(!m_loader);
  136. Frame* frame = m_pluginView->m_pluginElement->document()->frame();
  137. ASSERT(frame);
  138. m_loader = resourceLoadScheduler()->schedulePluginStreamLoad(frame, this, m_request);
  139. }
  140. void PluginView::Stream::cancel()
  141. {
  142. ASSERT(m_loader);
  143. m_streamWasCancelled = true;
  144. m_loader->cancel(m_loader->cancelledError());
  145. m_loader = 0;
  146. }
  147. static String buildHTTPHeaders(const ResourceResponse& response, long long& expectedContentLength)
  148. {
  149. if (!response.isHTTP())
  150. return String();
  151. StringBuilder stringBuilder;
  152. String statusLine = String::format("HTTP %d ", response.httpStatusCode());
  153. stringBuilder.append(statusLine);
  154. stringBuilder.append(response.httpStatusText());
  155. stringBuilder.append('\n');
  156. HTTPHeaderMap::const_iterator end = response.httpHeaderFields().end();
  157. for (HTTPHeaderMap::const_iterator it = response.httpHeaderFields().begin(); it != end; ++it) {
  158. stringBuilder.append(it->key);
  159. stringBuilder.appendLiteral(": ");
  160. stringBuilder.append(it->value);
  161. stringBuilder.append('\n');
  162. }
  163. String headers = stringBuilder.toString();
  164. // If the content is encoded (most likely compressed), then don't send its length to the plugin,
  165. // which is only interested in the decoded length, not yet known at the moment.
  166. // <rdar://problem/4470599> tracks a request for -[NSURLResponse expectedContentLength] to incorporate this logic.
  167. String contentEncoding = response.httpHeaderField("Content-Encoding");
  168. if (!contentEncoding.isNull() && contentEncoding != "identity")
  169. expectedContentLength = -1;
  170. return headers;
  171. }
  172. void PluginView::Stream::didReceiveResponse(NetscapePlugInStreamLoader*, const ResourceResponse& response)
  173. {
  174. // Compute the stream related data from the resource response.
  175. const KURL& responseURL = response.url();
  176. const String& mimeType = response.mimeType();
  177. long long expectedContentLength = response.expectedContentLength();
  178. String headers = buildHTTPHeaders(response, expectedContentLength);
  179. uint32_t streamLength = 0;
  180. if (expectedContentLength > 0)
  181. streamLength = expectedContentLength;
  182. m_pluginView->m_plugin->streamDidReceiveResponse(m_streamID, responseURL, streamLength, response.lastModifiedDate(), mimeType, headers, response.suggestedFilename());
  183. }
  184. void PluginView::Stream::didReceiveData(NetscapePlugInStreamLoader*, const char* bytes, int length)
  185. {
  186. m_pluginView->m_plugin->streamDidReceiveData(m_streamID, bytes, length);
  187. }
  188. void PluginView::Stream::didFail(NetscapePlugInStreamLoader*, const ResourceError& error)
  189. {
  190. // Calling streamDidFail could cause us to be deleted, so we hold on to a reference here.
  191. RefPtr<Stream> protect(this);
  192. // We only want to call streamDidFail if the stream was not explicitly cancelled by the plug-in.
  193. if (!m_streamWasCancelled)
  194. m_pluginView->m_plugin->streamDidFail(m_streamID, error.isCancellation());
  195. m_pluginView->removeStream(this);
  196. m_pluginView = 0;
  197. }
  198. void PluginView::Stream::didFinishLoading(NetscapePlugInStreamLoader*)
  199. {
  200. // Calling streamDidFinishLoading could cause us to be deleted, so we hold on to a reference here.
  201. RefPtr<Stream> protectStream(this);
  202. #if ENABLE(NETSCAPE_PLUGIN_API)
  203. // Protect the plug-in while we're calling into it.
  204. NPRuntimeObjectMap::PluginProtector pluginProtector(&m_pluginView->m_npRuntimeObjectMap);
  205. #endif
  206. m_pluginView->m_plugin->streamDidFinishLoading(m_streamID);
  207. m_pluginView->removeStream(this);
  208. m_pluginView = 0;
  209. }
  210. static inline WebPage* webPage(HTMLPlugInElement* pluginElement)
  211. {
  212. Frame* frame = pluginElement->document()->frame();
  213. ASSERT(frame);
  214. WebFrameLoaderClient* webFrameLoaderClient = toWebFrameLoaderClient(frame->loader()->client());
  215. WebPage* webPage = webFrameLoaderClient ? webFrameLoaderClient->webFrame()->page() : 0;
  216. ASSERT(webPage);
  217. return webPage;
  218. }
  219. PassRefPtr<PluginView> PluginView::create(PassRefPtr<HTMLPlugInElement> pluginElement, PassRefPtr<Plugin> plugin, const Plugin::Parameters& parameters)
  220. {
  221. return adoptRef(new PluginView(pluginElement, plugin, parameters));
  222. }
  223. PluginView::PluginView(PassRefPtr<HTMLPlugInElement> pluginElement, PassRefPtr<Plugin> plugin, const Plugin::Parameters& parameters)
  224. : PluginViewBase(0)
  225. , m_pluginElement(pluginElement)
  226. , m_plugin(plugin)
  227. , m_webPage(webPage(m_pluginElement.get()))
  228. , m_parameters(parameters)
  229. , m_isInitialized(false)
  230. , m_isWaitingForSynchronousInitialization(false)
  231. , m_isWaitingUntilMediaCanStart(false)
  232. , m_isBeingDestroyed(false)
  233. , m_pluginProcessHasCrashed(false)
  234. , m_pendingURLRequestsTimer(RunLoop::main(), this, &PluginView::pendingURLRequestsTimerFired)
  235. #if ENABLE(NETSCAPE_PLUGIN_API)
  236. , m_npRuntimeObjectMap(this)
  237. #endif
  238. , m_manualStreamState(StreamStateInitial)
  239. , m_pluginSnapshotTimer(this, &PluginView::pluginSnapshotTimerFired, pluginSnapshotTimerDelay)
  240. , m_countSnapshotRetries(0)
  241. , m_didReceiveUserInteraction(false)
  242. , m_pageScaleFactor(1)
  243. {
  244. m_webPage->addPluginView(this);
  245. }
  246. PluginView::~PluginView()
  247. {
  248. if (m_webPage)
  249. m_webPage->removePluginView(this);
  250. ASSERT(!m_isBeingDestroyed);
  251. if (m_isWaitingUntilMediaCanStart)
  252. m_pluginElement->document()->removeMediaCanStartListener(this);
  253. destroyPluginAndReset();
  254. // Null out the plug-in element explicitly so we'll crash earlier if we try to use
  255. // the plug-in view after it's been destroyed.
  256. m_pluginElement = nullptr;
  257. }
  258. void PluginView::destroyPluginAndReset()
  259. {
  260. // Cancel all pending frame loads.
  261. for (FrameLoadMap::iterator it = m_pendingFrameLoads.begin(), end = m_pendingFrameLoads.end(); it != end; ++it)
  262. it->key->setLoadListener(0);
  263. if (m_plugin) {
  264. m_isBeingDestroyed = true;
  265. m_plugin->destroyPlugin();
  266. m_isBeingDestroyed = false;
  267. m_pendingURLRequests.clear();
  268. m_pendingURLRequestsTimer.stop();
  269. #if PLATFORM(MAC)
  270. if (m_webPage)
  271. pluginFocusOrWindowFocusChanged(false);
  272. #endif
  273. }
  274. #if ENABLE(NETSCAPE_PLUGIN_API)
  275. // Invalidate the object map.
  276. m_npRuntimeObjectMap.invalidate();
  277. #endif
  278. cancelAllStreams();
  279. }
  280. void PluginView::recreateAndInitialize(PassRefPtr<Plugin> plugin)
  281. {
  282. if (m_plugin) {
  283. if (m_pluginSnapshotTimer.isActive())
  284. m_pluginSnapshotTimer.stop();
  285. destroyPluginAndReset();
  286. }
  287. // Reset member variables to initial values.
  288. m_plugin = plugin;
  289. m_isInitialized = false;
  290. m_isWaitingForSynchronousInitialization = false;
  291. m_isWaitingUntilMediaCanStart = false;
  292. m_isBeingDestroyed = false;
  293. m_manualStreamState = StreamStateInitial;
  294. m_transientPaintingSnapshot = nullptr;
  295. initializePlugin();
  296. }
  297. Frame* PluginView::frame() const
  298. {
  299. return m_pluginElement->document()->frame();
  300. }
  301. void PluginView::manualLoadDidReceiveResponse(const ResourceResponse& response)
  302. {
  303. // The plug-in can be null here if it failed to initialize.
  304. if (!m_plugin)
  305. return;
  306. if (!m_isInitialized) {
  307. ASSERT(m_manualStreamState == StreamStateInitial);
  308. m_manualStreamState = StreamStateHasReceivedResponse;
  309. m_manualStreamResponse = response;
  310. return;
  311. }
  312. // Compute the stream related data from the resource response.
  313. const KURL& responseURL = response.url();
  314. const String& mimeType = response.mimeType();
  315. long long expectedContentLength = response.expectedContentLength();
  316. String headers = buildHTTPHeaders(response, expectedContentLength);
  317. uint32_t streamLength = 0;
  318. if (expectedContentLength > 0)
  319. streamLength = expectedContentLength;
  320. m_plugin->manualStreamDidReceiveResponse(responseURL, streamLength, response.lastModifiedDate(), mimeType, headers, response.suggestedFilename());
  321. }
  322. void PluginView::manualLoadDidReceiveData(const char* bytes, int length)
  323. {
  324. // The plug-in can be null here if it failed to initialize.
  325. if (!m_plugin)
  326. return;
  327. if (!m_isInitialized) {
  328. ASSERT(m_manualStreamState == StreamStateHasReceivedResponse);
  329. if (!m_manualStreamData)
  330. m_manualStreamData = SharedBuffer::create();
  331. m_manualStreamData->append(bytes, length);
  332. return;
  333. }
  334. m_plugin->manualStreamDidReceiveData(bytes, length);
  335. }
  336. void PluginView::manualLoadDidFinishLoading()
  337. {
  338. // The plug-in can be null here if it failed to initialize.
  339. if (!m_plugin)
  340. return;
  341. if (!m_isInitialized) {
  342. ASSERT(m_manualStreamState == StreamStateHasReceivedResponse);
  343. m_manualStreamState = StreamStateFinished;
  344. return;
  345. }
  346. m_plugin->manualStreamDidFinishLoading();
  347. }
  348. void PluginView::manualLoadDidFail(const ResourceError& error)
  349. {
  350. // The plug-in can be null here if it failed to initialize.
  351. if (!m_plugin)
  352. return;
  353. if (!m_isInitialized) {
  354. m_manualStreamState = StreamStateFinished;
  355. m_manualStreamError = error;
  356. m_manualStreamData = nullptr;
  357. return;
  358. }
  359. m_plugin->manualStreamDidFail(error.isCancellation());
  360. }
  361. RenderBoxModelObject* PluginView::renderer() const
  362. {
  363. return toRenderBoxModelObject(m_pluginElement->renderer());
  364. }
  365. void PluginView::pageScaleFactorDidChange()
  366. {
  367. viewGeometryDidChange();
  368. }
  369. void PluginView::setPageScaleFactor(double scaleFactor, IntPoint)
  370. {
  371. m_pageScaleFactor = scaleFactor;
  372. m_webPage->send(Messages::WebPageProxy::PageScaleFactorDidChange(scaleFactor));
  373. m_webPage->send(Messages::WebPageProxy::PageZoomFactorDidChange(scaleFactor));
  374. pageScaleFactorDidChange();
  375. }
  376. double PluginView::pageScaleFactor() const
  377. {
  378. return m_pageScaleFactor;
  379. }
  380. bool PluginView::handlesPageScaleFactor() const
  381. {
  382. if (!m_plugin || !m_isInitialized)
  383. return false;
  384. return m_plugin->handlesPageScaleFactor();
  385. }
  386. void PluginView::webPageDestroyed()
  387. {
  388. m_webPage = 0;
  389. }
  390. #if PLATFORM(MAC)
  391. void PluginView::setWindowIsVisible(bool windowIsVisible)
  392. {
  393. if (!m_isInitialized || !m_plugin)
  394. return;
  395. m_plugin->windowVisibilityChanged(windowIsVisible);
  396. }
  397. void PluginView::setWindowIsFocused(bool windowIsFocused)
  398. {
  399. if (!m_isInitialized || !m_plugin)
  400. return;
  401. m_plugin->windowFocusChanged(windowIsFocused);
  402. }
  403. void PluginView::setDeviceScaleFactor(float scaleFactor)
  404. {
  405. if (!m_isInitialized || !m_plugin)
  406. return;
  407. m_plugin->contentsScaleFactorChanged(scaleFactor);
  408. }
  409. void PluginView::windowAndViewFramesChanged(const FloatRect& windowFrameInScreenCoordinates, const FloatRect& viewFrameInWindowCoordinates)
  410. {
  411. if (!m_isInitialized || !m_plugin)
  412. return;
  413. m_plugin->windowAndViewFramesChanged(enclosingIntRect(windowFrameInScreenCoordinates), enclosingIntRect(viewFrameInWindowCoordinates));
  414. }
  415. bool PluginView::sendComplexTextInput(uint64_t pluginComplexTextInputIdentifier, const String& textInput)
  416. {
  417. if (!m_plugin)
  418. return false;
  419. if (m_plugin->pluginComplexTextInputIdentifier() != pluginComplexTextInputIdentifier)
  420. return false;
  421. m_plugin->sendComplexTextInput(textInput);
  422. return true;
  423. }
  424. void PluginView::setLayerHostingMode(LayerHostingMode layerHostingMode)
  425. {
  426. if (!m_plugin)
  427. return;
  428. if (!m_isInitialized) {
  429. m_parameters.layerHostingMode = layerHostingMode;
  430. return;
  431. }
  432. m_plugin->setLayerHostingMode(layerHostingMode);
  433. }
  434. NSObject *PluginView::accessibilityObject() const
  435. {
  436. if (!m_isInitialized || !m_plugin)
  437. return 0;
  438. return m_plugin->accessibilityObject();
  439. }
  440. #endif
  441. void PluginView::initializePlugin()
  442. {
  443. if (m_isInitialized)
  444. return;
  445. if (!m_plugin) {
  446. // We've already tried and failed to initialize the plug-in.
  447. return;
  448. }
  449. if (Frame* frame = m_pluginElement->document()->frame()) {
  450. if (Page* page = frame->page()) {
  451. // We shouldn't initialize the plug-in right now, add a listener.
  452. if (!page->canStartMedia()) {
  453. if (m_isWaitingUntilMediaCanStart)
  454. return;
  455. m_isWaitingUntilMediaCanStart = true;
  456. m_pluginElement->document()->addMediaCanStartListener(this);
  457. return;
  458. }
  459. }
  460. }
  461. m_plugin->initialize(this, m_parameters);
  462. // Plug-in initialization continued in didFailToInitializePlugin() or didInitializePlugin().
  463. }
  464. void PluginView::didFailToInitializePlugin()
  465. {
  466. m_plugin = 0;
  467. String frameURLString = frame()->loader()->documentLoader()->responseURL().string();
  468. String pageURLString = m_webPage->corePage()->mainFrame()->loader()->documentLoader()->responseURL().string();
  469. m_webPage->send(Messages::WebPageProxy::DidFailToInitializePlugin(m_parameters.mimeType, frameURLString, pageURLString));
  470. }
  471. void PluginView::didInitializePlugin()
  472. {
  473. m_isInitialized = true;
  474. #if PLATFORM(MAC)
  475. windowAndViewFramesChanged(m_webPage->windowFrameInScreenCoordinates(), m_webPage->viewFrameInWindowCoordinates());
  476. #endif
  477. viewGeometryDidChange();
  478. if (m_pluginElement->document()->focusedElement() == m_pluginElement)
  479. m_plugin->setFocus(true);
  480. redeliverManualStream();
  481. #if PLATFORM(MAC)
  482. if (m_pluginElement->displayState() < HTMLPlugInElement::Restarting) {
  483. if (m_plugin->pluginLayer() && frame()) {
  484. frame()->view()->enterCompositingMode();
  485. m_pluginElement->setNeedsStyleRecalc(SyntheticStyleChange);
  486. }
  487. if (frame() && !frame()->settings()->maximumPlugInSnapshotAttempts()) {
  488. m_pluginElement->setDisplayState(HTMLPlugInElement::DisplayingSnapshot);
  489. return;
  490. }
  491. m_pluginSnapshotTimer.restart();
  492. } else {
  493. if (m_plugin->pluginLayer() && frame()) {
  494. frame()->view()->enterCompositingMode();
  495. m_pluginElement->setNeedsStyleRecalc(SyntheticStyleChange);
  496. }
  497. if (m_pluginElement->displayState() == HTMLPlugInElement::RestartingWithPendingMouseClick)
  498. m_pluginElement->dispatchPendingMouseClick();
  499. }
  500. setWindowIsVisible(m_webPage->windowIsVisible());
  501. setWindowIsFocused(m_webPage->windowIsFocused());
  502. #endif
  503. if (wantsWheelEvents()) {
  504. if (Frame* frame = m_pluginElement->document()->frame()) {
  505. if (FrameView* frameView = frame->view())
  506. frameView->setNeedsLayout();
  507. }
  508. }
  509. }
  510. #if PLATFORM(MAC)
  511. PlatformLayer* PluginView::platformLayer() const
  512. {
  513. // The plug-in can be null here if it failed to initialize.
  514. if (!m_isInitialized || !m_plugin || m_pluginProcessHasCrashed)
  515. return 0;
  516. return m_plugin->pluginLayer();
  517. }
  518. #endif
  519. JSObject* PluginView::scriptObject(JSGlobalObject* globalObject)
  520. {
  521. // If we're already waiting for synchronous initialization of the plugin,
  522. // calls to scriptObject() are from the plug-in itself and need to return 0;
  523. if (m_isWaitingForSynchronousInitialization)
  524. return 0;
  525. // We might not have started initialization of the plug-in yet, the plug-in might be in the middle
  526. // of being initializing asynchronously, or initialization might have previously failed.
  527. if (!m_isInitialized || !m_plugin)
  528. return 0;
  529. #if ENABLE(NETSCAPE_PLUGIN_API)
  530. NPObject* scriptableNPObject = m_plugin->pluginScriptableNPObject();
  531. if (!scriptableNPObject)
  532. return 0;
  533. JSObject* jsObject = m_npRuntimeObjectMap.getOrCreateJSObject(globalObject, scriptableNPObject);
  534. releaseNPObject(scriptableNPObject);
  535. return jsObject;
  536. #else
  537. UNUSED_PARAM(globalObject);
  538. return 0;
  539. #endif
  540. }
  541. void PluginView::storageBlockingStateChanged()
  542. {
  543. // The plug-in can be null here if it failed to initialize.
  544. if (!m_isInitialized || !m_plugin)
  545. return;
  546. bool storageBlockingPolicy = !frame()->document()->securityOrigin()->canAccessPluginStorage(frame()->document()->topOrigin());
  547. m_plugin->storageBlockingStateChanged(storageBlockingPolicy);
  548. }
  549. void PluginView::privateBrowsingStateChanged(bool privateBrowsingEnabled)
  550. {
  551. // The plug-in can be null here if it failed to initialize.
  552. if (!m_isInitialized || !m_plugin)
  553. return;
  554. m_plugin->privateBrowsingStateChanged(privateBrowsingEnabled);
  555. }
  556. bool PluginView::getFormValue(String& formValue)
  557. {
  558. // The plug-in can be null here if it failed to initialize.
  559. if (!m_isInitialized || !m_plugin)
  560. return false;
  561. return m_plugin->getFormValue(formValue);
  562. }
  563. bool PluginView::scroll(ScrollDirection direction, ScrollGranularity granularity)
  564. {
  565. // The plug-in can be null here if it failed to initialize.
  566. if (!m_isInitialized || !m_plugin)
  567. return false;
  568. return m_plugin->handleScroll(direction, granularity);
  569. }
  570. Scrollbar* PluginView::horizontalScrollbar()
  571. {
  572. // The plug-in can be null here if it failed to initialize.
  573. if (!m_isInitialized || !m_plugin)
  574. return 0;
  575. return m_plugin->horizontalScrollbar();
  576. }
  577. Scrollbar* PluginView::verticalScrollbar()
  578. {
  579. // The plug-in can be null here if it failed to initialize.
  580. if (!m_isInitialized || !m_plugin)
  581. return 0;
  582. return m_plugin->verticalScrollbar();
  583. }
  584. bool PluginView::wantsWheelEvents()
  585. {
  586. // The plug-in can be null here if it failed to initialize.
  587. if (!m_isInitialized || !m_plugin)
  588. return 0;
  589. return m_plugin->wantsWheelEvents();
  590. }
  591. void PluginView::setFrameRect(const WebCore::IntRect& rect)
  592. {
  593. Widget::setFrameRect(rect);
  594. viewGeometryDidChange();
  595. }
  596. void PluginView::paint(GraphicsContext* context, const IntRect& /*dirtyRect*/)
  597. {
  598. if (!m_plugin || !m_isInitialized || m_pluginElement->displayState() < HTMLPlugInElement::Restarting)
  599. return;
  600. if (context->paintingDisabled()) {
  601. if (context->updatingControlTints())
  602. m_plugin->updateControlTints(context);
  603. return;
  604. }
  605. // FIXME: We should try to intersect the dirty rect with the plug-in's clip rect here.
  606. IntRect paintRect = IntRect(IntPoint(), frameRect().size());
  607. if (paintRect.isEmpty())
  608. return;
  609. if (m_transientPaintingSnapshot) {
  610. m_transientPaintingSnapshot->paint(*context, contentsScaleFactor(), frameRect().location(), m_transientPaintingSnapshot->bounds());
  611. return;
  612. }
  613. GraphicsContextStateSaver stateSaver(*context);
  614. // Translate the coordinate system so that the origin is in the top-left corner of the plug-in.
  615. context->translate(frameRect().location().x(), frameRect().location().y());
  616. m_plugin->paint(context, paintRect);
  617. }
  618. void PluginView::frameRectsChanged()
  619. {
  620. Widget::frameRectsChanged();
  621. viewGeometryDidChange();
  622. }
  623. void PluginView::clipRectChanged()
  624. {
  625. viewGeometryDidChange();
  626. }
  627. void PluginView::setParent(ScrollView* scrollView)
  628. {
  629. Widget::setParent(scrollView);
  630. if (scrollView)
  631. initializePlugin();
  632. }
  633. unsigned PluginView::countFindMatches(const String& target, WebCore::FindOptions options, unsigned maxMatchCount)
  634. {
  635. if (!m_isInitialized || !m_plugin)
  636. return 0;
  637. return m_plugin->countFindMatches(target, options, maxMatchCount);
  638. }
  639. bool PluginView::findString(const String& target, WebCore::FindOptions options, unsigned maxMatchCount)
  640. {
  641. if (!m_isInitialized || !m_plugin)
  642. return false;
  643. return m_plugin->findString(target, options, maxMatchCount);
  644. }
  645. String PluginView::getSelectionString() const
  646. {
  647. if (!m_isInitialized || !m_plugin)
  648. return String();
  649. return m_plugin->getSelectionString();
  650. }
  651. PassOwnPtr<WebEvent> PluginView::createWebEvent(MouseEvent* event) const
  652. {
  653. WebEvent::Type type = WebEvent::NoType;
  654. unsigned clickCount = 1;
  655. if (event->type() == eventNames().mousedownEvent)
  656. type = WebEvent::MouseDown;
  657. else if (event->type() == eventNames().mouseupEvent)
  658. type = WebEvent::MouseUp;
  659. else if (event->type() == eventNames().mouseoverEvent) {
  660. type = WebEvent::MouseMove;
  661. clickCount = 0;
  662. } else if (event->type() == eventNames().clickEvent)
  663. return nullptr;
  664. else
  665. ASSERT_NOT_REACHED();
  666. WebMouseEvent::Button button = WebMouseEvent::NoButton;
  667. switch (event->button()) {
  668. case WebCore::LeftButton:
  669. button = WebMouseEvent::LeftButton;
  670. break;
  671. case WebCore::MiddleButton:
  672. button = WebMouseEvent::MiddleButton;
  673. break;
  674. case WebCore::RightButton:
  675. button = WebMouseEvent::RightButton;
  676. break;
  677. default:
  678. ASSERT_NOT_REACHED();
  679. break;
  680. }
  681. unsigned modifiers = 0;
  682. if (event->shiftKey())
  683. modifiers |= WebEvent::ShiftKey;
  684. if (event->ctrlKey())
  685. modifiers |= WebEvent::ControlKey;
  686. if (event->altKey())
  687. modifiers |= WebEvent::AltKey;
  688. if (event->metaKey())
  689. modifiers |= WebEvent::MetaKey;
  690. 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));
  691. }
  692. void PluginView::handleEvent(Event* event)
  693. {
  694. if (!m_isInitialized || !m_plugin)
  695. return;
  696. const WebEvent* currentEvent = WebPage::currentEvent();
  697. OwnPtr<WebEvent> simulatedWebEvent;
  698. if (event->isMouseEvent() && toMouseEvent(event)->isSimulated()) {
  699. simulatedWebEvent = createWebEvent(toMouseEvent(event));
  700. currentEvent = simulatedWebEvent.get();
  701. }
  702. if (!currentEvent)
  703. return;
  704. bool didHandleEvent = false;
  705. if ((event->type() == eventNames().mousemoveEvent && currentEvent->type() == WebEvent::MouseMove)
  706. || (event->type() == eventNames().mousedownEvent && currentEvent->type() == WebEvent::MouseDown)
  707. || (event->type() == eventNames().mouseupEvent && currentEvent->type() == WebEvent::MouseUp)) {
  708. // FIXME: Clicking in a scroll bar should not change focus.
  709. if (currentEvent->type() == WebEvent::MouseDown) {
  710. focusPluginElement();
  711. frame()->eventHandler()->setCapturingMouseEventsNode(m_pluginElement.get());
  712. } else if (currentEvent->type() == WebEvent::MouseUp)
  713. frame()->eventHandler()->setCapturingMouseEventsNode(0);
  714. didHandleEvent = m_plugin->handleMouseEvent(static_cast<const WebMouseEvent&>(*currentEvent));
  715. if (event->type() != eventNames().mousemoveEvent)
  716. pluginDidReceiveUserInteraction();
  717. } else if (event->type() == eventNames().mousewheelEvent && currentEvent->type() == WebEvent::Wheel && m_plugin->wantsWheelEvents()) {
  718. didHandleEvent = m_plugin->handleWheelEvent(static_cast<const WebWheelEvent&>(*currentEvent));
  719. pluginDidReceiveUserInteraction();
  720. } else if (event->type() == eventNames().mouseoverEvent && currentEvent->type() == WebEvent::MouseMove)
  721. didHandleEvent = m_plugin->handleMouseEnterEvent(static_cast<const WebMouseEvent&>(*currentEvent));
  722. else if (event->type() == eventNames().mouseoutEvent && currentEvent->type() == WebEvent::MouseMove)
  723. didHandleEvent = m_plugin->handleMouseLeaveEvent(static_cast<const WebMouseEvent&>(*currentEvent));
  724. else if (event->type() == eventNames().contextmenuEvent && currentEvent->type() == WebEvent::MouseDown) {
  725. didHandleEvent = m_plugin->handleContextMenuEvent(static_cast<const WebMouseEvent&>(*currentEvent));
  726. pluginDidReceiveUserInteraction();
  727. } else if ((event->type() == eventNames().keydownEvent && currentEvent->type() == WebEvent::KeyDown)
  728. || (event->type() == eventNames().keyupEvent && currentEvent->type() == WebEvent::KeyUp)) {
  729. didHandleEvent = m_plugin->handleKeyboardEvent(static_cast<const WebKeyboardEvent&>(*currentEvent));
  730. pluginDidReceiveUserInteraction();
  731. }
  732. if (didHandleEvent)
  733. event->setDefaultHandled();
  734. }
  735. bool PluginView::handleEditingCommand(const String& commandName, const String& argument)
  736. {
  737. if (!m_isInitialized || !m_plugin)
  738. return false;
  739. return m_plugin->handleEditingCommand(commandName, argument);
  740. }
  741. bool PluginView::isEditingCommandEnabled(const String& commandName)
  742. {
  743. if (!m_isInitialized || !m_plugin)
  744. return false;
  745. return m_plugin->isEditingCommandEnabled(commandName);
  746. }
  747. bool PluginView::shouldAllowScripting()
  748. {
  749. if (!m_isInitialized || !m_plugin)
  750. return false;
  751. return m_plugin->shouldAllowScripting();
  752. }
  753. bool PluginView::shouldAllowNavigationFromDrags() const
  754. {
  755. if (!m_isInitialized || !m_plugin)
  756. return false;
  757. return m_plugin->shouldAllowNavigationFromDrags();
  758. }
  759. bool PluginView::shouldNotAddLayer() const
  760. {
  761. return m_pluginElement->displayState() < HTMLPlugInElement::Restarting && !m_plugin->supportsSnapshotting();
  762. }
  763. PassRefPtr<SharedBuffer> PluginView::liveResourceData() const
  764. {
  765. if (!m_isInitialized || !m_plugin)
  766. return 0;
  767. return m_plugin->liveResourceData();
  768. }
  769. bool PluginView::performDictionaryLookupAtLocation(const WebCore::FloatPoint& point)
  770. {
  771. if (!m_isInitialized || !m_plugin)
  772. return false;
  773. return m_plugin->performDictionaryLookupAtLocation(point);
  774. }
  775. void PluginView::notifyWidget(WidgetNotification notification)
  776. {
  777. switch (notification) {
  778. case WillPaintFlattened:
  779. if (shouldCreateTransientPaintingSnapshot())
  780. m_transientPaintingSnapshot = m_plugin->snapshot();
  781. break;
  782. case DidPaintFlattened:
  783. m_transientPaintingSnapshot = nullptr;
  784. break;
  785. }
  786. }
  787. void PluginView::show()
  788. {
  789. bool wasVisible = isVisible();
  790. setSelfVisible(true);
  791. if (!wasVisible)
  792. viewVisibilityDidChange();
  793. Widget::show();
  794. }
  795. void PluginView::hide()
  796. {
  797. bool wasVisible = isVisible();
  798. setSelfVisible(false);
  799. if (wasVisible)
  800. viewVisibilityDidChange();
  801. Widget::hide();
  802. }
  803. bool PluginView::transformsAffectFrameRect()
  804. {
  805. return false;
  806. }
  807. void PluginView::viewGeometryDidChange()
  808. {
  809. if (!m_isInitialized || !m_plugin || !parent())
  810. return;
  811. ASSERT(frame());
  812. float pageScaleFactor = frame()->page() ? frame()->page()->pageScaleFactor() : 1;
  813. IntPoint scaledFrameRectLocation(frameRect().location().x() * pageScaleFactor, frameRect().location().y() * pageScaleFactor);
  814. IntPoint scaledLocationInRootViewCoordinates(parent()->contentsToRootView(scaledFrameRectLocation));
  815. // FIXME: We still don't get the right coordinates for transformed plugins.
  816. AffineTransform transform;
  817. transform.translate(scaledLocationInRootViewCoordinates.x(), scaledLocationInRootViewCoordinates.y());
  818. transform.scale(pageScaleFactor);
  819. // FIXME: The way we calculate this clip rect isn't correct.
  820. // But it is still important to distinguish between empty and non-empty rects so we can notify the plug-in when it becomes invisible.
  821. // Making the rect actually correct is covered by https://bugs.webkit.org/show_bug.cgi?id=95362
  822. IntRect clipRect = boundsRect();
  823. // FIXME: We can only get a semi-reliable answer from clipRectInWindowCoordinates() when the page is not scaled.
  824. // Fixing that is tracked in <rdar://problem/9026611> - Make the Widget hierarchy play nicely with transforms, for zoomed plug-ins and iframes
  825. if (pageScaleFactor == 1) {
  826. clipRect = clipRectInWindowCoordinates();
  827. if (!clipRect.isEmpty())
  828. clipRect = boundsRect();
  829. }
  830. m_plugin->geometryDidChange(size(), clipRect, transform);
  831. }
  832. void PluginView::viewVisibilityDidChange()
  833. {
  834. if (!m_isInitialized || !m_plugin || !parent())
  835. return;
  836. m_plugin->visibilityDidChange();
  837. }
  838. IntRect PluginView::clipRectInWindowCoordinates() const
  839. {
  840. // Get the frame rect in window coordinates.
  841. IntRect frameRectInWindowCoordinates = parent()->contentsToWindow(frameRect());
  842. Frame* frame = this->frame();
  843. // Get the window clip rect for the plugin element (in window coordinates).
  844. IntRect windowClipRect = frame->view()->windowClipRectForFrameOwner(m_pluginElement.get(), true);
  845. // Intersect the two rects to get the view clip rect in window coordinates.
  846. frameRectInWindowCoordinates.intersect(windowClipRect);
  847. return frameRectInWindowCoordinates;
  848. }
  849. void PluginView::focusPluginElement()
  850. {
  851. ASSERT(frame());
  852. if (Page* page = frame()->page())
  853. page->focusController()->setFocusedElement(m_pluginElement.get(), frame());
  854. else
  855. frame()->document()->setFocusedElement(m_pluginElement);
  856. }
  857. void PluginView::pendingURLRequestsTimerFired()
  858. {
  859. ASSERT(!m_pendingURLRequests.isEmpty());
  860. RefPtr<URLRequest> urlRequest = m_pendingURLRequests.takeFirst();
  861. // If there are more requests to perform, reschedule the timer.
  862. if (!m_pendingURLRequests.isEmpty())
  863. m_pendingURLRequestsTimer.startOneShot(0);
  864. performURLRequest(urlRequest.get());
  865. }
  866. void PluginView::performURLRequest(URLRequest* request)
  867. {
  868. // This protector is needed to make sure the PluginView is not destroyed while it is still needed.
  869. RefPtr<PluginView> protect(this);
  870. // First, check if this is a javascript: url.
  871. if (protocolIsJavaScript(request->request().url())) {
  872. performJavaScriptURLRequest(request);
  873. return;
  874. }
  875. if (!request->target().isNull()) {
  876. performFrameLoadURLRequest(request);
  877. return;
  878. }
  879. // This request is to load a URL and create a stream.
  880. RefPtr<Stream> stream = PluginView::Stream::create(this, request->requestID(), request->request());
  881. addStream(stream.get());
  882. stream->start();
  883. }
  884. void PluginView::performFrameLoadURLRequest(URLRequest* request)
  885. {
  886. ASSERT(!request->target().isNull());
  887. Frame* frame = m_pluginElement->document()->frame();
  888. if (!frame)
  889. return;
  890. if (!m_pluginElement->document()->securityOrigin()->canDisplay(request->request().url())) {
  891. // We can't load the request, send back a reply to the plug-in.
  892. m_plugin->frameDidFail(request->requestID(), false);
  893. return;
  894. }
  895. UserGestureIndicator gestureIndicator(request->allowPopups() ? DefinitelyProcessingNewUserGesture : PossiblyProcessingUserGesture);
  896. // First, try to find a target frame.
  897. Frame* targetFrame = frame->loader()->findFrameForNavigation(request->target());
  898. if (!targetFrame) {
  899. // We did not find a target frame. Ask our frame to load the page. This may or may not create a popup window.
  900. FrameLoadRequest frameRequest(frame, request->request());
  901. frameRequest.setFrameName(request->target());
  902. frameRequest.setShouldCheckNewWindowPolicy(true);
  903. frame->loader()->load(frameRequest);
  904. // FIXME: We don't know whether the window was successfully created here so we just assume that it worked.
  905. // It's better than not telling the plug-in anything.
  906. m_plugin->frameDidFinishLoading(request->requestID());
  907. return;
  908. }
  909. // Now ask the frame to load the request.
  910. targetFrame->loader()->load(FrameLoadRequest(targetFrame, request->request()));
  911. WebFrameLoaderClient* webFrameLoaderClient = toWebFrameLoaderClient(targetFrame->loader()->client());
  912. WebFrame* targetWebFrame = webFrameLoaderClient ? webFrameLoaderClient->webFrame() : 0;
  913. ASSERT(targetWebFrame);
  914. if (WebFrame::LoadListener* loadListener = targetWebFrame->loadListener()) {
  915. // Check if another plug-in view or even this view is waiting for the frame to load.
  916. // If it is, tell it that the load was cancelled because it will be anyway.
  917. loadListener->didFailLoad(targetWebFrame, true);
  918. }
  919. m_pendingFrameLoads.set(targetWebFrame, request);
  920. targetWebFrame->setLoadListener(this);
  921. }
  922. void PluginView::performJavaScriptURLRequest(URLRequest* request)
  923. {
  924. ASSERT(protocolIsJavaScript(request->request().url()));
  925. RefPtr<Frame> frame = m_pluginElement->document()->frame();
  926. if (!frame)
  927. return;
  928. String jsString = decodeURLEscapeSequences(request->request().url().string().substring(sizeof("javascript:") - 1));
  929. if (!request->target().isNull()) {
  930. // For security reasons, only allow JS requests to be made on the frame that contains the plug-in.
  931. if (frame->tree()->find(request->target()) != frame) {
  932. // Let the plug-in know that its frame load failed.
  933. m_plugin->frameDidFail(request->requestID(), false);
  934. return;
  935. }
  936. }
  937. // Evaluate the JavaScript code. Note that running JavaScript here could cause the plug-in to be destroyed, so we
  938. // grab references to the plug-in here.
  939. RefPtr<Plugin> plugin = m_plugin;
  940. ScriptValue result = frame->script()->executeScript(jsString, request->allowPopups());
  941. // Check if evaluating the JavaScript destroyed the plug-in.
  942. if (!plugin->controller())
  943. return;
  944. // Don't notify the plug-in at all about targeted javascript: requests. This matches Mozilla and WebKit1.
  945. if (!request->target().isNull())
  946. return;
  947. ScriptState* scriptState = frame->script()->globalObject(pluginWorld())->globalExec();
  948. String resultString;
  949. result.getString(scriptState, resultString);
  950. // Send the result back to the plug-in.
  951. plugin->didEvaluateJavaScript(request->requestID(), resultString);
  952. }
  953. void PluginView::addStream(Stream* stream)
  954. {
  955. ASSERT(!m_streams.contains(stream->streamID()));
  956. m_streams.set(stream->streamID(), stream);
  957. }
  958. void PluginView::removeStream(Stream* stream)
  959. {
  960. ASSERT(m_streams.get(stream->streamID()) == stream);
  961. m_streams.remove(stream->streamID());
  962. }
  963. void PluginView::cancelAllStreams()
  964. {
  965. Vector<RefPtr<Stream>> streams;
  966. copyValuesToVector(m_streams, streams);
  967. for (size_t i = 0; i < streams.size(); ++i)
  968. streams[i]->cancel();
  969. // Cancelling a stream removes it from the m_streams map, so if we cancel all streams the map should be empty.
  970. ASSERT(m_streams.isEmpty());
  971. }
  972. void PluginView::redeliverManualStream()
  973. {
  974. if (m_manualStreamState == StreamStateInitial) {
  975. // Nothing to do.
  976. return;
  977. }
  978. if (m_manualStreamState == StreamStateFailed) {
  979. manualLoadDidFail(m_manualStreamError);
  980. return;
  981. }
  982. // Deliver the response.
  983. manualLoadDidReceiveResponse(m_manualStreamResponse);
  984. // Deliver the data.
  985. if (m_manualStreamData) {
  986. const char* data;
  987. unsigned position = 0;
  988. while (unsigned length = m_manualStreamData->getSomeData(data, position)) {
  989. manualLoadDidReceiveData(data, length);
  990. position += length;
  991. }
  992. m_manualStreamData = nullptr;
  993. }
  994. if (m_manualStreamState == StreamStateFinished)
  995. manualLoadDidFinishLoading();
  996. }
  997. void PluginView::invalidateRect(const IntRect& dirtyRect)
  998. {
  999. if (!parent() || !m_plugin || !m_isInitialized)
  1000. return;
  1001. #if PLATFORM(MAC)
  1002. if (m_plugin->pluginLayer())
  1003. return;
  1004. #endif
  1005. if (m_pluginElement->displayState() < HTMLPlugInElement::Restarting)
  1006. return;
  1007. RenderBoxModelObject* renderer = toRenderBoxModelObject(m_pluginElement->renderer());
  1008. if (!renderer)
  1009. return;
  1010. IntRect contentRect(dirtyRect);
  1011. contentRect.move(renderer->borderLeft() + renderer->paddingLeft(), renderer->borderTop() + renderer->paddingTop());
  1012. renderer->repaintRectangle(contentRect);
  1013. }
  1014. void PluginView::setFocus(bool hasFocus)
  1015. {
  1016. Widget::setFocus(hasFocus);
  1017. if (!m_isInitialized || !m_plugin)
  1018. return;
  1019. m_plugin->setFocus(hasFocus);
  1020. }
  1021. void PluginView::mediaCanStart()
  1022. {
  1023. ASSERT(m_isWaitingUntilMediaCanStart);
  1024. m_isWaitingUntilMediaCanStart = false;
  1025. initializePlugin();
  1026. }
  1027. bool PluginView::isPluginVisible()
  1028. {
  1029. return isVisible();
  1030. }
  1031. void PluginView::invalidate(const IntRect& dirtyRect)
  1032. {
  1033. invalidateRect(dirtyRect);
  1034. }
  1035. String PluginView::userAgent()
  1036. {
  1037. Frame* frame = m_pluginElement->document()->frame();
  1038. if (!frame)
  1039. return String();
  1040. return frame->loader()->client()->userAgent(KURL());
  1041. }
  1042. void PluginView::loadURL(uint64_t requestID, const String& method, const String& urlString, const String& target,
  1043. const HTTPHeaderMap& headerFields, const Vector<uint8_t>& httpBody, bool allowPopups)
  1044. {
  1045. FrameLoadRequest frameLoadRequest(m_pluginElement->document()->securityOrigin());
  1046. frameLoadRequest.resourceRequest().setHTTPMethod(method);
  1047. frameLoadRequest.resourceRequest().setURL(m_pluginElement->document()->completeURL(urlString));
  1048. frameLoadRequest.resourceRequest().addHTTPHeaderFields(headerFields);
  1049. frameLoadRequest.resourceRequest().setHTTPBody(FormData::create(httpBody.data(), httpBody.size()));
  1050. frameLoadRequest.setFrameName(target);
  1051. String referrer = SecurityPolicy::generateReferrerHeader(frame()->document()->referrerPolicy(), frameLoadRequest.resourceRequest().url(), frame()->loader()->outgoingReferrer());
  1052. if (!referrer.isEmpty())
  1053. frameLoadRequest.resourceRequest().setHTTPReferrer(referrer);
  1054. m_pendingURLRequests.append(URLRequest::create(requestID, frameLoadRequest, allowPopups));
  1055. m_pendingURLRequestsTimer.startOneShot(0);
  1056. }
  1057. void PluginView::cancelStreamLoad(uint64_t streamID)
  1058. {
  1059. // Keep a reference to the stream. Stream::cancel might remove the stream from the map, and thus
  1060. // releasing its last reference.
  1061. RefPtr<Stream> stream = m_streams.get(streamID);
  1062. if (!stream)
  1063. return;
  1064. // Cancelling the stream here will remove it from the map.
  1065. stream->cancel();
  1066. ASSERT(!m_streams.contains(streamID));
  1067. }
  1068. void PluginView::cancelManualStreamLoad()
  1069. {
  1070. if (!frame())
  1071. return;
  1072. DocumentLoader* documentLoader = frame()->loader()->activeDocumentLoader();
  1073. ASSERT(documentLoader);
  1074. if (documentLoader->isLoadingMainResource())
  1075. documentLoader->cancelMainResourceLoad(frame()->loader()->cancelledError(m_parameters.url));
  1076. }
  1077. #if ENABLE(NETSCAPE_PLUGIN_API)
  1078. NPObject* PluginView::windowScriptNPObject()
  1079. {
  1080. if (!frame())
  1081. return 0;
  1082. if (!frame()->script()->canExecuteScripts(NotAboutToExecuteScript)) {
  1083. // FIXME: Investigate if other browsers allow plug-ins to access JavaScript objects even if JavaScript is disabled.
  1084. return 0;
  1085. }
  1086. return m_npRuntimeObjectMap.getOrCreateNPObject(*pluginWorld()->vm(), frame()->script()->windowShell(pluginWorld())->window());
  1087. }
  1088. NPObject* PluginView::pluginElementNPObject()
  1089. {
  1090. if (!frame())
  1091. return 0;
  1092. if (!frame()->script()->canExecuteScripts(NotAboutToExecuteScript)) {
  1093. // FIXME: Investigate if other browsers allow plug-ins to access JavaScript objects even if JavaScript is disabled.
  1094. return 0;
  1095. }
  1096. JSObject* object = frame()->script()->jsObjectForPluginElement(m_pluginElement.get());
  1097. ASSERT(object);
  1098. return m_npRuntimeObjectMap.getOrCreateNPObject(*pluginWorld()->vm(), object);
  1099. }
  1100. bool PluginView::evaluate(NPObject* npObject, const String& scriptString, NPVariant* result, bool allowPopups)
  1101. {
  1102. // FIXME: Is this check necessary?
  1103. if (!m_pluginElement->document()->frame())
  1104. return false;
  1105. // Calling evaluate will run JavaScript that can potentially remove the plug-in element, so we need to
  1106. // protect the plug-in view from destruction.
  1107. NPRuntimeObjectMap::PluginProtector pluginProtector(&m_npRuntimeObjectMap);
  1108. UserGestureIndicator gestureIndicator(allowPopups ? DefinitelyProcessingNewUserGesture : PossiblyProcessingUserGesture);
  1109. return m_npRuntimeObjectMap.evaluate(npObject, scriptString, result);
  1110. }
  1111. #endif
  1112. void PluginView::setStatusbarText(const String& statusbarText)
  1113. {
  1114. if (!frame())
  1115. return;
  1116. Page* page = frame()->page();
  1117. if (!page)
  1118. return;
  1119. page->chrome().setStatusbarText(frame(), statusbarText);
  1120. }
  1121. bool PluginView::isAcceleratedCompositingEnabled()
  1122. {
  1123. if (!frame())
  1124. return false;
  1125. Settings* settings = frame()->settings();
  1126. if (!settings)
  1127. return false;
  1128. // We know that some plug-ins can support snapshotting without needing
  1129. // accelerated compositing. Since we're trying to snapshot them anyway,
  1130. // put them into normal compositing mode. A side benefit is that this might
  1131. // allow the entire page to stay in that mode.
  1132. if (m_pluginElement->displayState() < HTMLPlugInElement::Restarting && m_parameters.mimeType == "application/x-shockwave-flash")
  1133. return false;
  1134. return settings->acceleratedCompositingEnabled();
  1135. }
  1136. void PluginView::pluginProcessCrashed()
  1137. {
  1138. m_pluginProcessHasCrashed = true;
  1139. if (!m_pluginElement->renderer())
  1140. return;
  1141. // FIXME: The renderer could also be a RenderApplet, we should handle that.
  1142. if (!m_pluginElement->renderer()->isEmbeddedObject())
  1143. return;
  1144. m_pluginElement->setNeedsStyleRecalc(SyntheticStyleChange);
  1145. RenderEmbeddedObject* renderer = toRenderEmbeddedObject(m_pluginElement->renderer());
  1146. renderer->setPluginUnavailabilityReason(RenderEmbeddedObject::PluginCrashed);
  1147. Widget::invalidate();
  1148. }
  1149. void PluginView::willSendEventToPlugin()
  1150. {
  1151. // If we're sending an event to a plug-in, we can't control how long the plug-in
  1152. // takes to process it (e.g. it may display a context menu), so we tell the UI process
  1153. // to stop the responsiveness timer in this case.
  1154. m_webPage->send(Messages::WebPageProxy::StopResponsivenessTimer());
  1155. }
  1156. #if PLATFORM(MAC)
  1157. void PluginView::pluginFocusOrWindowFocusChanged(bool pluginHasFocusAndWindowHasFocus)
  1158. {
  1159. if (m_webPage)
  1160. m_webPage->send(Messages::WebPageProxy::PluginFocusOrWindowFocusChanged(m_plugin->pluginComplexTextInputIdentifier(), pluginHasFocusAndWindowHasFocus));
  1161. }
  1162. void PluginView::setComplexTextInputState(PluginComplexTextInputState pluginComplexTextInputState)
  1163. {
  1164. if (m_webPage)
  1165. m_webPage->send(Messages::WebPageProxy::SetPluginComplexTextInputState(m_plugin->pluginComplexTextInputIdentifier(), pluginComplexTextInputState));
  1166. }
  1167. mach_port_t PluginView::compositingRenderServerPort()
  1168. {
  1169. return WebProcess::shared().compositingRenderServerPort();
  1170. }
  1171. void PluginView::openPluginPreferencePane()
  1172. {
  1173. ASSERT_NOT_REACHED();
  1174. }
  1175. #endif
  1176. float PluginView::contentsScaleFactor()
  1177. {
  1178. if (Page* page = frame() ? frame()->page() : 0)
  1179. return page->deviceScaleFactor();
  1180. return 1;
  1181. }
  1182. String PluginView::proxiesForURL(const String& urlString)
  1183. {
  1184. const FrameLoader* frameLoader = frame() ? frame()->loader() : 0;
  1185. const NetworkingContext* context = frameLoader ? frameLoader->networkingContext() : 0;
  1186. Vector<ProxyServer> proxyServers = proxyServersForURL(KURL(KURL(), urlString), context);
  1187. return toString(proxyServers);
  1188. }
  1189. String PluginView::cookiesForURL(const String& urlString)
  1190. {
  1191. return cookies(m_pluginElement->document(), KURL(KURL(), urlString));
  1192. }
  1193. void PluginView::setCookiesForURL(const String& urlString, const String& cookieString)
  1194. {
  1195. setCookies(m_pluginElement->document(), KURL(KURL(), urlString), cookieString);
  1196. }
  1197. bool PluginView::getAuthenticationInfo(const ProtectionSpace& protectionSpace, String& username, String& password)
  1198. {
  1199. Credential credential = CredentialStorage::get(protectionSpace);
  1200. if (credential.isEmpty())
  1201. credential = CredentialStorage::getFromPersistentStorage(protectionSpace);
  1202. if (!credential.hasPassword())
  1203. return false;
  1204. username = credential.user();
  1205. password = credential.password();
  1206. return true;
  1207. }
  1208. bool PluginView::isPrivateBrowsingEnabled()
  1209. {
  1210. // If we can't get the real setting, we'll assume that private browsing is enabled.
  1211. if (!frame())
  1212. return true;
  1213. if (!frame()->document()->securityOrigin()->canAccessPluginStorage(frame()->document()->topOrigin()))
  1214. return true;
  1215. Settings* settings = frame()->settings();
  1216. if (!settings)
  1217. return true;
  1218. return settings->privateBrowsingEnabled();
  1219. }
  1220. bool PluginView::asynchronousPluginInitializationEnabled() const
  1221. {
  1222. return m_webPage->asynchronousPluginInitializationEnabled();
  1223. }
  1224. bool PluginView::asynchronousPluginInitializationEnabledForAllPlugins() const
  1225. {
  1226. return m_webPage->asynchronousPluginInitializationEnabledForAllPlugins();
  1227. }
  1228. bool PluginView::artificialPluginInitializationDelayEnabled() const
  1229. {
  1230. return m_webPage->artificialPluginInitializationDelayEnabled();
  1231. }
  1232. void PluginView::protectPluginFromDestruction()
  1233. {
  1234. if (!m_isBeingDestroyed)
  1235. ref();
  1236. }
  1237. static void derefPluginView(PluginView* pluginView)
  1238. {
  1239. pluginView->deref();
  1240. }
  1241. void PluginView::unprotectPluginFromDestruction()
  1242. {
  1243. if (m_isBeingDestroyed)
  1244. return;
  1245. // A plug-in may ask us to evaluate JavaScript that removes the plug-in from the
  1246. // page, but expect the object to still be alive when the call completes. Flash,
  1247. // for example, may crash if the plug-in is destroyed and we return to code for
  1248. // the destroyed object higher on the stack. To prevent this, if the plug-in has
  1249. // only one remaining reference, call deref() asynchronously.
  1250. if (hasOneRef())
  1251. RunLoop::main()->dispatch(bind(derefPluginView, this));
  1252. else
  1253. deref();
  1254. }
  1255. void PluginView::didFinishLoad(WebFrame* webFrame)
  1256. {
  1257. RefPtr<URLRequest> request = m_pendingFrameLoads.take(webFrame);
  1258. ASSERT(request);
  1259. webFrame->setLoadListener(0);
  1260. m_plugin->frameDidFinishLoading(request->requestID());
  1261. }
  1262. void PluginView::didFailLoad(WebFrame* webFrame, bool wasCancelled)
  1263. {
  1264. RefPtr<URLRequest> request = m_pendingFrameLoads.take(webFrame);
  1265. ASSERT(request);
  1266. webFrame->setLoadListener(0);
  1267. m_plugin->frameDidFail(request->requestID(), wasCancelled);
  1268. }
  1269. #if PLUGIN_ARCHITECTURE(X11)
  1270. uint64_t PluginView::createPluginContainer()
  1271. {
  1272. uint64_t windowID = 0;
  1273. m_webPage->sendSync(Messages::WebPageProxy::CreatePluginContainer(), Messages::WebPageProxy::CreatePluginContainer::Reply(windowID));
  1274. return windowID;
  1275. }
  1276. void PluginView::windowedPluginGeometryDidChange(const WebCore::IntRect& frameRect, const WebCore::IntRect& clipRect, uint64_t windowID)
  1277. {
  1278. m_webPage->send(Messages::WebPageProxy::WindowedPluginGeometryDidChange(frameRect, clipRect, windowID));
  1279. }
  1280. #endif
  1281. #if PLATFORM(MAC)
  1282. static bool isAlmostSolidColor(BitmapImage* bitmap)
  1283. {
  1284. CGImageRef image = bitmap->getCGImageRef();
  1285. ASSERT(CGImageGetBitsPerComponent(image) == 8);
  1286. CGBitmapInfo imageInfo = CGImageGetBitmapInfo(image);
  1287. if (!(imageInfo & kCGBitmapByteOrder32Little) || (imageInfo & kCGBitmapAlphaInfoMask) != kCGImageAlphaPremultipliedFirst) {
  1288. // FIXME: Consider being able to handle other pixel formats.
  1289. ASSERT_NOT_REACHED();
  1290. return false;
  1291. }
  1292. size_t width = CGImageGetWidth(image);
  1293. size_t height = CGImageGetHeight(image);
  1294. size_t bytesPerRow = CGImageGetBytesPerRow(image);
  1295. RetainPtr<CFDataRef> provider = adoptCF(CGDataProviderCopyData(CGImageGetDataProvider(image)));
  1296. const UInt8* data = CFDataGetBytePtr(provider.get());
  1297. // Overlay a grid of sampling dots on top of a grayscale version of the image.
  1298. // For the interior points, calculate the difference in luminance among the sample point
  1299. // and its surrounds points, scaled by transparency.
  1300. const unsigned sampleRows = 7;
  1301. const unsigned sampleCols = 7;
  1302. // FIXME: Refine the proper number of samples, and accommodate different aspect ratios.
  1303. if (width < sampleCols || height < sampleRows)
  1304. return false;
  1305. // Ensure that the last row/column land on the image perimeter.
  1306. const float strideWidth = static_cast<float>(width - 1) / (sampleCols - 1);
  1307. const float strideHeight = static_cast<float>(height - 1) / (sampleRows - 1);
  1308. float samples[sampleRows][sampleCols];
  1309. // Find the luminance of the sample points.
  1310. float y = 0;
  1311. const UInt8* row = data;
  1312. for (unsigned i = 0; i < sampleRows; ++i) {
  1313. float x = 0;
  1314. for (unsigned j = 0; j < sampleCols; ++j) {
  1315. const UInt8* p0 = row + (static_cast<int>(x + .5)) * 4;
  1316. // R G B A
  1317. samples[i][j] = (0.2125 * *p0 + 0.7154 * *(p0+1) + 0.0721 * *(p0+2)) * *(p0+3) / 255;
  1318. x += strideWidth;
  1319. }
  1320. y += strideHeight;
  1321. row = data + (static_cast<int>(y + .5)) * bytesPerRow;
  1322. }
  1323. // Determine the image score.
  1324. float accumScore = 0;
  1325. for (unsigned i = 1; i < sampleRows - 1; ++i) {
  1326. for (unsigned j = 1; j < sampleCols - 1; ++j) {
  1327. float diff = samples[i - 1][j] + samples[i + 1][j] + samples[i][j - 1] + samples[i][j + 1] - 4 * samples[i][j];
  1328. accumScore += diff * diff;
  1329. }
  1330. }
  1331. // The score for a given sample can be within the range of 0 and 255^2.
  1332. return accumScore < 2500 * (sampleRows - 2) * (sampleCols - 2);
  1333. }
  1334. #endif
  1335. void PluginView::pluginSnapshotTimerFired(DeferrableOneShotTimer<PluginView>*)
  1336. {
  1337. ASSERT(m_plugin);
  1338. if (m_plugin->supportsSnapshotting()) {
  1339. // Snapshot might be 0 if plugin size is 0x0.
  1340. RefPtr<ShareableBitmap> snapshot = m_plugin->snapshot();
  1341. RefPtr<Image> snapshotImage;
  1342. if (snapshot)
  1343. snapshotImage = snapshot->createImage();
  1344. m_pluginElement->updateSnapshot(snapshotImage.get());
  1345. #if PLATFORM(MAC)
  1346. unsigned maximumSnapshotRetries = frame() ? frame()->settings()->maximumPlugInSnapshotAttempts() : 0;
  1347. if (snapshotImage && isAlmostSolidColor(static_cast<BitmapImage*>(snapshotImage.get())) && m_countSnapshotRetries < maximumSnapshotRetries) {
  1348. ++m_countSnapshotRetries;
  1349. m_pluginSnapshotTimer.restart();
  1350. return;
  1351. }
  1352. #endif
  1353. }
  1354. // Even if there is no snapshot we still set the state to DisplayingSnapshot
  1355. // since we just want to display the default empty box.
  1356. m_pluginElement->setDisplayState(HTMLPlugInElement::DisplayingSnapshot);
  1357. }
  1358. void PluginView::beginSnapshottingRunningPlugin()
  1359. {
  1360. m_pluginSnapshotTimer.restart();
  1361. }
  1362. bool PluginView::shouldAlwaysAutoStart() const
  1363. {
  1364. if (!m_plugin)
  1365. return PluginViewBase::shouldAlwaysAutoStart();
  1366. if (MIMETypeRegistry::isJavaAppletMIMEType(m_parameters.mimeType))
  1367. return true;
  1368. return m_plugin->shouldAlwaysAutoStart();
  1369. }
  1370. void PluginView::pluginDidReceiveUserInteraction()
  1371. {
  1372. if (frame() && !frame()->settings()->plugInSnapshottingEnabled())
  1373. return;
  1374. if (m_didReceiveUserInteraction)
  1375. return;
  1376. m_didReceiveUserInteraction = true;
  1377. WebCore::HTMLPlugInImageElement* plugInImageElement = toHTMLPlugInImageElement(m_pluginElement.get());
  1378. String pageOrigin = plugInImageElement->document()->page()->mainFrame()->document()->baseURL().host();
  1379. String pluginOrigin = plugInImageElement->loadedUrl().host();
  1380. String mimeType = plugInImageElement->loadedMimeType();
  1381. WebProcess::shared().plugInDidReceiveUserInteraction(pageOrigin, pluginOrigin, mimeType);
  1382. }
  1383. bool PluginView::shouldCreateTransientPaintingSnapshot() const
  1384. {
  1385. if (!m_plugin)
  1386. return false;
  1387. if (!m_isInitialized)
  1388. return false;
  1389. if (FrameView* frameView = frame()->view()) {
  1390. if (frameView->paintBehavior() & (PaintBehaviorSelectionOnly | PaintBehaviorForceBlackText)) {
  1391. // This paint behavior is used when drawing the find indicator and there's no need to
  1392. // snapshot plug-ins, because they can never be painted as part of the find indicator.
  1393. return false;
  1394. }
  1395. }
  1396. return true;
  1397. }
  1398. } // namespace WebKit