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.

1100 lines
36KB

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