Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1002 lines
33KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE 6 technical preview.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. You may use this code under the terms of the GPL v3
  6. (see www.gnu.org/licenses).
  7. For this technical preview, this file is not subject to commercial licensing.
  8. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  9. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  10. DISCLAIMED.
  11. ==============================================================================
  12. */
  13. namespace juce
  14. {
  15. struct InternalWebViewType
  16. {
  17. InternalWebViewType() {}
  18. virtual ~InternalWebViewType() {}
  19. virtual void createBrowser() = 0;
  20. virtual bool hasBrowserBeenCreated() = 0;
  21. virtual void goToURL (const String&, const StringArray*, const MemoryBlock*) = 0;
  22. virtual void stop() = 0;
  23. virtual void goBack() = 0;
  24. virtual void goForward() = 0;
  25. virtual void refresh() = 0;
  26. virtual void focusGained() {}
  27. virtual void setWebViewSize (int, int) = 0;
  28. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InternalWebViewType)
  29. };
  30. #if JUCE_MINGW
  31. JUCE_DECLARE_UUID_GETTER (IOleClientSite, "00000118-0000-0000-c000-000000000046")
  32. JUCE_DECLARE_UUID_GETTER (IDispatch, "00020400-0000-0000-c000-000000000046")
  33. #ifndef WebBrowser
  34. class WebBrowser;
  35. #endif
  36. #endif
  37. JUCE_DECLARE_UUID_GETTER (DWebBrowserEvents2, "34A715A0-6587-11D0-924A-0020AFC7AC4D")
  38. JUCE_DECLARE_UUID_GETTER (IConnectionPointContainer, "B196B284-BAB4-101A-B69C-00AA00341D07")
  39. JUCE_DECLARE_UUID_GETTER (IWebBrowser2, "D30C1661-CDAF-11D0-8A3E-00C04FC9E26E")
  40. JUCE_DECLARE_UUID_GETTER (WebBrowser, "8856F961-340A-11D0-A96B-00C04FD705A2")
  41. //==============================================================================
  42. class Win32WebView : public InternalWebViewType,
  43. public ActiveXControlComponent
  44. {
  45. public:
  46. Win32WebView (WebBrowserComponent& owner)
  47. {
  48. owner.addAndMakeVisible (this);
  49. }
  50. ~Win32WebView() override
  51. {
  52. if (connectionPoint != nullptr)
  53. connectionPoint->Unadvise (adviseCookie);
  54. if (browser != nullptr)
  55. browser->Release();
  56. }
  57. void createBrowser() override
  58. {
  59. auto webCLSID = __uuidof (WebBrowser);
  60. createControl (&webCLSID);
  61. auto iidWebBrowser2 = __uuidof (IWebBrowser2);
  62. auto iidConnectionPointContainer = __uuidof (IConnectionPointContainer);
  63. browser = (IWebBrowser2*) queryInterface (&iidWebBrowser2);
  64. if (auto connectionPointContainer = (IConnectionPointContainer*) queryInterface (&iidConnectionPointContainer))
  65. {
  66. connectionPointContainer->FindConnectionPoint (__uuidof (DWebBrowserEvents2), &connectionPoint);
  67. if (connectionPoint != nullptr)
  68. {
  69. auto* owner = dynamic_cast<WebBrowserComponent*> (Component::getParentComponent());
  70. jassert (owner != nullptr);
  71. auto handler = new EventHandler (*owner);
  72. connectionPoint->Advise (handler, &adviseCookie);
  73. handler->Release();
  74. }
  75. }
  76. }
  77. bool hasBrowserBeenCreated() override
  78. {
  79. return browser != nullptr;
  80. }
  81. void goToURL (const String& url, const StringArray* headers, const MemoryBlock* postData) override
  82. {
  83. if (browser != nullptr)
  84. {
  85. VARIANT headerFlags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  86. VariantInit (&headerFlags);
  87. VariantInit (&frame);
  88. VariantInit (&postDataVar);
  89. VariantInit (&headersVar);
  90. if (headers != nullptr)
  91. {
  92. V_VT (&headersVar) = VT_BSTR;
  93. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n").toWideCharPointer());
  94. }
  95. if (postData != nullptr && postData->getSize() > 0)
  96. {
  97. auto sa = SafeArrayCreateVector (VT_UI1, 0, (ULONG) postData->getSize());
  98. if (sa != nullptr)
  99. {
  100. void* data = nullptr;
  101. SafeArrayAccessData (sa, &data);
  102. jassert (data != nullptr);
  103. if (data != nullptr)
  104. {
  105. postData->copyTo (data, 0, postData->getSize());
  106. SafeArrayUnaccessData (sa);
  107. VARIANT postDataVar2;
  108. VariantInit (&postDataVar2);
  109. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  110. V_ARRAY (&postDataVar2) = sa;
  111. sa = nullptr;
  112. postDataVar = postDataVar2;
  113. }
  114. else
  115. {
  116. SafeArrayDestroy (sa);
  117. }
  118. }
  119. }
  120. auto urlBSTR = SysAllocString ((const OLECHAR*) url.toWideCharPointer());
  121. browser->Navigate (urlBSTR, &headerFlags, &frame, &postDataVar, &headersVar);
  122. SysFreeString (urlBSTR);
  123. VariantClear (&headerFlags);
  124. VariantClear (&frame);
  125. VariantClear (&postDataVar);
  126. VariantClear (&headersVar);
  127. }
  128. }
  129. void stop() override
  130. {
  131. if (browser != nullptr)
  132. browser->Stop();
  133. }
  134. void goBack() override
  135. {
  136. if (browser != nullptr)
  137. browser->GoBack();
  138. }
  139. void goForward() override
  140. {
  141. if (browser != nullptr)
  142. browser->GoForward();
  143. }
  144. void refresh() override
  145. {
  146. if (browser != nullptr)
  147. browser->Refresh();
  148. }
  149. void focusGained() override
  150. {
  151. auto iidOleObject = __uuidof (IOleObject);
  152. auto iidOleWindow = __uuidof (IOleWindow);
  153. if (auto oleObject = (IOleObject*) queryInterface (&iidOleObject))
  154. {
  155. if (auto oleWindow = (IOleWindow*) queryInterface (&iidOleWindow))
  156. {
  157. IOleClientSite* oleClientSite = nullptr;
  158. if (SUCCEEDED (oleObject->GetClientSite (&oleClientSite)))
  159. {
  160. HWND hwnd;
  161. oleWindow->GetWindow (&hwnd);
  162. oleObject->DoVerb (OLEIVERB_UIACTIVATE, nullptr, oleClientSite, 0, hwnd, nullptr);
  163. oleClientSite->Release();
  164. }
  165. oleWindow->Release();
  166. }
  167. oleObject->Release();
  168. }
  169. }
  170. using ActiveXControlComponent::focusGained;
  171. void setWebViewSize (int width, int height) override
  172. {
  173. setSize (width, height);
  174. }
  175. private:
  176. IWebBrowser2* browser = nullptr;
  177. IConnectionPoint* connectionPoint = nullptr;
  178. DWORD adviseCookie = 0;
  179. //==============================================================================
  180. struct EventHandler : public ComBaseClassHelper<IDispatch>,
  181. public ComponentMovementWatcher
  182. {
  183. EventHandler (WebBrowserComponent& w) : ComponentMovementWatcher (&w), owner (w) {}
  184. JUCE_COMRESULT GetTypeInfoCount (UINT*) override { return E_NOTIMPL; }
  185. JUCE_COMRESULT GetTypeInfo (UINT, LCID, ITypeInfo**) override { return E_NOTIMPL; }
  186. JUCE_COMRESULT GetIDsOfNames (REFIID, LPOLESTR*, UINT, LCID, DISPID*) override { return E_NOTIMPL; }
  187. JUCE_COMRESULT Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/, WORD /*wFlags*/, DISPPARAMS* pDispParams,
  188. VARIANT* /*pVarResult*/, EXCEPINFO* /*pExcepInfo*/, UINT* /*puArgErr*/) override
  189. {
  190. if (dispIdMember == DISPID_BEFORENAVIGATE2)
  191. {
  192. *pDispParams->rgvarg->pboolVal
  193. = owner.pageAboutToLoad (getStringFromVariant (pDispParams->rgvarg[5].pvarVal)) ? VARIANT_FALSE
  194. : VARIANT_TRUE;
  195. return S_OK;
  196. }
  197. if (dispIdMember == 273 /*DISPID_NEWWINDOW3*/)
  198. {
  199. owner.newWindowAttemptingToLoad (pDispParams->rgvarg[0].bstrVal);
  200. *pDispParams->rgvarg[3].pboolVal = VARIANT_TRUE;
  201. return S_OK;
  202. }
  203. if (dispIdMember == DISPID_DOCUMENTCOMPLETE)
  204. {
  205. owner.pageFinishedLoading (getStringFromVariant (pDispParams->rgvarg[0].pvarVal));
  206. return S_OK;
  207. }
  208. if (dispIdMember == 271 /*DISPID_NAVIGATEERROR*/)
  209. {
  210. int statusCode = pDispParams->rgvarg[1].pvarVal->intVal;
  211. *pDispParams->rgvarg[0].pboolVal = VARIANT_FALSE;
  212. // IWebBrowser2 also reports http status codes here, we need
  213. // report only network errors
  214. if (statusCode < 0)
  215. {
  216. LPTSTR messageBuffer = nullptr;
  217. auto size = FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  218. nullptr, statusCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  219. (LPTSTR) &messageBuffer, 0, nullptr);
  220. String message (messageBuffer, size);
  221. LocalFree (messageBuffer);
  222. if (! owner.pageLoadHadNetworkError (message))
  223. *pDispParams->rgvarg[0].pboolVal = VARIANT_TRUE;
  224. }
  225. return S_OK;
  226. }
  227. if (dispIdMember == 263 /*DISPID_WINDOWCLOSING*/)
  228. {
  229. owner.windowCloseRequest();
  230. // setting this bool tells the browser to ignore the event - we'll handle it.
  231. if (pDispParams->cArgs > 0 && pDispParams->rgvarg[0].vt == (VT_BYREF | VT_BOOL))
  232. *pDispParams->rgvarg[0].pboolVal = VARIANT_TRUE;
  233. return S_OK;
  234. }
  235. return E_NOTIMPL;
  236. }
  237. void componentMovedOrResized (bool, bool) override {}
  238. void componentPeerChanged() override {}
  239. void componentVisibilityChanged() override { owner.visibilityChanged(); }
  240. private:
  241. WebBrowserComponent& owner;
  242. static String getStringFromVariant (VARIANT* v)
  243. {
  244. return (v->vt & VT_BYREF) != 0 ? *v->pbstrVal
  245. : v->bstrVal;
  246. }
  247. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (EventHandler)
  248. };
  249. };
  250. #if JUCE_USE_WINRT_WEBVIEW
  251. extern RTL_OSVERSIONINFOW getWindowsVersionInfo();
  252. using namespace Microsoft::WRL;
  253. using namespace ABI::Windows::Foundation;
  254. using namespace ABI::Windows::Storage::Streams;
  255. using namespace ABI::Windows::Web;
  256. using namespace ABI::Windows::Web::UI;
  257. using namespace ABI::Windows::Web::UI::Interop;
  258. using namespace ABI::Windows::Web::Http;
  259. using namespace ABI::Windows::Web::Http::Headers;
  260. //==============================================================================
  261. class WinRTWebView : public InternalWebViewType,
  262. public Component,
  263. public ComponentMovementWatcher
  264. {
  265. public:
  266. WinRTWebView (WebBrowserComponent& o)
  267. : ComponentMovementWatcher (&o),
  268. owner (o)
  269. {
  270. if (! WinRTWrapper::getInstance()->isInitialised())
  271. throw std::runtime_error ("Failed to initialise the WinRT wrapper");
  272. if (! createWebViewProcess())
  273. throw std::runtime_error ("Failed to create the WebViewControlProcess");
  274. owner.addAndMakeVisible (this);
  275. }
  276. ~WinRTWebView() override
  277. {
  278. if (webViewControl != nullptr)
  279. webViewControl->Stop();
  280. removeEventHandlers();
  281. webViewProcess->Terminate();
  282. }
  283. void createBrowser() override
  284. {
  285. if (webViewControl == nullptr)
  286. createWebViewControl();
  287. }
  288. bool hasBrowserBeenCreated() override
  289. {
  290. return webViewControl != nullptr || isCreating;
  291. }
  292. void goToURL (const String& url, const StringArray* headers, const MemoryBlock* postData) override
  293. {
  294. if (webViewControl != nullptr)
  295. {
  296. if ((headers != nullptr && ! headers->isEmpty())
  297. || (postData != nullptr && postData->getSize() > 0))
  298. {
  299. auto requestMessage = createHttpRequestMessage (url, headers, postData);
  300. webViewControl->NavigateWithHttpRequestMessage (requestMessage.get());
  301. }
  302. else
  303. {
  304. auto uri = createURI (url);
  305. webViewControl->Navigate (uri.get());
  306. }
  307. }
  308. }
  309. void stop() override
  310. {
  311. if (webViewControl != nullptr)
  312. webViewControl->Stop();
  313. }
  314. void goBack() override
  315. {
  316. if (webViewControl != nullptr)
  317. {
  318. boolean canGoBack = false;
  319. webViewControl->get_CanGoBack (&canGoBack);
  320. if (canGoBack)
  321. webViewControl->GoBack();
  322. }
  323. }
  324. void goForward() override
  325. {
  326. if (webViewControl != nullptr)
  327. {
  328. boolean canGoForward = false;
  329. webViewControl->get_CanGoForward (&canGoForward);
  330. if (canGoForward)
  331. webViewControl->GoForward();
  332. }
  333. }
  334. void refresh() override
  335. {
  336. if (webViewControl != nullptr)
  337. webViewControl->Refresh();
  338. }
  339. void setWebViewSize (int width, int height) override
  340. {
  341. setSize (width, height);
  342. }
  343. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) override
  344. {
  345. if (auto* peer = owner.getTopLevelComponent()->getPeer())
  346. setControlBounds (peer->getAreaCoveredBy (owner));
  347. }
  348. void componentPeerChanged() override
  349. {
  350. componentMovedOrResized (true, true);
  351. }
  352. void componentVisibilityChanged() override
  353. {
  354. setControlVisible (owner.isShowing());
  355. componentPeerChanged();
  356. owner.visibilityChanged();
  357. }
  358. private:
  359. //==============================================================================
  360. template<typename OperationResultType, typename ResultsType>
  361. static HRESULT waitForCompletion (IAsyncOperation<OperationResultType>* op, ResultsType* results)
  362. {
  363. using OperationType = IAsyncOperation<OperationResultType>;
  364. using DelegateType = IAsyncOperationCompletedHandler<OperationResultType>;
  365. struct EventDelegate : public RuntimeClass<RuntimeClassFlags<RuntimeClassType::Delegate>,
  366. DelegateType,
  367. FtmBase>
  368. {
  369. EventDelegate() = default;
  370. ~EventDelegate()
  371. {
  372. CloseHandle (eventCompleted);
  373. }
  374. HRESULT RuntimeClassInitialize()
  375. {
  376. eventCompleted = CreateEventEx (nullptr, nullptr, 0, EVENT_ALL_ACCESS);
  377. return eventCompleted == nullptr ? HRESULT_FROM_WIN32 (GetLastError()) : S_OK;
  378. }
  379. HRESULT Invoke (OperationType*, AsyncStatus newStatus)
  380. {
  381. status = newStatus;
  382. SetEvent (eventCompleted);
  383. return S_OK;
  384. }
  385. AsyncStatus status = AsyncStatus::Started;
  386. HANDLE eventCompleted = nullptr;
  387. };
  388. WinRTWrapper::ComPtr<OperationType> operation = op;
  389. WinRTWrapper::ComPtr<EventDelegate> eventCallback;
  390. auto hr = MakeAndInitialize<EventDelegate> (eventCallback.resetAndGetPointerAddress());
  391. if (SUCCEEDED (hr))
  392. {
  393. hr = operation->put_Completed (eventCallback.get());
  394. if (SUCCEEDED (hr))
  395. {
  396. HANDLE waitForEvents[1] { eventCallback->eventCompleted };
  397. auto handleCount = (ULONG) ARRAYSIZE (waitForEvents);
  398. DWORD handleIndex = 0;
  399. hr = CoWaitForMultipleHandles (COWAIT_DISPATCH_WINDOW_MESSAGES | COWAIT_DISPATCH_CALLS | COWAIT_INPUTAVAILABLE,
  400. INFINITE, handleCount, waitForEvents, &handleIndex);
  401. if (SUCCEEDED (hr))
  402. {
  403. if (eventCallback->status == AsyncStatus::Completed)
  404. {
  405. hr = operation->GetResults (results);
  406. }
  407. else
  408. {
  409. WinRTWrapper::ComPtr<IAsyncInfo> asyncInfo;
  410. if (SUCCEEDED (operation->QueryInterface (asyncInfo.resetAndGetPointerAddress())))
  411. asyncInfo->get_ErrorCode (&hr);
  412. }
  413. }
  414. }
  415. }
  416. return hr;
  417. }
  418. //==============================================================================
  419. template<class ArgsType>
  420. String getURIStringFromArgs (ArgsType& args)
  421. {
  422. WinRTWrapper::ComPtr<IUriRuntimeClass> uri;
  423. args.get_Uri (uri.resetAndGetPointerAddress());
  424. if (uri != nullptr)
  425. {
  426. HSTRING uriString;
  427. uri->get_AbsoluteUri (&uriString);
  428. return WinRTWrapper::getInstance()->hStringToString (uriString);
  429. }
  430. return {};
  431. }
  432. void addEventHandlers()
  433. {
  434. if (webViewControl != nullptr)
  435. {
  436. webViewControl->add_NavigationStarting (Callback<ITypedEventHandler<IWebViewControl*, WebViewControlNavigationStartingEventArgs*>> (
  437. [this] (IWebViewControl*, IWebViewControlNavigationStartingEventArgs* args)
  438. {
  439. auto uriString = getURIStringFromArgs (*args);
  440. if (uriString.isNotEmpty())
  441. args->put_Cancel (! owner.pageAboutToLoad (uriString));
  442. return S_OK;
  443. }
  444. ).Get(), &navigationStartingToken);
  445. webViewControl->add_NewWindowRequested (Callback<ITypedEventHandler<IWebViewControl*, WebViewControlNewWindowRequestedEventArgs*>> (
  446. [this] (IWebViewControl*, IWebViewControlNewWindowRequestedEventArgs* args)
  447. {
  448. auto uriString = getURIStringFromArgs (*args);
  449. if (uriString.isNotEmpty())
  450. {
  451. owner.newWindowAttemptingToLoad (uriString);
  452. args->put_Handled (true);
  453. }
  454. return S_OK;
  455. }
  456. ).Get(), &newWindowRequestedToken);
  457. webViewControl->add_NavigationCompleted (Callback<ITypedEventHandler<IWebViewControl*, WebViewControlNavigationCompletedEventArgs*>> (
  458. [this] (IWebViewControl*, IWebViewControlNavigationCompletedEventArgs* args)
  459. {
  460. auto uriString = getURIStringFromArgs (*args);
  461. if (uriString.isNotEmpty())
  462. {
  463. boolean success;
  464. args->get_IsSuccess (&success);
  465. if (success)
  466. {
  467. owner.pageFinishedLoading (uriString);
  468. }
  469. else
  470. {
  471. WebErrorStatus status;
  472. args->get_WebErrorStatus (&status);
  473. owner.pageLoadHadNetworkError ("Error code: " + String (status));
  474. }
  475. }
  476. return S_OK;
  477. }
  478. ).Get(), &navigationCompletedToken);
  479. }
  480. }
  481. void removeEventHandlers()
  482. {
  483. if (webViewControl != nullptr)
  484. {
  485. if (navigationStartingToken.value != 0)
  486. webViewControl->remove_NavigationStarting (navigationStartingToken);
  487. if (newWindowRequestedToken.value != 0)
  488. webViewControl->remove_NewWindowRequested (newWindowRequestedToken);
  489. if (navigationCompletedToken.value != 0)
  490. webViewControl->remove_NavigationCompleted (navigationCompletedToken);
  491. }
  492. }
  493. bool createWebViewProcess()
  494. {
  495. auto webViewControlProcessFactory
  496. = WinRTWrapper::getInstance()->getWRLFactory<IWebViewControlProcessFactory> (RuntimeClass_Windows_Web_UI_Interop_WebViewControlProcess);
  497. if (webViewControlProcessFactory == nullptr)
  498. {
  499. jassertfalse;
  500. return false;
  501. }
  502. auto webViewProcessOptions
  503. = WinRTWrapper::getInstance()->activateInstance<IWebViewControlProcessOptions> (RuntimeClass_Windows_Web_UI_Interop_WebViewControlProcessOptions,
  504. __uuidof (IWebViewControlProcessOptions));
  505. webViewProcessOptions->put_PrivateNetworkClientServerCapability (WebViewControlProcessCapabilityState_Enabled);
  506. webViewControlProcessFactory->CreateWithOptions (webViewProcessOptions.get(), webViewProcess.resetAndGetPointerAddress());
  507. return webViewProcess != nullptr;
  508. }
  509. void createWebViewControl()
  510. {
  511. if (auto* peer = getPeer())
  512. {
  513. ScopedValueSetter<bool> svs (isCreating, true);
  514. WinRTWrapper::ComPtr<IAsyncOperation<WebViewControl*>> createWebViewAsyncOperation;
  515. webViewProcess->CreateWebViewControlAsync ((INT64) peer->getNativeHandle(), {},
  516. createWebViewAsyncOperation.resetAndGetPointerAddress());
  517. waitForCompletion (createWebViewAsyncOperation.get(), webViewControl.resetAndGetPointerAddress());
  518. addEventHandlers();
  519. componentMovedOrResized (true, true);
  520. }
  521. }
  522. //==============================================================================
  523. WinRTWrapper::ComPtr<IUriRuntimeClass> createURI (const String& url)
  524. {
  525. auto uriRuntimeFactory
  526. = WinRTWrapper::getInstance()->getWRLFactory <IUriRuntimeClassFactory> (RuntimeClass_Windows_Foundation_Uri);
  527. if (uriRuntimeFactory == nullptr)
  528. {
  529. jassertfalse;
  530. return {};
  531. }
  532. WinRTWrapper::ScopedHString hstr (url);
  533. WinRTWrapper::ComPtr<IUriRuntimeClass> uriRuntimeClass;
  534. uriRuntimeFactory->CreateUri (hstr.get(), uriRuntimeClass.resetAndGetPointerAddress());
  535. return uriRuntimeClass;
  536. }
  537. WinRTWrapper::ComPtr<IHttpContent> getPOSTContent (const MemoryBlock& postData)
  538. {
  539. auto factory = WinRTWrapper::getInstance()->getWRLFactory<IHttpStringContentFactory> (RuntimeClass_Windows_Web_Http_HttpStringContent);
  540. if (factory == nullptr)
  541. {
  542. jassertfalse;
  543. return {};
  544. }
  545. WinRTWrapper::ScopedHString hStr (postData.toString());
  546. WinRTWrapper::ComPtr<IHttpContent> content;
  547. factory->CreateFromString (hStr.get(), content.resetAndGetPointerAddress());
  548. return content;
  549. }
  550. WinRTWrapper::ComPtr<IHttpMethod> getMethod (bool isPOST)
  551. {
  552. auto methodFactory = WinRTWrapper::getInstance()->getWRLFactory<IHttpMethodStatics> (RuntimeClass_Windows_Web_Http_HttpMethod);
  553. if (methodFactory == nullptr)
  554. {
  555. jassertfalse;
  556. return {};
  557. }
  558. WinRTWrapper::ComPtr<IHttpMethod> method;
  559. if (isPOST)
  560. methodFactory->get_Post (method.resetAndGetPointerAddress());
  561. else
  562. methodFactory->get_Get (method.resetAndGetPointerAddress());
  563. return method;
  564. }
  565. void addHttpHeaders (WinRTWrapper::ComPtr<IHttpRequestMessage>& requestMessage, const StringArray& headers)
  566. {
  567. WinRTWrapper::ComPtr<IHttpRequestHeaderCollection> headerCollection;
  568. requestMessage->get_Headers (headerCollection.resetAndGetPointerAddress());
  569. for (int i = 0; i < headers.size(); ++i)
  570. {
  571. WinRTWrapper::ScopedHString headerName (headers[i].upToFirstOccurrenceOf (":", false, false).trim());
  572. WinRTWrapper::ScopedHString headerValue (headers[i].fromFirstOccurrenceOf (":", false, false).trim());
  573. headerCollection->Append (headerName.get(), headerValue.get());
  574. }
  575. }
  576. WinRTWrapper::ComPtr<IHttpRequestMessage> createHttpRequestMessage (const String& url,
  577. const StringArray* headers,
  578. const MemoryBlock* postData)
  579. {
  580. auto requestFactory
  581. = WinRTWrapper::getInstance()->getWRLFactory<IHttpRequestMessageFactory> (RuntimeClass_Windows_Web_Http_HttpRequestMessage);
  582. if (requestFactory == nullptr)
  583. {
  584. jassertfalse;
  585. return {};
  586. }
  587. bool isPOSTRequest = (postData != nullptr && postData->getSize() > 0);
  588. auto method = getMethod (isPOSTRequest);
  589. auto uri = createURI (url);
  590. WinRTWrapper::ComPtr<IHttpRequestMessage> requestMessage;
  591. requestFactory->Create (method.get(), uri.get(), requestMessage.resetAndGetPointerAddress());
  592. if (isPOSTRequest)
  593. {
  594. auto content = getPOSTContent (*postData);
  595. requestMessage->put_Content (content.get());
  596. }
  597. if (headers != nullptr && ! headers->isEmpty())
  598. addHttpHeaders (requestMessage, *headers);
  599. return requestMessage;
  600. }
  601. //==============================================================================
  602. void setControlBounds (Rectangle<int> newBounds) const
  603. {
  604. if (webViewControl != nullptr)
  605. {
  606. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  607. if (auto* peer = owner.getTopLevelComponent()->getPeer())
  608. newBounds = (newBounds.toDouble() * peer->getPlatformScaleFactor()).toNearestInt();
  609. #endif
  610. WinRTWrapper::ComPtr<IWebViewControlSite> site;
  611. if (SUCCEEDED (webViewControl->QueryInterface (site.resetAndGetPointerAddress())))
  612. site->put_Bounds ({ static_cast<FLOAT> (newBounds.getX()), static_cast<FLOAT> (newBounds.getY()),
  613. static_cast<FLOAT> (newBounds.getWidth()), static_cast<FLOAT> (newBounds.getHeight()) });
  614. }
  615. }
  616. void setControlVisible (bool shouldBeVisible) const
  617. {
  618. if (webViewControl != 0)
  619. {
  620. WinRTWrapper::ComPtr<IWebViewControlSite> site;
  621. if (SUCCEEDED (webViewControl->QueryInterface (site.resetAndGetPointerAddress())))
  622. site->put_IsVisible (shouldBeVisible);
  623. }
  624. }
  625. //==============================================================================
  626. WebBrowserComponent& owner;
  627. WinRTWrapper::ComPtr<IWebViewControlProcess> webViewProcess;
  628. WinRTWrapper::ComPtr<IWebViewControl> webViewControl;
  629. EventRegistrationToken navigationStartingToken { 0 },
  630. newWindowRequestedToken { 0 },
  631. navigationCompletedToken { 0 };
  632. bool isCreating = false;
  633. };
  634. #endif
  635. //==============================================================================
  636. class WebBrowserComponent::Pimpl
  637. {
  638. public:
  639. Pimpl (WebBrowserComponent& owner)
  640. {
  641. #if JUCE_USE_WINRT_WEBVIEW
  642. auto windowsVersionInfo = getWindowsVersionInfo();
  643. if (windowsVersionInfo.dwMajorVersion >= 10 && windowsVersionInfo.dwBuildNumber >= 17763)
  644. {
  645. try
  646. {
  647. internal.reset (new WinRTWebView (owner));
  648. }
  649. catch (std::runtime_error&) {}
  650. }
  651. #endif
  652. if (internal == nullptr)
  653. internal.reset (new Win32WebView (owner));
  654. }
  655. InternalWebViewType& getInternalWebView()
  656. {
  657. return *internal;
  658. }
  659. private:
  660. std::unique_ptr<InternalWebViewType> internal;
  661. };
  662. //==============================================================================
  663. WebBrowserComponent::WebBrowserComponent (bool unloadWhenHidden)
  664. : browser (new Pimpl (*this)),
  665. unloadPageWhenBrowserIsHidden (unloadWhenHidden)
  666. {
  667. setOpaque (true);
  668. }
  669. WebBrowserComponent::~WebBrowserComponent()
  670. {
  671. }
  672. //==============================================================================
  673. void WebBrowserComponent::goToURL (const String& url,
  674. const StringArray* headers,
  675. const MemoryBlock* postData)
  676. {
  677. lastURL = url;
  678. if (headers != nullptr)
  679. lastHeaders = *headers;
  680. else
  681. lastHeaders.clear();
  682. if (postData != nullptr)
  683. lastPostData = *postData;
  684. else
  685. lastPostData.reset();
  686. blankPageShown = false;
  687. if (! browser->getInternalWebView().hasBrowserBeenCreated())
  688. checkWindowAssociation();
  689. browser->getInternalWebView().goToURL (url, headers, postData);
  690. }
  691. void WebBrowserComponent::stop()
  692. {
  693. browser->getInternalWebView().stop();
  694. }
  695. void WebBrowserComponent::goBack()
  696. {
  697. lastURL.clear();
  698. blankPageShown = false;
  699. browser->getInternalWebView().goBack();
  700. }
  701. void WebBrowserComponent::goForward()
  702. {
  703. lastURL.clear();
  704. browser->getInternalWebView().goForward();
  705. }
  706. void WebBrowserComponent::refresh()
  707. {
  708. browser->getInternalWebView().refresh();
  709. }
  710. //==============================================================================
  711. void WebBrowserComponent::paint (Graphics& g)
  712. {
  713. if (! browser->getInternalWebView().hasBrowserBeenCreated())
  714. {
  715. g.fillAll (Colours::white);
  716. checkWindowAssociation();
  717. }
  718. }
  719. void WebBrowserComponent::checkWindowAssociation()
  720. {
  721. if (isShowing())
  722. {
  723. if (! browser->getInternalWebView().hasBrowserBeenCreated() && getPeer() != nullptr)
  724. {
  725. browser->getInternalWebView().createBrowser();
  726. reloadLastURL();
  727. }
  728. else
  729. {
  730. if (blankPageShown)
  731. goBack();
  732. }
  733. }
  734. else
  735. {
  736. if (browser != nullptr && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  737. {
  738. // when the component becomes invisible, some stuff like flash
  739. // carries on playing audio, so we need to force it onto a blank
  740. // page to avoid this..
  741. blankPageShown = true;
  742. browser->getInternalWebView().goToURL ("about:blank", 0, 0);
  743. }
  744. }
  745. }
  746. void WebBrowserComponent::reloadLastURL()
  747. {
  748. if (lastURL.isNotEmpty())
  749. {
  750. goToURL (lastURL, &lastHeaders, &lastPostData);
  751. lastURL.clear();
  752. }
  753. }
  754. void WebBrowserComponent::parentHierarchyChanged()
  755. {
  756. checkWindowAssociation();
  757. }
  758. void WebBrowserComponent::resized()
  759. {
  760. browser->getInternalWebView().setWebViewSize (getWidth(), getHeight());
  761. }
  762. void WebBrowserComponent::visibilityChanged()
  763. {
  764. checkWindowAssociation();
  765. }
  766. void WebBrowserComponent::focusGained (FocusChangeType)
  767. {
  768. browser->getInternalWebView().focusGained();
  769. }
  770. void WebBrowserComponent::clearCookies()
  771. {
  772. HeapBlock<::INTERNET_CACHE_ENTRY_INFOA> entry;
  773. ::DWORD entrySize = sizeof (::INTERNET_CACHE_ENTRY_INFOA);
  774. ::HANDLE urlCacheHandle = ::FindFirstUrlCacheEntryA ("cookie:", entry.getData(), &entrySize);
  775. if (urlCacheHandle == nullptr && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
  776. {
  777. entry.realloc (1, entrySize);
  778. urlCacheHandle = ::FindFirstUrlCacheEntryA ("cookie:", entry.getData(), &entrySize);
  779. }
  780. if (urlCacheHandle != nullptr)
  781. {
  782. for (;;)
  783. {
  784. ::DeleteUrlCacheEntryA (entry.getData()->lpszSourceUrlName);
  785. if (::FindNextUrlCacheEntryA (urlCacheHandle, entry.getData(), &entrySize) == 0)
  786. {
  787. if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
  788. {
  789. entry.realloc (1, entrySize);
  790. if (::FindNextUrlCacheEntryA (urlCacheHandle, entry.getData(), &entrySize) != 0)
  791. continue;
  792. }
  793. break;
  794. }
  795. }
  796. FindCloseUrlCache (urlCacheHandle);
  797. }
  798. }
  799. } // namespace juce