The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1186 lines
40KB

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