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.

1301 lines
43KB

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