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.

1208 lines
40KB

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