The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

1272 lines
42KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 6 End-User License
  8. Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
  9. End User License Agreement: www.juce.com/juce-6-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. #if defined (__IPHONE_13_0)
  19. #define JUCE_HAS_IOS_POINTER_SUPPORT 1
  20. #else
  21. #define JUCE_HAS_IOS_POINTER_SUPPORT 0
  22. #endif
  23. namespace juce
  24. {
  25. class UIViewComponentPeer;
  26. static UIInterfaceOrientation getWindowOrientation()
  27. {
  28. UIApplication* sharedApplication = [UIApplication sharedApplication];
  29. #if (defined (__IPHONE_13_0) && __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_13_0)
  30. for (UIScene* scene in [sharedApplication connectedScenes])
  31. if ([scene isKindOfClass: [UIWindowScene class]])
  32. return [(UIWindowScene*) scene interfaceOrientation];
  33. return UIInterfaceOrientationPortrait;
  34. #else
  35. return [sharedApplication statusBarOrientation];
  36. #endif
  37. }
  38. namespace Orientations
  39. {
  40. static Desktop::DisplayOrientation convertToJuce (UIInterfaceOrientation orientation)
  41. {
  42. switch (orientation)
  43. {
  44. case UIInterfaceOrientationPortrait: return Desktop::upright;
  45. case UIInterfaceOrientationPortraitUpsideDown: return Desktop::upsideDown;
  46. case UIInterfaceOrientationLandscapeLeft: return Desktop::rotatedClockwise;
  47. case UIInterfaceOrientationLandscapeRight: return Desktop::rotatedAntiClockwise;
  48. case UIInterfaceOrientationUnknown:
  49. default: jassertfalse; // unknown orientation!
  50. }
  51. return Desktop::upright;
  52. }
  53. static UIInterfaceOrientation convertFromJuce (Desktop::DisplayOrientation orientation)
  54. {
  55. switch (orientation)
  56. {
  57. case Desktop::upright: return UIInterfaceOrientationPortrait;
  58. case Desktop::upsideDown: return UIInterfaceOrientationPortraitUpsideDown;
  59. case Desktop::rotatedClockwise: return UIInterfaceOrientationLandscapeLeft;
  60. case Desktop::rotatedAntiClockwise: return UIInterfaceOrientationLandscapeRight;
  61. case Desktop::allOrientations:
  62. default: jassertfalse; // unknown orientation!
  63. }
  64. return UIInterfaceOrientationPortrait;
  65. }
  66. static NSUInteger getSupportedOrientations()
  67. {
  68. NSUInteger allowed = 0;
  69. auto& d = Desktop::getInstance();
  70. if (d.isOrientationEnabled (Desktop::upright)) allowed |= UIInterfaceOrientationMaskPortrait;
  71. if (d.isOrientationEnabled (Desktop::upsideDown)) allowed |= UIInterfaceOrientationMaskPortraitUpsideDown;
  72. if (d.isOrientationEnabled (Desktop::rotatedClockwise)) allowed |= UIInterfaceOrientationMaskLandscapeLeft;
  73. if (d.isOrientationEnabled (Desktop::rotatedAntiClockwise)) allowed |= UIInterfaceOrientationMaskLandscapeRight;
  74. return allowed;
  75. }
  76. }
  77. enum class MouseEventFlags
  78. {
  79. none,
  80. down,
  81. up,
  82. upAndCancel,
  83. };
  84. //==============================================================================
  85. } // namespace juce
  86. using namespace juce;
  87. @interface JuceUIView : UIView <UITextViewDelegate>
  88. {
  89. @public
  90. UIViewComponentPeer* owner;
  91. UITextView* hiddenTextView;
  92. }
  93. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  94. - (void) dealloc;
  95. - (void) drawRect: (CGRect) r;
  96. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  97. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  98. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  99. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  100. #if JUCE_HAS_IOS_POINTER_SUPPORT
  101. - (void) onHover: (UIHoverGestureRecognizer*) gesture API_AVAILABLE (ios (13.0));
  102. - (void) onScroll: (UIPanGestureRecognizer*) gesture;
  103. #endif
  104. - (BOOL) becomeFirstResponder;
  105. - (BOOL) resignFirstResponder;
  106. - (BOOL) canBecomeFirstResponder;
  107. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text;
  108. - (void) traitCollectionDidChange: (UITraitCollection*) previousTraitCollection;
  109. - (BOOL) isAccessibilityElement;
  110. - (CGRect) accessibilityFrame;
  111. - (NSArray*) accessibilityElements;
  112. @end
  113. //==============================================================================
  114. @interface JuceUIViewController : UIViewController
  115. {
  116. }
  117. - (JuceUIViewController*) init;
  118. - (NSUInteger) supportedInterfaceOrientations;
  119. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation;
  120. - (void) willRotateToInterfaceOrientation: (UIInterfaceOrientation) toInterfaceOrientation duration: (NSTimeInterval) duration;
  121. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation;
  122. - (void) viewWillTransitionToSize: (CGSize) size withTransitionCoordinator: (id<UIViewControllerTransitionCoordinator>) coordinator;
  123. - (BOOL) prefersStatusBarHidden;
  124. - (UIStatusBarStyle) preferredStatusBarStyle;
  125. - (void) viewDidLoad;
  126. - (void) viewWillAppear: (BOOL) animated;
  127. - (void) viewDidAppear: (BOOL) animated;
  128. - (void) viewWillLayoutSubviews;
  129. - (void) viewDidLayoutSubviews;
  130. @end
  131. //==============================================================================
  132. @interface JuceUIWindow : UIWindow
  133. {
  134. @private
  135. UIViewComponentPeer* owner;
  136. }
  137. - (void) setOwner: (UIViewComponentPeer*) owner;
  138. - (void) becomeKeyWindow;
  139. @end
  140. //==============================================================================
  141. //==============================================================================
  142. namespace juce
  143. {
  144. struct UIViewPeerControllerReceiver
  145. {
  146. virtual ~UIViewPeerControllerReceiver() = default;
  147. virtual void setViewController (UIViewController*) = 0;
  148. };
  149. class UIViewComponentPeer : public ComponentPeer,
  150. public FocusChangeListener,
  151. public UIViewPeerControllerReceiver
  152. {
  153. public:
  154. UIViewComponentPeer (Component&, int windowStyleFlags, UIView* viewToAttachTo);
  155. ~UIViewComponentPeer() override;
  156. //==============================================================================
  157. void* getNativeHandle() const override { return view; }
  158. void setVisible (bool shouldBeVisible) override;
  159. void setTitle (const String& title) override;
  160. void setBounds (const Rectangle<int>&, bool isNowFullScreen) override;
  161. void setViewController (UIViewController* newController) override
  162. {
  163. jassert (controller == nullptr);
  164. controller = [newController retain];
  165. }
  166. Rectangle<int> getBounds() const override { return getBounds (! isSharedWindow); }
  167. Rectangle<int> getBounds (bool global) const;
  168. Point<float> localToGlobal (Point<float> relativePosition) override;
  169. Point<float> globalToLocal (Point<float> screenPosition) override;
  170. using ComponentPeer::localToGlobal;
  171. using ComponentPeer::globalToLocal;
  172. void setAlpha (float newAlpha) override;
  173. void setMinimised (bool) override {}
  174. bool isMinimised() const override { return false; }
  175. void setFullScreen (bool shouldBeFullScreen) override;
  176. bool isFullScreen() const override { return fullScreen; }
  177. bool contains (Point<int> localPos, bool trueIfInAChildWindow) const override;
  178. BorderSize<int> getFrameSize() const override { return BorderSize<int>(); }
  179. bool setAlwaysOnTop (bool alwaysOnTop) override;
  180. void toFront (bool makeActiveWindow) override;
  181. void toBehind (ComponentPeer* other) override;
  182. void setIcon (const Image& newIcon) override;
  183. StringArray getAvailableRenderingEngines() override { return StringArray ("CoreGraphics Renderer"); }
  184. void drawRect (CGRect);
  185. bool canBecomeKeyWindow();
  186. //==============================================================================
  187. void viewFocusGain();
  188. void viewFocusLoss();
  189. bool isFocused() const override;
  190. void grabFocus() override;
  191. void textInputRequired (Point<int>, TextInputTarget&) override;
  192. BOOL textViewReplaceCharacters (Range<int>, const String&);
  193. void updateHiddenTextContent (TextInputTarget*);
  194. void globalFocusChanged (Component*) override;
  195. void updateScreenBounds();
  196. void handleTouches (UIEvent*, MouseEventFlags);
  197. #if JUCE_HAS_IOS_POINTER_SUPPORT
  198. API_AVAILABLE (ios (13.0)) void onHover (UIHoverGestureRecognizer*);
  199. void onScroll (UIPanGestureRecognizer*);
  200. #endif
  201. //==============================================================================
  202. void repaint (const Rectangle<int>& area) override;
  203. void performAnyPendingRepaintsNow() override;
  204. //==============================================================================
  205. UIWindow* window = nil;
  206. JuceUIView* view = nil;
  207. UIViewController* controller = nil;
  208. const bool isSharedWindow, isAppex;
  209. bool fullScreen = false, insideDrawRect = false;
  210. static int64 getMouseTime (NSTimeInterval timestamp) noexcept
  211. {
  212. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  213. + (int64) (timestamp * 1000.0);
  214. }
  215. static int64 getMouseTime (UIEvent* e) noexcept
  216. {
  217. return getMouseTime ([e timestamp]);
  218. }
  219. static NSString* getDarkModeNotificationName()
  220. {
  221. return @"ViewDarkModeChanged";
  222. }
  223. static MultiTouchMapper<UITouch*> currentTouches;
  224. private:
  225. //==============================================================================
  226. class AsyncRepaintMessage : public CallbackMessage
  227. {
  228. public:
  229. UIViewComponentPeer* const peer;
  230. const Rectangle<int> rect;
  231. AsyncRepaintMessage (UIViewComponentPeer* const p, const Rectangle<int>& r)
  232. : peer (p), rect (r)
  233. {
  234. }
  235. void messageCallback() override
  236. {
  237. if (ComponentPeer::isValidPeer (peer))
  238. peer->repaint (rect);
  239. }
  240. };
  241. //==============================================================================
  242. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIViewComponentPeer)
  243. };
  244. static UIViewComponentPeer* getViewPeer (JuceUIViewController* c)
  245. {
  246. if (JuceUIView* juceView = (JuceUIView*) [c view])
  247. return juceView->owner;
  248. jassertfalse;
  249. return nullptr;
  250. }
  251. static void sendScreenBoundsUpdate (JuceUIViewController* c)
  252. {
  253. if (auto* peer = getViewPeer (c))
  254. peer->updateScreenBounds();
  255. }
  256. static bool isKioskModeView (JuceUIViewController* c)
  257. {
  258. if (auto* peer = getViewPeer (c))
  259. return Desktop::getInstance().getKioskModeComponent() == &(peer->getComponent());
  260. return false;
  261. }
  262. MultiTouchMapper<UITouch*> UIViewComponentPeer::currentTouches;
  263. } // namespace juce
  264. //==============================================================================
  265. //==============================================================================
  266. @implementation JuceUIViewController
  267. - (JuceUIViewController*) init
  268. {
  269. self = [super init];
  270. return self;
  271. }
  272. - (NSUInteger) supportedInterfaceOrientations
  273. {
  274. return Orientations::getSupportedOrientations();
  275. }
  276. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation
  277. {
  278. return Desktop::getInstance().isOrientationEnabled (Orientations::convertToJuce (interfaceOrientation));
  279. }
  280. - (void) willRotateToInterfaceOrientation: (UIInterfaceOrientation) toInterfaceOrientation
  281. duration: (NSTimeInterval) duration
  282. {
  283. ignoreUnused (toInterfaceOrientation, duration);
  284. [UIView setAnimationsEnabled: NO]; // disable this because it goes the wrong way and looks like crap.
  285. }
  286. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation
  287. {
  288. ignoreUnused (fromInterfaceOrientation);
  289. sendScreenBoundsUpdate (self);
  290. [UIView setAnimationsEnabled: YES];
  291. }
  292. - (void) viewWillTransitionToSize: (CGSize) size withTransitionCoordinator: (id<UIViewControllerTransitionCoordinator>) coordinator
  293. {
  294. [super viewWillTransitionToSize: size withTransitionCoordinator: coordinator];
  295. [coordinator animateAlongsideTransition: nil completion: ^void (id<UIViewControllerTransitionCoordinatorContext>)
  296. {
  297. sendScreenBoundsUpdate (self);
  298. }];
  299. }
  300. - (BOOL) prefersStatusBarHidden
  301. {
  302. if (isKioskModeView (self))
  303. return true;
  304. return [[[NSBundle mainBundle] objectForInfoDictionaryKey: @"UIStatusBarHidden"] boolValue];
  305. }
  306. #if defined (__IPHONE_11_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_11_0
  307. - (BOOL) prefersHomeIndicatorAutoHidden
  308. {
  309. return isKioskModeView (self);
  310. }
  311. #endif
  312. - (UIStatusBarStyle) preferredStatusBarStyle
  313. {
  314. return UIStatusBarStyleDefault;
  315. }
  316. - (void) viewDidLoad
  317. {
  318. sendScreenBoundsUpdate (self);
  319. [super viewDidLoad];
  320. }
  321. - (void) viewWillAppear: (BOOL) animated
  322. {
  323. sendScreenBoundsUpdate (self);
  324. [super viewWillAppear:animated];
  325. }
  326. - (void) viewDidAppear: (BOOL) animated
  327. {
  328. sendScreenBoundsUpdate (self);
  329. [super viewDidAppear:animated];
  330. }
  331. - (void) viewWillLayoutSubviews
  332. {
  333. sendScreenBoundsUpdate (self);
  334. }
  335. - (void) viewDidLayoutSubviews
  336. {
  337. sendScreenBoundsUpdate (self);
  338. }
  339. @end
  340. @implementation JuceUIView
  341. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) peer
  342. withFrame: (CGRect) frame
  343. {
  344. [super initWithFrame: frame];
  345. owner = peer;
  346. hiddenTextView = [[UITextView alloc] initWithFrame: CGRectZero];
  347. [self addSubview: hiddenTextView];
  348. hiddenTextView.delegate = self;
  349. hiddenTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
  350. hiddenTextView.autocorrectionType = UITextAutocorrectionTypeNo;
  351. hiddenTextView.inputAssistantItem.leadingBarButtonGroups = @[];
  352. hiddenTextView.inputAssistantItem.trailingBarButtonGroups = @[];
  353. #if JUCE_HAS_IOS_POINTER_SUPPORT
  354. if (@available (iOS 13.4, *))
  355. {
  356. auto hoverRecognizer = [[[UIHoverGestureRecognizer alloc] initWithTarget: self action: @selector (onHover:)] autorelease];
  357. [hoverRecognizer setCancelsTouchesInView: NO];
  358. [hoverRecognizer setRequiresExclusiveTouchType: YES];
  359. [self addGestureRecognizer: hoverRecognizer];
  360. auto panRecognizer = [[[UIPanGestureRecognizer alloc] initWithTarget: self action: @selector (onScroll:)] autorelease];
  361. [panRecognizer setCancelsTouchesInView: NO];
  362. [panRecognizer setRequiresExclusiveTouchType: YES];
  363. [panRecognizer setAllowedScrollTypesMask: UIScrollTypeMaskAll];
  364. [panRecognizer setMaximumNumberOfTouches: 0];
  365. [self addGestureRecognizer: panRecognizer];
  366. }
  367. #endif
  368. return self;
  369. }
  370. - (void) dealloc
  371. {
  372. [hiddenTextView removeFromSuperview];
  373. [hiddenTextView release];
  374. [super dealloc];
  375. }
  376. //==============================================================================
  377. - (void) drawRect: (CGRect) r
  378. {
  379. if (owner != nullptr)
  380. owner->drawRect (r);
  381. }
  382. //==============================================================================
  383. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  384. {
  385. ignoreUnused (touches);
  386. if (owner != nullptr)
  387. owner->handleTouches (event, MouseEventFlags::down);
  388. }
  389. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  390. {
  391. ignoreUnused (touches);
  392. if (owner != nullptr)
  393. owner->handleTouches (event, MouseEventFlags::none);
  394. }
  395. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  396. {
  397. ignoreUnused (touches);
  398. if (owner != nullptr)
  399. owner->handleTouches (event, MouseEventFlags::up);
  400. }
  401. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  402. {
  403. if (owner != nullptr)
  404. owner->handleTouches (event, MouseEventFlags::upAndCancel);
  405. [self touchesEnded: touches withEvent: event];
  406. }
  407. #if JUCE_HAS_IOS_POINTER_SUPPORT
  408. - (void) onHover: (UIHoverGestureRecognizer*) gesture
  409. {
  410. if (owner != nullptr)
  411. owner->onHover (gesture);
  412. }
  413. - (void) onScroll: (UIPanGestureRecognizer*) gesture
  414. {
  415. if (owner != nullptr)
  416. owner->onScroll (gesture);
  417. }
  418. #endif
  419. //==============================================================================
  420. - (BOOL) becomeFirstResponder
  421. {
  422. if (owner != nullptr)
  423. owner->viewFocusGain();
  424. return true;
  425. }
  426. - (BOOL) resignFirstResponder
  427. {
  428. if (owner != nullptr)
  429. owner->viewFocusLoss();
  430. return [super resignFirstResponder];
  431. }
  432. - (BOOL) canBecomeFirstResponder
  433. {
  434. return owner != nullptr && owner->canBecomeKeyWindow();
  435. }
  436. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
  437. {
  438. ignoreUnused (textView);
  439. return owner->textViewReplaceCharacters (Range<int> ((int) range.location, (int) (range.location + range.length)),
  440. nsStringToJuce (text));
  441. }
  442. - (void) traitCollectionDidChange: (UITraitCollection*) previousTraitCollection
  443. {
  444. [super traitCollectionDidChange: previousTraitCollection];
  445. #if defined (__IPHONE_12_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_12_0
  446. if (@available (iOS 12.0, *))
  447. {
  448. const auto wasDarkModeActive = ([previousTraitCollection userInterfaceStyle] == UIUserInterfaceStyleDark);
  449. if (wasDarkModeActive != Desktop::getInstance().isDarkModeActive())
  450. [[NSNotificationCenter defaultCenter] postNotificationName: UIViewComponentPeer::getDarkModeNotificationName()
  451. object: nil];
  452. }
  453. #endif
  454. }
  455. - (BOOL) isAccessibilityElement
  456. {
  457. return NO;
  458. }
  459. - (CGRect) accessibilityFrame
  460. {
  461. if (owner != nullptr)
  462. if (auto* handler = owner->getComponent().getAccessibilityHandler())
  463. return convertToCGRect (handler->getComponent().getScreenBounds());
  464. return CGRectZero;
  465. }
  466. - (NSArray*) accessibilityElements
  467. {
  468. if (owner != nullptr)
  469. if (auto* handler = owner->getComponent().getAccessibilityHandler())
  470. return getContainerAccessibilityElements (*handler);
  471. return nil;
  472. }
  473. @end
  474. //==============================================================================
  475. @implementation JuceUIWindow
  476. - (void) setOwner: (UIViewComponentPeer*) peer
  477. {
  478. owner = peer;
  479. }
  480. - (void) becomeKeyWindow
  481. {
  482. [super becomeKeyWindow];
  483. if (owner != nullptr)
  484. owner->grabFocus();
  485. }
  486. @end
  487. //==============================================================================
  488. //==============================================================================
  489. namespace juce
  490. {
  491. bool KeyPress::isKeyCurrentlyDown (int)
  492. {
  493. return false;
  494. }
  495. Point<float> juce_lastMousePos;
  496. //==============================================================================
  497. UIViewComponentPeer::UIViewComponentPeer (Component& comp, int windowStyleFlags, UIView* viewToAttachTo)
  498. : ComponentPeer (comp, windowStyleFlags),
  499. isSharedWindow (viewToAttachTo != nil),
  500. isAppex (SystemStats::isRunningInAppExtensionSandbox())
  501. {
  502. CGRect r = convertToCGRect (component.getBounds());
  503. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  504. view.multipleTouchEnabled = YES;
  505. view.hidden = true;
  506. view.opaque = component.isOpaque();
  507. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  508. #if JUCE_COREGRAPHICS_DRAW_ASYNC
  509. if (! getComponentAsyncLayerBackedViewDisabled (component))
  510. [[view layer] setDrawsAsynchronously: YES];
  511. #endif
  512. if (isSharedWindow)
  513. {
  514. window = [viewToAttachTo window];
  515. [viewToAttachTo addSubview: view];
  516. }
  517. else
  518. {
  519. r = convertToCGRect (component.getBounds());
  520. r.origin.y = [UIScreen mainScreen].bounds.size.height - (r.origin.y + r.size.height);
  521. window = [[JuceUIWindow alloc] initWithFrame: r];
  522. [((JuceUIWindow*) window) setOwner: this];
  523. controller = [[JuceUIViewController alloc] init];
  524. controller.view = view;
  525. window.rootViewController = controller;
  526. window.hidden = true;
  527. window.opaque = component.isOpaque();
  528. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  529. if (component.isAlwaysOnTop())
  530. window.windowLevel = UIWindowLevelAlert;
  531. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  532. }
  533. setTitle (component.getName());
  534. setVisible (component.isVisible());
  535. Desktop::getInstance().addFocusChangeListener (this);
  536. }
  537. UIViewComponentPeer::~UIViewComponentPeer()
  538. {
  539. currentTouches.deleteAllTouchesForPeer (this);
  540. Desktop::getInstance().removeFocusChangeListener (this);
  541. view->owner = nullptr;
  542. [view removeFromSuperview];
  543. [view release];
  544. [controller release];
  545. if (! isSharedWindow)
  546. {
  547. [((JuceUIWindow*) window) setOwner: nil];
  548. #if defined (__IPHONE_13_0)
  549. if (@available (iOS 13.0, *))
  550. window.windowScene = nil;
  551. #endif
  552. [window release];
  553. }
  554. }
  555. //==============================================================================
  556. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  557. {
  558. if (! isSharedWindow)
  559. window.hidden = ! shouldBeVisible;
  560. view.hidden = ! shouldBeVisible;
  561. }
  562. void UIViewComponentPeer::setTitle (const String&)
  563. {
  564. // xxx is this possible?
  565. }
  566. void UIViewComponentPeer::setBounds (const Rectangle<int>& newBounds, const bool isNowFullScreen)
  567. {
  568. fullScreen = isNowFullScreen;
  569. if (isSharedWindow)
  570. {
  571. CGRect r = convertToCGRect (newBounds);
  572. if (view.frame.size.width != r.size.width || view.frame.size.height != r.size.height)
  573. [view setNeedsDisplay];
  574. view.frame = r;
  575. }
  576. else
  577. {
  578. window.frame = convertToCGRect (newBounds);
  579. view.frame = CGRectMake (0, 0, (CGFloat) newBounds.getWidth(), (CGFloat) newBounds.getHeight());
  580. handleMovedOrResized();
  581. }
  582. }
  583. Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  584. {
  585. auto r = view.frame;
  586. if (global)
  587. {
  588. if (view.window != nil)
  589. {
  590. r = [view convertRect: r toView: view.window];
  591. r = [view.window convertRect: r toWindow: nil];
  592. }
  593. else if (window != nil)
  594. {
  595. r.origin.x += window.frame.origin.x;
  596. r.origin.y += window.frame.origin.y;
  597. }
  598. }
  599. return convertToRectInt (r);
  600. }
  601. Point<float> UIViewComponentPeer::localToGlobal (Point<float> relativePosition)
  602. {
  603. return relativePosition + getBounds (true).getPosition().toFloat();
  604. }
  605. Point<float> UIViewComponentPeer::globalToLocal (Point<float> screenPosition)
  606. {
  607. return screenPosition - getBounds (true).getPosition().toFloat();
  608. }
  609. void UIViewComponentPeer::setAlpha (float newAlpha)
  610. {
  611. [view.window setAlpha: (CGFloat) newAlpha];
  612. }
  613. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  614. {
  615. if (! isSharedWindow)
  616. {
  617. auto r = shouldBeFullScreen ? Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea
  618. : lastNonFullscreenBounds;
  619. if ((! shouldBeFullScreen) && r.isEmpty())
  620. r = getBounds();
  621. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  622. if (! r.isEmpty())
  623. setBounds (ScalingHelpers::scaledScreenPosToUnscaled (component, r), shouldBeFullScreen);
  624. component.repaint();
  625. }
  626. }
  627. void UIViewComponentPeer::updateScreenBounds()
  628. {
  629. auto& desktop = Desktop::getInstance();
  630. auto oldArea = component.getBounds();
  631. auto oldDesktop = desktop.getDisplays().getPrimaryDisplay()->userArea;
  632. forceDisplayUpdate();
  633. if (fullScreen)
  634. {
  635. fullScreen = false;
  636. setFullScreen (true);
  637. }
  638. else if (! isSharedWindow)
  639. {
  640. auto newDesktop = desktop.getDisplays().getPrimaryDisplay()->userArea;
  641. if (newDesktop != oldDesktop)
  642. {
  643. // this will re-centre the window, but leave its size unchanged
  644. auto centreRelX = oldArea.getCentreX() / (float) oldDesktop.getWidth();
  645. auto centreRelY = oldArea.getCentreY() / (float) oldDesktop.getHeight();
  646. auto x = ((int) (newDesktop.getWidth() * centreRelX)) - (oldArea.getWidth() / 2);
  647. auto y = ((int) (newDesktop.getHeight() * centreRelY)) - (oldArea.getHeight() / 2);
  648. component.setBounds (oldArea.withPosition (x, y));
  649. }
  650. }
  651. [view setNeedsDisplay];
  652. }
  653. bool UIViewComponentPeer::contains (Point<int> localPos, bool trueIfInAChildWindow) const
  654. {
  655. if (! ScalingHelpers::scaledScreenPosToUnscaled (component, component.getLocalBounds()).contains (localPos))
  656. return false;
  657. UIView* v = [view hitTest: convertToCGPoint (localPos)
  658. withEvent: nil];
  659. if (trueIfInAChildWindow)
  660. return v != nil;
  661. return v == view;
  662. }
  663. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  664. {
  665. if (! isSharedWindow)
  666. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  667. return true;
  668. }
  669. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  670. {
  671. if (isSharedWindow)
  672. [[view superview] bringSubviewToFront: view];
  673. if (makeActiveWindow && window != nil && component.isVisible())
  674. [window makeKeyAndVisible];
  675. }
  676. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  677. {
  678. if (auto* otherPeer = dynamic_cast<UIViewComponentPeer*> (other))
  679. {
  680. if (isSharedWindow)
  681. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  682. }
  683. else
  684. {
  685. jassertfalse; // wrong type of window?
  686. }
  687. }
  688. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  689. {
  690. // to do..
  691. }
  692. //==============================================================================
  693. static float getMaximumTouchForce (UITouch* touch) noexcept
  694. {
  695. if ([touch respondsToSelector: @selector (maximumPossibleForce)])
  696. return (float) touch.maximumPossibleForce;
  697. return 0.0f;
  698. }
  699. static float getTouchForce (UITouch* touch) noexcept
  700. {
  701. if ([touch respondsToSelector: @selector (force)])
  702. return (float) touch.force;
  703. return 0.0f;
  704. }
  705. void UIViewComponentPeer::handleTouches (UIEvent* event, MouseEventFlags mouseEventFlags)
  706. {
  707. NSArray* touches = [[event touchesForView: view] allObjects];
  708. for (unsigned int i = 0; i < [touches count]; ++i)
  709. {
  710. UITouch* touch = [touches objectAtIndex: i];
  711. auto maximumForce = getMaximumTouchForce (touch);
  712. if ([touch phase] == UITouchPhaseStationary && maximumForce <= 0)
  713. continue;
  714. auto pos = convertToPointFloat ([touch locationInView: view]);
  715. juce_lastMousePos = pos + getBounds (true).getPosition().toFloat();
  716. auto time = getMouseTime (event);
  717. auto touchIndex = currentTouches.getIndexOfTouch (this, touch);
  718. auto modsToSend = ModifierKeys::currentModifiers;
  719. auto isUp = [] (MouseEventFlags m)
  720. {
  721. return m == MouseEventFlags::up || m == MouseEventFlags::upAndCancel;
  722. };
  723. if (mouseEventFlags == MouseEventFlags::down)
  724. {
  725. if ([touch phase] != UITouchPhaseBegan)
  726. continue;
  727. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  728. modsToSend = ModifierKeys::currentModifiers;
  729. // this forces a mouse-enter/up event, in case for some reason we didn't get a mouse-up before.
  730. handleMouseEvent (MouseInputSource::InputSourceType::touch, pos, modsToSend.withoutMouseButtons(),
  731. MouseInputSource::invalidPressure, MouseInputSource::invalidOrientation, time, {}, touchIndex);
  732. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  733. return;
  734. }
  735. else if (isUp (mouseEventFlags))
  736. {
  737. if (! ([touch phase] == UITouchPhaseEnded || [touch phase] == UITouchPhaseCancelled))
  738. continue;
  739. modsToSend = modsToSend.withoutMouseButtons();
  740. currentTouches.clearTouch (touchIndex);
  741. if (! currentTouches.areAnyTouchesActive())
  742. mouseEventFlags = MouseEventFlags::upAndCancel;
  743. }
  744. if (mouseEventFlags == MouseEventFlags::upAndCancel)
  745. {
  746. currentTouches.clearTouch (touchIndex);
  747. modsToSend = ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons();
  748. }
  749. // NB: some devices return 0 or 1.0 if pressure is unknown, so we'll clip our value to a believable range:
  750. auto pressure = maximumForce > 0 ? jlimit (0.0001f, 0.9999f, getTouchForce (touch) / maximumForce)
  751. : MouseInputSource::invalidPressure;
  752. handleMouseEvent (MouseInputSource::InputSourceType::touch,
  753. pos, modsToSend, pressure, MouseInputSource::invalidOrientation, time, { }, touchIndex);
  754. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  755. return;
  756. if (isUp (mouseEventFlags))
  757. {
  758. handleMouseEvent (MouseInputSource::InputSourceType::touch, MouseInputSource::offscreenMousePos, modsToSend,
  759. MouseInputSource::invalidPressure, MouseInputSource::invalidOrientation, time, {}, touchIndex);
  760. if (! isValidPeer (this))
  761. return;
  762. }
  763. }
  764. }
  765. #if JUCE_HAS_IOS_POINTER_SUPPORT
  766. void UIViewComponentPeer::onHover (UIHoverGestureRecognizer* gesture)
  767. {
  768. auto pos = convertToPointFloat ([gesture locationInView: view]);
  769. juce_lastMousePos = pos + getBounds (true).getPosition().toFloat();
  770. handleMouseEvent (MouseInputSource::InputSourceType::touch,
  771. pos,
  772. ModifierKeys::currentModifiers,
  773. MouseInputSource::invalidPressure, MouseInputSource::invalidOrientation,
  774. UIViewComponentPeer::getMouseTime ([[NSProcessInfo processInfo] systemUptime]),
  775. {});
  776. }
  777. void UIViewComponentPeer::onScroll (UIPanGestureRecognizer* gesture)
  778. {
  779. const auto offset = [gesture translationInView: view];
  780. const auto scale = 0.5f / 256.0f;
  781. MouseWheelDetails details;
  782. details.deltaX = scale * (float) offset.x;
  783. details.deltaY = scale * (float) offset.y;
  784. details.isReversed = false;
  785. details.isSmooth = true;
  786. details.isInertial = false;
  787. handleMouseWheel (MouseInputSource::InputSourceType::touch,
  788. convertToPointFloat ([gesture locationInView: view]),
  789. UIViewComponentPeer::getMouseTime ([[NSProcessInfo processInfo] systemUptime]),
  790. details);
  791. }
  792. #endif
  793. //==============================================================================
  794. static UIViewComponentPeer* currentlyFocusedPeer = nullptr;
  795. void UIViewComponentPeer::viewFocusGain()
  796. {
  797. if (currentlyFocusedPeer != this)
  798. {
  799. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  800. currentlyFocusedPeer->handleFocusLoss();
  801. currentlyFocusedPeer = this;
  802. handleFocusGain();
  803. }
  804. }
  805. void UIViewComponentPeer::viewFocusLoss()
  806. {
  807. if (currentlyFocusedPeer == this)
  808. {
  809. currentlyFocusedPeer = nullptr;
  810. handleFocusLoss();
  811. }
  812. }
  813. bool UIViewComponentPeer::isFocused() const
  814. {
  815. if (isAppex)
  816. return true;
  817. return isSharedWindow ? this == currentlyFocusedPeer
  818. : (window != nil && [window isKeyWindow]);
  819. }
  820. void UIViewComponentPeer::grabFocus()
  821. {
  822. if (window != nil)
  823. {
  824. [window makeKeyWindow];
  825. viewFocusGain();
  826. }
  827. }
  828. void UIViewComponentPeer::textInputRequired (Point<int>, TextInputTarget&)
  829. {
  830. }
  831. static UIKeyboardType getUIKeyboardType (TextInputTarget::VirtualKeyboardType type) noexcept
  832. {
  833. switch (type)
  834. {
  835. case TextInputTarget::textKeyboard: return UIKeyboardTypeAlphabet;
  836. case TextInputTarget::numericKeyboard: return UIKeyboardTypeNumbersAndPunctuation;
  837. case TextInputTarget::decimalKeyboard: return UIKeyboardTypeNumbersAndPunctuation;
  838. case TextInputTarget::urlKeyboard: return UIKeyboardTypeURL;
  839. case TextInputTarget::emailAddressKeyboard: return UIKeyboardTypeEmailAddress;
  840. case TextInputTarget::phoneNumberKeyboard: return UIKeyboardTypePhonePad;
  841. default: jassertfalse; break;
  842. }
  843. return UIKeyboardTypeDefault;
  844. }
  845. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  846. {
  847. view->hiddenTextView.keyboardType = getUIKeyboardType (target->getKeyboardType());
  848. view->hiddenTextView.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  849. view->hiddenTextView.selectedRange = NSMakeRange ((NSUInteger) target->getHighlightedRegion().getStart(), 0);
  850. }
  851. BOOL UIViewComponentPeer::textViewReplaceCharacters (Range<int> range, const String& text)
  852. {
  853. if (auto* target = findCurrentTextInputTarget())
  854. {
  855. auto currentSelection = target->getHighlightedRegion();
  856. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  857. if (currentSelection.isEmpty())
  858. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  859. WeakReference<Component> deletionChecker (dynamic_cast<Component*> (target));
  860. if (text == "\r" || text == "\n" || text == "\r\n")
  861. handleKeyPress (KeyPress::returnKey, text[0]);
  862. else
  863. target->insertTextAtCaret (text);
  864. if (deletionChecker != nullptr)
  865. updateHiddenTextContent (target);
  866. }
  867. return NO;
  868. }
  869. void UIViewComponentPeer::globalFocusChanged (Component*)
  870. {
  871. if (auto* target = findCurrentTextInputTarget())
  872. {
  873. if (auto* comp = dynamic_cast<Component*> (target))
  874. {
  875. auto pos = component.getLocalPoint (comp, Point<int>());
  876. view->hiddenTextView.frame = CGRectMake (pos.x, pos.y, 0, 0);
  877. updateHiddenTextContent (target);
  878. [view->hiddenTextView becomeFirstResponder];
  879. }
  880. }
  881. else
  882. {
  883. [view->hiddenTextView resignFirstResponder];
  884. }
  885. }
  886. //==============================================================================
  887. void UIViewComponentPeer::drawRect (CGRect r)
  888. {
  889. if (r.size.width < 1.0f || r.size.height < 1.0f)
  890. return;
  891. CGContextRef cg = UIGraphicsGetCurrentContext();
  892. if (! component.isOpaque())
  893. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  894. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, getComponent().getHeight()));
  895. CoreGraphicsContext g (cg, getComponent().getHeight());
  896. insideDrawRect = true;
  897. handlePaint (g);
  898. insideDrawRect = false;
  899. }
  900. bool UIViewComponentPeer::canBecomeKeyWindow()
  901. {
  902. return (getStyleFlags() & juce::ComponentPeer::windowIgnoresKeyPresses) == 0;
  903. }
  904. //==============================================================================
  905. void Desktop::setKioskComponent (Component* kioskModeComp, bool enableOrDisable, bool /*allowMenusAndBars*/)
  906. {
  907. displays->refresh();
  908. if (auto* peer = kioskModeComp->getPeer())
  909. {
  910. if (auto* uiViewPeer = dynamic_cast<UIViewComponentPeer*> (peer))
  911. [uiViewPeer->controller setNeedsStatusBarAppearanceUpdate];
  912. peer->setFullScreen (enableOrDisable);
  913. }
  914. }
  915. void Desktop::allowedOrientationsChanged()
  916. {
  917. // if the current orientation isn't allowed anymore then switch orientations
  918. if (! isOrientationEnabled (getCurrentOrientation()))
  919. {
  920. auto newOrientation = [this]
  921. {
  922. for (auto orientation : { upright, upsideDown, rotatedClockwise, rotatedAntiClockwise })
  923. if (isOrientationEnabled (orientation))
  924. return orientation;
  925. // you need to support at least one orientation
  926. jassertfalse;
  927. return upright;
  928. }();
  929. NSNumber* value = [NSNumber numberWithInt: (int) Orientations::convertFromJuce (newOrientation)];
  930. [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
  931. [value release];
  932. }
  933. }
  934. //==============================================================================
  935. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  936. {
  937. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  938. (new AsyncRepaintMessage (this, area))->post();
  939. else
  940. [view setNeedsDisplayInRect: convertToCGRect (area)];
  941. }
  942. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  943. {
  944. }
  945. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  946. {
  947. return new UIViewComponentPeer (*this, styleFlags, (UIView*) windowToAttachTo);
  948. }
  949. //==============================================================================
  950. const int KeyPress::spaceKey = ' ';
  951. const int KeyPress::returnKey = 0x0d;
  952. const int KeyPress::escapeKey = 0x1b;
  953. const int KeyPress::backspaceKey = 0x7f;
  954. const int KeyPress::leftKey = 0x1000;
  955. const int KeyPress::rightKey = 0x1001;
  956. const int KeyPress::upKey = 0x1002;
  957. const int KeyPress::downKey = 0x1003;
  958. const int KeyPress::pageUpKey = 0x1004;
  959. const int KeyPress::pageDownKey = 0x1005;
  960. const int KeyPress::endKey = 0x1006;
  961. const int KeyPress::homeKey = 0x1007;
  962. const int KeyPress::deleteKey = 0x1008;
  963. const int KeyPress::insertKey = -1;
  964. const int KeyPress::tabKey = 9;
  965. const int KeyPress::F1Key = 0x2001;
  966. const int KeyPress::F2Key = 0x2002;
  967. const int KeyPress::F3Key = 0x2003;
  968. const int KeyPress::F4Key = 0x2004;
  969. const int KeyPress::F5Key = 0x2005;
  970. const int KeyPress::F6Key = 0x2006;
  971. const int KeyPress::F7Key = 0x2007;
  972. const int KeyPress::F8Key = 0x2008;
  973. const int KeyPress::F9Key = 0x2009;
  974. const int KeyPress::F10Key = 0x200a;
  975. const int KeyPress::F11Key = 0x200b;
  976. const int KeyPress::F12Key = 0x200c;
  977. const int KeyPress::F13Key = 0x200d;
  978. const int KeyPress::F14Key = 0x200e;
  979. const int KeyPress::F15Key = 0x200f;
  980. const int KeyPress::F16Key = 0x2010;
  981. const int KeyPress::F17Key = 0x2011;
  982. const int KeyPress::F18Key = 0x2012;
  983. const int KeyPress::F19Key = 0x2013;
  984. const int KeyPress::F20Key = 0x2014;
  985. const int KeyPress::F21Key = 0x2015;
  986. const int KeyPress::F22Key = 0x2016;
  987. const int KeyPress::F23Key = 0x2017;
  988. const int KeyPress::F24Key = 0x2018;
  989. const int KeyPress::F25Key = 0x2019;
  990. const int KeyPress::F26Key = 0x201a;
  991. const int KeyPress::F27Key = 0x201b;
  992. const int KeyPress::F28Key = 0x201c;
  993. const int KeyPress::F29Key = 0x201d;
  994. const int KeyPress::F30Key = 0x201e;
  995. const int KeyPress::F31Key = 0x201f;
  996. const int KeyPress::F32Key = 0x2020;
  997. const int KeyPress::F33Key = 0x2021;
  998. const int KeyPress::F34Key = 0x2022;
  999. const int KeyPress::F35Key = 0x2023;
  1000. const int KeyPress::numberPad0 = 0x30020;
  1001. const int KeyPress::numberPad1 = 0x30021;
  1002. const int KeyPress::numberPad2 = 0x30022;
  1003. const int KeyPress::numberPad3 = 0x30023;
  1004. const int KeyPress::numberPad4 = 0x30024;
  1005. const int KeyPress::numberPad5 = 0x30025;
  1006. const int KeyPress::numberPad6 = 0x30026;
  1007. const int KeyPress::numberPad7 = 0x30027;
  1008. const int KeyPress::numberPad8 = 0x30028;
  1009. const int KeyPress::numberPad9 = 0x30029;
  1010. const int KeyPress::numberPadAdd = 0x3002a;
  1011. const int KeyPress::numberPadSubtract = 0x3002b;
  1012. const int KeyPress::numberPadMultiply = 0x3002c;
  1013. const int KeyPress::numberPadDivide = 0x3002d;
  1014. const int KeyPress::numberPadSeparator = 0x3002e;
  1015. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  1016. const int KeyPress::numberPadEquals = 0x30030;
  1017. const int KeyPress::numberPadDelete = 0x30031;
  1018. const int KeyPress::playKey = 0x30000;
  1019. const int KeyPress::stopKey = 0x30001;
  1020. const int KeyPress::fastForwardKey = 0x30002;
  1021. const int KeyPress::rewindKey = 0x30003;
  1022. } // namespace juce