Audio plugin host https://kx.studio/carla
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.

1234 lines
41KB

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