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.

417 lines
14KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2015 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. #if JUCE_MAC
  18. struct DownloadClickDetectorClass : public ObjCClass<NSObject>
  19. {
  20. DownloadClickDetectorClass() : ObjCClass<NSObject> ("JUCEWebClickDetector_")
  21. {
  22. addIvar<WebBrowserComponent*> ("owner");
  23. addMethod (@selector (webView:decidePolicyForNavigationAction:request:frame:decisionListener:),
  24. decidePolicyForNavigationAction, "v@:@@@@@");
  25. addMethod (@selector (webView:decidePolicyForNewWindowAction:request:newFrameName:decisionListener:),
  26. decidePolicyForNewWindowAction, "v@:@@@@@");
  27. addMethod (@selector (webView:didFinishLoadForFrame:), didFinishLoadForFrame, "v@:@@");
  28. addMethod (@selector (webView:willCloseFrame:), willCloseFrame, "v@:@@");
  29. addMethod (@selector (webView:runOpenPanelForFileButtonWithResultListener:allowMultipleFiles:), runOpenPanel, "v@:@@", @encode (BOOL));
  30. registerClass();
  31. }
  32. static void setOwner (id self, WebBrowserComponent* owner) { object_setInstanceVariable (self, "owner", owner); }
  33. static WebBrowserComponent* getOwner (id self) { return getIvar<WebBrowserComponent*> (self, "owner"); }
  34. private:
  35. static String getOriginalURL (NSDictionary* actionInformation)
  36. {
  37. if (NSURL* url = [actionInformation valueForKey: nsStringLiteral ("WebActionOriginalURLKey")])
  38. return nsStringToJuce ([url absoluteString]);
  39. return String();
  40. }
  41. static void decidePolicyForNavigationAction (id self, SEL, WebView*, NSDictionary* actionInformation,
  42. NSURLRequest*, WebFrame*, id<WebPolicyDecisionListener> listener)
  43. {
  44. if (getOwner (self)->pageAboutToLoad (getOriginalURL (actionInformation)))
  45. [listener use];
  46. else
  47. [listener ignore];
  48. }
  49. static void decidePolicyForNewWindowAction (id self, SEL, WebView*, NSDictionary* actionInformation,
  50. NSURLRequest*, NSString*, id<WebPolicyDecisionListener> listener)
  51. {
  52. getOwner (self)->newWindowAttemptingToLoad (getOriginalURL (actionInformation));
  53. [listener ignore];
  54. }
  55. static void didFinishLoadForFrame (id self, SEL, WebView* sender, WebFrame* frame)
  56. {
  57. if ([frame isEqual: [sender mainFrame]])
  58. {
  59. NSURL* url = [[[frame dataSource] request] URL];
  60. getOwner (self)->pageFinishedLoading (nsStringToJuce ([url absoluteString]));
  61. }
  62. }
  63. static void willCloseFrame (id self, SEL, WebView*, WebFrame*)
  64. {
  65. getOwner (self)->windowCloseRequest();
  66. }
  67. static void runOpenPanel (id, SEL, WebView*, id<WebOpenPanelResultListener> resultListener, BOOL allowMultipleFiles)
  68. {
  69. #if JUCE_MODAL_LOOPS_PERMITTED
  70. FileChooser chooser (TRANS("Select the file you want to upload..."),
  71. File::getSpecialLocation (File::userHomeDirectory), "*");
  72. if (allowMultipleFiles ? chooser.browseForMultipleFilesToOpen()
  73. : chooser.browseForFileToOpen())
  74. {
  75. const Array<File>& files = chooser.getResults();
  76. for (int i = 0; i < files.size(); ++i)
  77. [resultListener chooseFilename: juceStringToNS (files.getReference(i).getFullPathName())];
  78. }
  79. #else
  80. ignoreUnused (resultListener, allowMultipleFiles);
  81. jassertfalse; // Can't use this without modal loops being enabled!
  82. #endif
  83. }
  84. };
  85. #else
  86. } // (juce namespace)
  87. //==============================================================================
  88. @interface WebViewTapDetector : NSObject<UIGestureRecognizerDelegate>
  89. {
  90. }
  91. - (BOOL) gestureRecognizer: (UIGestureRecognizer*) gestureRecognizer
  92. shouldRecognizeSimultaneouslyWithGestureRecognizer: (UIGestureRecognizer*) otherGestureRecognizer;
  93. @end
  94. @implementation WebViewTapDetector
  95. - (BOOL) gestureRecognizer: (UIGestureRecognizer*) gestureRecognizer
  96. shouldRecognizeSimultaneouslyWithGestureRecognizer: (UIGestureRecognizer*) otherGestureRecognizer
  97. {
  98. ignoreUnused (gestureRecognizer, otherGestureRecognizer);
  99. return YES;
  100. }
  101. @end
  102. //==============================================================================
  103. @interface WebViewURLChangeDetector : NSObject<UIWebViewDelegate>
  104. {
  105. juce::WebBrowserComponent* ownerComponent;
  106. }
  107. - (WebViewURLChangeDetector*) initWithWebBrowserOwner: (juce::WebBrowserComponent*) ownerComponent;
  108. - (BOOL) webView: (UIWebView*) webView shouldStartLoadWithRequest: (NSURLRequest*) request
  109. navigationType: (UIWebViewNavigationType) navigationType;
  110. - (void) webViewDidFinishLoad: (UIWebView*) webView;
  111. @end
  112. @implementation WebViewURLChangeDetector
  113. - (WebViewURLChangeDetector*) initWithWebBrowserOwner: (juce::WebBrowserComponent*) ownerComp
  114. {
  115. [super init];
  116. ownerComponent = ownerComp;
  117. return self;
  118. }
  119. - (BOOL) webView: (UIWebView*) webView shouldStartLoadWithRequest: (NSURLRequest*) request
  120. navigationType: (UIWebViewNavigationType) navigationType
  121. {
  122. ignoreUnused (webView, navigationType);
  123. return ownerComponent->pageAboutToLoad (nsStringToJuce (request.URL.absoluteString));
  124. }
  125. - (void) webViewDidFinishLoad: (UIWebView*) webView
  126. {
  127. ownerComponent->pageFinishedLoading (nsStringToJuce (webView.request.URL.absoluteString));
  128. }
  129. @end
  130. namespace juce {
  131. #endif
  132. //==============================================================================
  133. class WebBrowserComponent::Pimpl
  134. #if JUCE_MAC
  135. : public NSViewComponent
  136. #else
  137. : public UIViewComponent
  138. #endif
  139. {
  140. public:
  141. Pimpl (WebBrowserComponent* owner)
  142. {
  143. #if JUCE_MAC
  144. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  145. frameName: nsEmptyString()
  146. groupName: nsEmptyString()];
  147. setView (webView);
  148. static DownloadClickDetectorClass cls;
  149. clickListener = [cls.createInstance() init];
  150. DownloadClickDetectorClass::setOwner (clickListener, owner);
  151. [webView setPolicyDelegate: clickListener];
  152. [webView setFrameLoadDelegate: clickListener];
  153. [webView setUIDelegate: clickListener];
  154. #else
  155. webView = [[UIWebView alloc] initWithFrame: CGRectMake (0, 0, 1.0f, 1.0f)];
  156. setView (webView);
  157. tapDetector = [[WebViewTapDetector alloc] init];
  158. urlDetector = [[WebViewURLChangeDetector alloc] initWithWebBrowserOwner: owner];
  159. gestureRecogniser = nil;
  160. webView.delegate = urlDetector;
  161. #endif
  162. }
  163. ~Pimpl()
  164. {
  165. #if JUCE_MAC
  166. [webView setPolicyDelegate: nil];
  167. [webView setFrameLoadDelegate: nil];
  168. [webView setUIDelegate: nil];
  169. [clickListener release];
  170. #else
  171. webView.delegate = nil;
  172. [webView removeGestureRecognizer: gestureRecogniser];
  173. [gestureRecogniser release];
  174. [tapDetector release];
  175. [urlDetector release];
  176. #endif
  177. setView (nil);
  178. }
  179. void goToURL (const String& url,
  180. const StringArray* headers,
  181. const MemoryBlock* postData)
  182. {
  183. stop();
  184. if (url.trimStart().startsWithIgnoreCase ("javascript:"))
  185. {
  186. [webView stringByEvaluatingJavaScriptFromString:
  187. juceStringToNS (url.fromFirstOccurrenceOf (":", false, false))];
  188. }
  189. else
  190. {
  191. NSMutableURLRequest* r
  192. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  193. cachePolicy: NSURLRequestUseProtocolCachePolicy
  194. timeoutInterval: 30.0];
  195. if (postData != nullptr && postData->getSize() > 0)
  196. {
  197. [r setHTTPMethod: nsStringLiteral ("POST")];
  198. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  199. length: postData->getSize()]];
  200. }
  201. if (headers != nullptr)
  202. {
  203. for (int i = 0; i < headers->size(); ++i)
  204. {
  205. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  206. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  207. [r setValue: juceStringToNS (headerValue)
  208. forHTTPHeaderField: juceStringToNS (headerName)];
  209. }
  210. }
  211. #if JUCE_MAC
  212. [[webView mainFrame] loadRequest: r];
  213. #else
  214. [webView loadRequest: r];
  215. #endif
  216. #if JUCE_IOS
  217. [webView setScalesPageToFit:YES];
  218. #endif
  219. }
  220. }
  221. void goBack() { [webView goBack]; }
  222. void goForward() { [webView goForward]; }
  223. #if JUCE_MAC
  224. void stop() { [webView stopLoading: nil]; }
  225. void refresh() { [webView reload: nil]; }
  226. #else
  227. void stop() { [webView stopLoading]; }
  228. void refresh() { [webView reload]; }
  229. #endif
  230. void mouseMove (const MouseEvent&)
  231. {
  232. // WebKit doesn't capture mouse-moves itself, so it seems the only way to make
  233. // them work is to push them via this non-public method..
  234. if ([webView respondsToSelector: @selector (_updateMouseoverWithFakeEvent)])
  235. [webView performSelector: @selector (_updateMouseoverWithFakeEvent)];
  236. }
  237. private:
  238. #if JUCE_MAC
  239. WebView* webView;
  240. id clickListener;
  241. #else
  242. UIWebView* webView;
  243. WebViewTapDetector* tapDetector;
  244. WebViewURLChangeDetector* urlDetector;
  245. UITapGestureRecognizer* gestureRecogniser;
  246. #endif
  247. };
  248. //==============================================================================
  249. WebBrowserComponent::WebBrowserComponent (const bool unloadWhenHidden)
  250. : browser (nullptr),
  251. blankPageShown (false),
  252. unloadPageWhenBrowserIsHidden (unloadWhenHidden)
  253. {
  254. setOpaque (true);
  255. addAndMakeVisible (browser = new Pimpl (this));
  256. }
  257. WebBrowserComponent::~WebBrowserComponent()
  258. {
  259. deleteAndZero (browser);
  260. }
  261. //==============================================================================
  262. void WebBrowserComponent::goToURL (const String& url,
  263. const StringArray* headers,
  264. const MemoryBlock* postData)
  265. {
  266. lastURL = url;
  267. if (headers != nullptr)
  268. lastHeaders = *headers;
  269. else
  270. lastHeaders.clear();
  271. if (postData != nullptr)
  272. lastPostData = *postData;
  273. else
  274. lastPostData.reset();
  275. blankPageShown = false;
  276. browser->goToURL (url, headers, postData);
  277. }
  278. void WebBrowserComponent::stop()
  279. {
  280. browser->stop();
  281. }
  282. void WebBrowserComponent::goBack()
  283. {
  284. lastURL.clear();
  285. blankPageShown = false;
  286. browser->goBack();
  287. }
  288. void WebBrowserComponent::goForward()
  289. {
  290. lastURL.clear();
  291. browser->goForward();
  292. }
  293. void WebBrowserComponent::refresh()
  294. {
  295. browser->refresh();
  296. }
  297. //==============================================================================
  298. void WebBrowserComponent::paint (Graphics&)
  299. {
  300. }
  301. void WebBrowserComponent::checkWindowAssociation()
  302. {
  303. if (isShowing())
  304. {
  305. reloadLastURL();
  306. if (blankPageShown)
  307. goBack();
  308. }
  309. else
  310. {
  311. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  312. {
  313. // when the component becomes invisible, some stuff like flash
  314. // carries on playing audio, so we need to force it onto a blank
  315. // page to avoid this, (and send it back when it's made visible again).
  316. blankPageShown = true;
  317. browser->goToURL ("about:blank", 0, 0);
  318. }
  319. }
  320. }
  321. void WebBrowserComponent::reloadLastURL()
  322. {
  323. if (lastURL.isNotEmpty())
  324. {
  325. goToURL (lastURL, &lastHeaders, &lastPostData);
  326. lastURL.clear();
  327. }
  328. }
  329. void WebBrowserComponent::parentHierarchyChanged()
  330. {
  331. checkWindowAssociation();
  332. }
  333. void WebBrowserComponent::resized()
  334. {
  335. browser->setSize (getWidth(), getHeight());
  336. }
  337. void WebBrowserComponent::visibilityChanged()
  338. {
  339. checkWindowAssociation();
  340. }
  341. void WebBrowserComponent::focusGained (FocusChangeType)
  342. {
  343. }