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.

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