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.

1143 lines
38KB

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