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.

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