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.

1231 lines
41KB

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