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.

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